Calculating $\lim_{n\to\infty}\left(2^n+n2^n\sin^2{\frac{n}{2}}\right)^{\left(\frac{1}{2n-n\cos{\frac{1}{n}}}\right)}$

Question: I was looking up to some previous papers of a competitive exam when I found the following problem:
$$\lim_{n\to\infty}\left(2^n+n\cdot2^n\sin^2{\frac{n}{2}}\right)^{\left(\frac{1}{2n-n\cos{\frac{1}{n}}}\right)}$$
I proceeded as follows:
$$\require{cancel}\lim_{n\to\infty}\left(2^n+n\cdot2^n\sin^2{\frac{n}{2}}\right)^{\left(\frac{1}{2n-n\cos{\frac{1}{n}}}\right)}\\
=\lim_{n\to\infty}2^\left(\frac{1}{2-\cos{\frac{1}{n}}}\right)\cdot\lim_{n\to\infty}\left(1+n\cdot\sin^2{\frac{n}{2}}\right)^{\left(\frac{1}{2n-n\cos{\frac{1}{n}}}\right)}\\
=\cancelto{2^1=2}{\lim_{n\to\infty}2^\left(\frac{1}{2-\cos{\frac{1}{n}}}\right)}\cdot\lim_{n\to\infty}\left(1+n\cdot\sin^2{\frac{n}{2}}\right)^{\left(\frac{1}{2n-n\cos{\frac{1}{n}}}\right)}\\
=2\cdot\lim_{n\to\infty}\left(1+n\cdot\sin^2{\frac{n}{2}}\right)^{\left(\frac{1}{2n-n\cos{\frac{1}{n}}}\right)}$$
After this step, my intuition was that the answer is $2$ as this was an integer-only answer type question. But, I cannot seem to proceed after this step. I did apply the L'hospital method after this, but, I didn't go far. A little bit of hint/help would be very kind.
P.S.: WolframAlpha did confirm my intuition (see here).
Comment: Can you please clarify how did you arrive at the last step from the second last?
Comment: @RamanujanXV I tried to use the $1^\infty$ form. However, I made a mistake here, as DatBoi mentioned in his answer below. I'll edit and cut out that part from the question...
Answer: Your method is incorrect since
$$\lim_{n\to\infty}1+n\cdot\sin^2{\frac{n}{2}}\ne 1$$
So you cannot possibly use the $1^{\infty}$ form
To solve the limit we can use logarithms
$$L=\lim_{n\to\infty}\left(1+n\cdot\sin^2{\frac{n}{2}}\right)^{\left(\frac{1}
{2n-n\cos{\frac{1}{n}}}\right)}$$
$$\ln L=\lim_{n\to\infty}\frac{\ln\left(1+n\cdot\sin^2{\frac{n}{2}}\right)}{{2n-n\cos{\frac{1}{n}}}}=\lim_{n\to\infty}\frac{\ln\left(1+n\cdot\sin^2{\frac{n}{2}}\right)}{n}$$
Since $\sin^2x\in [0,1]$
$$\lim_{n\to\infty}\frac{\ln\left(1\right)}{n}\le\lim_{n\to\infty}\frac{\ln\left(1+n\cdot\sin^2{\frac{n}{2}}\right)}{n}\le\lim_{n\to\infty}\frac{\ln\left(1+n\right)}{n}$$
$$0\le\ln L\le0$$
Therefore the limit is indeed $2$
Comment: @DeBARtha $\lim_{n\to\infty}\cos(\frac{1}{n})$ takes a specific value that doesnt affect the $n$ thats multiplied with it
Comment: I didn't quite get the fact how you managed to derive $n$ in the denominator. Can you clarify that once pls?
Comment: @DeBARtha $\lim_{n\to\infty}\cos(\frac{1}{n})=?$
Comment: But there's a $2n$ in the denominator also, and $\cos\frac{1}{n}$ has $n$ multiplied to it. Won't that change also?
Answer: look on the parts.
(2-cos1/n)n -> (2-cos0) n= (2-1)n = n
so  the power is just 1/n
(2^n) ^1/n =2
1 <= (1+n*sin^2(n/2))^1/n <= (1+n)^1/n=1 ( * )
( * ) in detail is when you write (*) = e^(ln(1+n)/n) then apply Lopetals rule, bottom wins and you ver e^0 = 1
so the answer is 2*1 = 2
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Multiple ways to provide similar functionality in a text editor

Question: I am working on a text editor (web app) which will provide powerful, customizable functionality, but in a minimal (requirement) appearance.
One of the functions is: "create new snippet". I want this function to be applicable to either:

a chunk of selected text inside the current document, meaning that a new snippet will be created containing the selected text
the whole text, meaning that a new snippet will be created containing the whole text contained in the current document
empty content, meaning that an empty new snippet will be created

I have a few other functions that need similar behavior (regarding applicability to selected text, to the whole document, and/or to empty content), so, I really need a smart, minimal, coherent solution to this.
My question is: What kind of UI interface should I provide to satisfy the aforementioned requirements, in the most intuitive and frictionless way possible?
Some of the solutions I am considering (but I am not totally happy with):

When a user selects (highlights) some text, a toolbar pops up (similar to medium.com's one) showing the applicable actions to the selected text (in the form of labelled icons). The user then clicks on the "create snippet" labelled icon and a new snippet is created containing the selected text. If the user simply clicks inside the text without selecting any text and without the intention to change the caret position, (i.e. she clicks on the caret once), the aforementioned toolbar pops up, but when the user clicks on the "create snippet" labelled icon, an empty snippet will be created. In order to create a new snippet containing the whole text, a user simply selects all the text of the document.
(This solution, obviously, tries to use the pop up toolbar as the only interface through which the user will communicate her intentions, AKA: uber minimal, which is a plus)
Same as above, but, without allowing toolbar pop up when a user simply clicks inside the text. In order to provide the "create empty snippet" functionality, provide a labelled "create snippet" icon in a hideable sidebar. (This solution provides two interfaces for serving different needs: a pop up toolbar and a sidebar)
Do not provide a toolbar that pops up upon text selection at all. Instead, only provide an icon labelled "mark snippet" in the hideable sidebar, that when clicked, it will change the cursor icon to a new one, indicating that the user must select which part of the text should be. There will also be another icon labelled "create new snippet", which will create a new empty snippet. (This solution uses the sidebar as the only interface through which the user will communicate her intentions)

What would your suggestion be?
Please don't focus too much on the "snippet" concept. I need other functionalities as well, such as: "share a part, or the whole of the text" on social media, etc.
Note: I really like the pop up toolbar (medium.com style) because it is minimal (i.e. doesn't clutter the editor window by being visible all the time) and also it is quick, because it appears very close to where the user's mouse pointer is located. Its drawback is probably the fact that new users might miss it (and users have very little patience with discovering the functionality of something new).
Comment: If the feature is a core function then you could have persistent buttons in the UI for all of these features. Context menus can be added to make the features more efficient for more advanced users. But it all depends on what problem you're trying to solve
Comment: Thank you Lewis. Yes, those features I'm talking about are core functionalities. Do you think it is good practice to provide the same functionality through two different paths?

I am also wondering if there is any successful paradigm where core functionality is offered through context menus in an obvious-to-the-user way...
Answer: Have it be based on selected text.

No selection = new snippet
all selected = snippet with everything
selected segment = snippet with selected segment

You can provide a selector by hijacking the right click functionality to provide the menu, or simply provide it on hover.  You should always have at least 2 means of accomplishing a task depending on the UI paradigms your user base is used to.  If it is a core feature, then there is precedent for it to be available on a menu bar or similar.
While a minimal UI is ideal, never forget that affordability is also desired.  You never want your design to be so minimal that the affordances of your application are lost.


How to model a class that is a collection of individuals of another class in Protege

Question: I need to model following example in Protege:
Suppose I have a class, Pride, which represents a collection of instances of another class, Lion. Is there any other way to do this without use of user defined object property with minimum cardinality?
Furthermore, if a lion has color "Yellow" and is a member of a pride, then the reasoner should infer that the pride has color "Yellow". Is there any other to do this without defining a set of SWRL rules ?
Comment: You mean that an *instance* of Pride represents a collection of *instances* of Lion, right?
Answer:
Is there any other way to do this without use of user defined object
  property with minimum cardinality?

You will  need to define some sort of membership property.  It can be generic (e.g., hasMember), or more specific to the particular type (e.g., hasLion), but you'll need to define something to relate the collection to its instances.  You do not required to use any cardinality axioms here, though you might want to say something like (Pride ⊑ ≥ hasMember 2).

Furthermore, if a lion has color "Yellow" and is a member of a pride, then the reasoner should infer that the pride has color "Yellow". Is
  there any other to do this without defining a set of SWRL rules ?

To make the properties of the members transfer to the collection, you don't have to use SWRL rules.  You can use subproperty chain axioms. (You will need to do this for each property that you want to transfer over, though.)  For instance, to express the fact that:
        If a lion has color X and is a member of pride, then the pride has color X.
You can use the axiom:
        hasMember • hasColor ⊑ hasColor
That means that whenever you have data like:
        P →hasMember L →hasColor C
you can infer
        P →hasColor C
For more on how that works, see Using Property Chains to get inferred Knowledge in an OWL Ontology(Protege).
Comment: Hey Joshua..Thanks for the help...I am facing another problem in Jena regarding rules..Can you pls go through this question...http://stackoverflow.com/questions/30297919/specifying-class-equivalence-in-jena-rules


Information Architecture and Navigation

Question: The Main Screens of an application are listed in the main navigation. When a user goes to one of these screens they have the ability to open the navigation and get to another Main Screen.
If a user clicks on a piece of content on a Main Screen, they have the ability to then navigation 'back' to the Main Screen they came from. For iOS you will see a Back button in the upper right and for Android you will have the 'Up Button'.
For the purposes of this question, we are using a hamburger menu for our main navigation:
My question is what if you have a call-to-action on the Home Screen to immediately jump to one of the Main Screen. Do you have a 'Back Button' to bring the user back to the Home Screen, or keep the main navigation in the upper left corner and let the user choose where they wan to go next?
Thank you for any thoughts on this.
Comment: I don't really understand the setup. In IA terms, the hamburger usually reveals the 'hub' in a 'hub and spokes' navigation structure. As such, the menu revealed by the hamburger is, in essence, the 'home screen'. I fail to think of a mobile app that has both hamburger menu and a home screen. Or do I misunderstand what 'home screen' mean?
Answer: Imagine it was a website. What would happen in when a user clicked the back button? That's what a "back" link should do.
If you want to move the user higher up in a page hierachy then make that clear.
Comment: I disagree, in a mobile application you have top level screens a user will get to from the Navigation.  Then you have sub-level screens a user gets to from those top level, such as an article.  The navigation appears on the top level but not on the sub-level screens.  So you can't act like its a website.
Comment: My point was to make the intent of the button clear. If the user understands the button to be a back button then it should behave as a back button which is a well understood pattern. If the context of the button in an OS makes it clear that it's an "up" button then the button should behave like that.

If I've misunderstood you and you're saying that when a user taps a "back" button they should go to a mid-level hierarchy page they've not seen before, then I think that'd be very confusing.

Information Architecture and Navigation


instagram api rails hidden token in heroku

Question: I want to upload my api to heroku, what I want is that the token is hidden for possible hakers.This code is in ruby on rails app / assets / application.js This is my code
   var token = "MYTOKEN",
      userid =  MYUSERID,
      num_photos = 4;

    $(document).ready(function() {

    $.ajax({
        url: 'https://api.instagram.com/v1/users/' + userid + '/media/recent/?access_token=' + token,
        dataType: 'jsonp',
        type: 'GET',
        data: {access_token: token, count: num_photos},
        success: function(data){
            console.log(data);
            for( x in data.data ){
                $("#container").append('

');
            }
        },
        error: function(data){
            console.log(data);
        }
    });
    });

Answer: Store the token in an environment variable which your rails app can then access and pass to the view. There are gems such as dotenv that can help you manage access to them locally. This article explains how to configure your variables in heroku.


Getting probability density graph & k-means clustering with 300 million rows

Question: The DBMS I use is MySQL(MariaDB).
The table scheme is as below:
CREATE TABLE MyTable (
ID     INT     PRIMARY KEY,
TEXT   VARCHAR(200),
VALUE  DECIMAL(15,2) )

The table has 300 million rows or more.
I'd like to get the result from the following two processes by extracting values from the texts(For example, SELECT VALUE FROM MyTable WHEN TEXT LIKE '%any keywords%'; SQL) (Results to be displayed on the web)

To draw probability density graph
To cluster values by using K-Means Algorithm

Is it possible to obtain the results above only by using SQL? If so, how is the performance? (the required response time is less than 2 seconds) If not, could you recommend better way?
If there are 10 data nodes with the combination of NoSQL and Mahout, is it possible to get the result from each query within 2 seconds especially when there are 5 queries per second? If not, how many data nodes are required?
So, please recommand me the system architecture if you know any solution to the trouble I've currently run into.
Comment: Queries with `LIKE '%...'` can't use an index and will performance poorly. You may look into the [fulltext functions](https://dev.mysql.com/doc/refman/5.6/en/fulltext-search.html) instead.
Comment: Thanks @VMai . I just wanted to give you an example how I filter the records. It helped anyway.
Answer: This is a bit long for a comment.
Your expectations are a bit extreme.  It would might be possible to meet the requirements, using a lot of custom code and systems with lots of processors and lots of memory.
First, you don't seem to understand how k-means works.  What is the distance metric?
Second, you don't explain why you need to re-cluster the records for each query.  Typically, clustering is more of an offline activity and scoring (or assigning clusters) is online.
Finally, I wouldn't recommend k-means clustering on raw text.  There are other algorithms for clustering text that could very well be more appropriate for your actual problem.  I would suggest you learn a bit about data mining (What is the k-means algorithm?  What is it useful?  What is expectation-maximization clustering?  What is singular value decomposition?)  I would also suggest that you learn about text analysis (What is tokenization?  What is stemming?  What are bag-of-words approaches?  What is semantic analysis?).  Your question betrays a lack of understanding of both these subjects.
Comment: @KeithPark . . . Clustering along one dimension is often overkill.  It sounds like a reasonable solution would be to break the range into centiles and just do a histogram within each centile.  That can make a respectable picture too.
Comment: Thank you for your comment.
What I need to cluster is just using one parameter (Please refer 'VALUE' colomn above.)
As it has one demension, distance matric will be abs(value-value).
Probably, I made a mistake to deliver what I meant. I didn't mean that I'm going to cluster texts. just numeric values.
Comment: That is a great idea. That's one of reason why I asked that I want to get probability density graph. Data would be concentrated to 3~5 clusters. but the problem is that each cluster will be along norminal distribution. and can be overlapped.


Create boolean list based on index ranges in python

Question: For some reason I am trying to create a boolean list of given length with the default False. Furthermore I know the index range(s) to be set to True.
I have to do that several times and for readability dont want to write out every list manually (neither with 0 and 1 and convert it), but write the actual index ranges, e.g. range(2, 5).
I would like to have one-liner for every variable, but I simply do not seem to be able to get this done.
index_length = 10
raw = [False] * index_length
# raw = np.array(raw)
var1 = [
  list(range(2,5)) + list(range(6,9)),
  list(range(0, 9),
  [],
]

Iterating through var1 should result in a new variable var2 as stated below, whereas the elements can either be binary integer or boolean values.
var2 = [
  [0, 0, 1, 1, 1, 0, 1, 1, 1, 0],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],

I dont need a function which iterates through every element of the sublists of var1, but something like this.
var2 = [None] * len(var1)
for idx  in var1:
  var2[idx] = ...

I thought there must be some list comprehension or something, but I failed for quite some time now. I tried using the raw list/numpy array but couldnt assign it to var2 and edit the boolean values in one line
Maybe it is so easy I dont see it, maybe it is not possible at all, maybe python is not designed to do that but Id like to try anyways.
PS: I have spent that much time on it now, that I cant tell if my question explains my problem well, if not I am sorry in advance.
Answer: You can convert each sub-list in var1 to a set, so that you can iterate an index through the range of index_length to efficiently test if the current index is in the set:
[[i in s for i in range(index_length)] for s in map(set, var1)]

This returns:
[[False, False, True, True, True, False, True, True, True, False],
 [True, True, True, True, True, True, True, True, True, False],
 [False, False, False, False, False, False, False, False, False, False]]

Note that the expected output in your question has unnecessary values at index 0 and 6 in each sub-list, which are presumed to be typos on your part.
Comment: thank you, truth values with `in` was exactly what I had in mind...somewhere hidden deep in my mind.
You are right my expected output is wrong (in addition of being to long), even though I dont agree with your stated indices entirely. Anyways, your output is right and I edited mine.


Trying to join two function returns in Angular.js or JavaScript

Question: I have the following Angular controller. I want to take items from both x and y variables and show them on the web page. Right now, the web page only shows items from the y variable. I try to use .push() to put the two function result sets together into the PremByClass array. Any help or direction on how to do this would be greatly appreciated.
app.controller('PremByClass', ['$scope', '$http', 'policyApi', 'lookupApi', function ($scope, $http, policyApi, lookupApi) {
    $scope.model = {};
    $scope.load.then(function () {
        function formatDate(value) {
            return value.getMonth() + 1 + "-" + value.getDate() + "-" + value.getFullYear();
        }
        $scope.PremByClass = [];
        policyApi.policy.get().then(function (t) {
            if (t) {
                policyApi.class.get().then(function (x) {
                    if (x) {
                        //Put x into $scope.PremByClass
                        $scope.PremByClass.push(x);
                        var dtEff = formatDate(t.DateEffective);
                        for (var i = 0, e = null; e = x[i]; i++) {
                            lookupApi.WCClassDesc.get(e.GovState, e.classCode, e.DescCode, dtEff).then(function (y) {
                                //This seems to wrok correctly however it seems that $scope.PremByClass forgets about x
                                //The web page only shows stuff from y
                                $scope.PremByClass.push(y);
                            })
                        }
                    }
                })
            }
        })
    });
}]);

Answer: As it seems that your x variable is an array, I guess you should be showing it in your page as a list or table of objects with something like :

    {{item.GovState}} // {{item.classCode}}

I used the index 0 on PremByClass because your x variable is the first item you push into the PremByClass array. Although, I would make that part of the code more maintainable by setting the x variable into a more meaningful scope property.
You could replace this line in your controller:
$scope.PremByClass.push(x);

with this line:
$scope.policies = x;

and then simply rewrite your ng-repeat block to use policies:

    {{item.GovState}} // {{item.classCode}}

the variable/array PremByClass would then contain only results from your lookupApi.WCClassDesc service or factory and you should be able to render them on screen using the same ng-repeat code as above simply replacing policies with PremByClass.


Form Validation and HTTP Exception

Question: A form is submitted using jQuery form plug-in to an action in MVC framework. In the action, if form validation fails a reply should be sent back to the client. jQuery form plug-in comes with error and success callbacks (like any other jQuery Ajax functions).
Isnt it a better practice to return an HTTP Exception with error-code 400 (Bad Request) and catch it in error callback rather than returning a successful HTTP response and catching it in success callback?
If the answer is yes, wouldn't it be more descriptive to have data attached to HTTP Exception?
From what I see right now, HTTPException.Data is readonly. One of the constructors seems to do the job (HttpException(SerializationInfo, StreamingContext)) but I cant wrap my head around it.
Would someone please explain for me how to add data to HTTP Exception?
Answer: No, it's not better practice to simply return an error code, even if you do manage to attach messages to the HTTPException.
Why?  Well, you lose so much information that way.  You have the option to return an arbitrary JSON object, which could include (for example) a list of all validation errors (or indeed, any pertinent info which may help the calling client out), which you then render on the client so that the user is able to correct.
Also, you've got to consider what happens when your call is successful.  Is a 200 return code really enough for your purposes?
Comment: I feel you're misunderstanding the point of an HttpException. It is used to describe an exception that occurred during the _processing_ of an HTTP request. Your request is processing fine, hence you should return 200 OK. Your form failing to validate is an entirely different aspect. You'd be misappropriating the HttpException class.
Comment: The Http Response code is what confuses me. Correct me if I am wrong but what I understand from 200 is that the request is processed successfully. I mean if there is an error function call back isn't it better to make a good use of it?
Comment: It's not an HTTP exception that you're trying to report. It's a form validation error. So as Paul implies return HTTP OK, but include data in your HTTP response pertaining to the validation error. Look at MVC's JsonResult which inherits ActionResult.
Comment: Whether your data is valid or not, it's better for your endpoint to complete successfully, return a 200 and include data which indicates why validation failed.
Comment: @tomtroughton: Thanks for the advice, but my problem is more philosophical in nature. Isn't it better to use `HttpException`, considering the fact that error callbacks will be called if and only if an exception happens?
Comment: I found this [here](http://stackoverflow.com/questions/6639931/asp-net-mvc-httpexception-message-not-shown-on-client). "if you want to access strings and stuff you should return JSON objects and not throw any exceptions. You should choose which of two you want: either a fully RESTFul API in which the status code is sufficient and allows you to imply the errors message or return JSON objects. – Darin Dimitrov"

Form Validation and HTTP Exception


What's up with Outlaw's Den?

Question: I've visited Outlaw's Den on Tatooine. It's an open PvP area and according to an article I've found from before the release, it should contain rare gathering nodes and also chests containing commendations.
The place contains no such thing. I didn't find any chests there or gathering nodes. Why is that? Is there any reason to go there now or in the future? (Other than visiting the only GTM kiosk on the planet, while fearing that you are going to be killed while trading.)
Comment: It would seem that the devs nerfed it: http://www.swtor.com/de/community/showthread.php?t=98999 Dx
Comment: Maybe someone already mined them up / looted the chest? I imagine "rare gathering nodes" and "chests containing commendations" to be somewhat rare and in high demand.
Comment: @Resorath, I doubt that. The area was mostly deserted and I didn't see gathering node of any type whatsoever. Clearing all of them would require cooperation between several people, who weren't anywhere nearby (or were hidden).
Answer: OLD:
Per the link (provided by Krazer) to the official forums:

Amending the patch notes: The chests containing commendations and
  credits in Outlaw's Den have had their respawn timer increased
  dramatically or respawn at a speed correspondent to the amount of
  players in Outlaw's Den.
EDIT: Actually these chests have been removed entirely as well as all
  resource nodes from Outlaw's Den and Ilum.

This apparently was done because of players exploiting the area to grab more high-end resources than the devs were expecting.
Hopefully, they will fix the previous system's exploits and reintroduce loot to the area. But yes, for now the area is only for your own PvP fun. No in-game loot rewards are available in that area at this time.
NEW UPDATE:
As Raven Dreamer pointed out, as of the 1.1 patch released on Jan 18, 2012, the Outlaws' Den (Tatooine) Chests containing Mercenary Commendations are available again.
I have confirmed they do spawn again as of the 1.1 patch. They spawn one at a time. I'm not sure of the exact respawn rate, since there are a handful of easily found spawn locations, but it's around 10 minutes from what I can tell.
They provide a handful of credits and 20 Mercenary Commendations. Probably a random loot item too from time to time.
Comment: As of the 1.1 patch; `The Outlaws' Den (Tatooine)

Chests containing Mercenary Commendations are now available again in the Outlaw's Den.`
Answer: I still farm three chest in Outlaw Den each day. When I land on the planet I check WHO. If there are any lvl 50s then figure the chest are already looted and come back the next day. I still get parts of the gear set, weapons, and commendations.

What's up with Outlaw's Den?


Python disregarding zeros when sorting numbers in a list

Question: I'm trying to sort a list of dollar amounts from lowest to highest using python's built in sort ability, but when I call on it, it sorts the numbers super screwy. It starts at $10,000 then goes up to $19,0000 (which is the highest) then jumps down to $2,000 and counts up from there ostensibly because 2 is bigger than 1. I don't know how to correct for this. The code I've used is below.
numbers=[['$10014.710000000001'], ['$10014.83'],['$11853.300000000001'],
['$19060.010000000006'],['$2159.1099999999997'],['$3411.1400000000003']]

print(sorted(numbers))

Comment: Possible duplicate of [How to sort a list numerically?](https://stackoverflow.com/questions/3426108/how-to-sort-a-list-numerically)
Comment: its because your "numbers" are not numbers and poor python has to Lexicographical sort the strings. want numerical sort, you'd need to temporarily convert to numbers for sorting.
Comment: Possible duplicate of https://stackoverflow.com/questions/3426108/how-to-sort-a-list-numerically.
Answer: You are not sorting numbers but strings, which explains the "weird" result. Instead, change your type to float and sort the resulting list:
In [3]: sorted([[float(el[0][1:])] for el in numbers])
Out[3]:
[[2159.1099999999997],
 [3411.1400000000003],
 [10014.710000000001],
 [10014.83],
 [11853.300000000001],
 [19060.010000000006]]

I need the el[0] because every number is inside its own list, which is not a good style, but I guess you have your reasons for this. The [1:] strips away the $ sign.
EDIT really good point made in the comments. More robust solution:
from decimal import Decimal

import decimal

decimal.getcontext().prec = 4

sorted([Decimal(el[0][1:]) for el in numbers])
Out[8]:
[Decimal('2159.1099999999997'),
 Decimal('3411.1400000000003'),
 Decimal('10014.710000000001'),
 Decimal('10014.83'),
 Decimal('11853.300000000001'),
 Decimal('19060.010000000006')]

Comment: Don't use `float` for currency values!
Comment: Yes, the list within a list formatting is due to some other functions I have to perform with the data. Thanks for your inputs!
Comment: If you don't want this kind of encapsulation in the sorted list, just change `sorted([[float(el[0][1:])] for el in numbers])` to `sorted([float(el[0][1:]) for el in numbers])` :)
Answer: Your numbers are currency values. So as pointed out in the comments below, it might make sense to use Python's decimal module which offers several advantages over the float datatype. (See link for further information.)

If, however, this is only an exercise for better getting to know Python, as I suspect. You might look for a simpler solution:
The reason, why your sorting doesn't work, is because your numbers are stored in the list inside another list as a string. You have to convert them to integers or floats before sorting has the effect you're looking for:
numbers=[
    ['$10014.710000000001'],
    ['$10014.83'],
    ['$11853.300000000001'],
    ['$19060.010000000006'],
    ['$2159.1099999999997'],
    ['$3411.1400000000003']
]

numbers_float = [float(number[0][1:]) for number in numbers]
numbers_float.sort()

print(numbers_float)

Which prints:
[2159.1099999999997, 3411.1400000000003, 10014.710000000001, 10014.83, 11853.300000000001, 19060.010000000006]

When you look at float(number[0][1:]), then [0] takes the first (and only) number of your (inner) number list, [1:] strips the $ sign and finally float does the conversion to floating point number.
If you want the $ sign back:
for number in numbers_float:
    print("${}".format(number))

Which prints:
$2159.1099999999997
$3411.1400000000003
$10014.710000000001
$10014.83
$11853.300000000001
$19060.010000000006

Comment: Okay, that makes sense. I'll give that a shot. Thanks very much!
Comment: Don't use `float` for currency values, since it doesn't round the same way decimal numbers round. You probably want to use the `decimal` module instead.
Comment: @DanielPryden I highly suspect that this is not necessary here but you're definitely right to mention it. Doesn't hurt, so I added it to the answer as a disclaimer.
Answer: The key insight here is that the values in your list are actually strings, and strings are compared lexically: each character in the string is compared one at a time until the first non-matching character. So "aa" sorts before "ab", but that also means that "a1000" sorts before "a2". If you want to sort in a different way, you need to tell the sort method (or the sorted function) what it is you want to sort by.
In this case, you probably should use the decimal module. And you want the key attribute of the sort method. This will sort the existing list you have, only using the converted values during the sorting process.
import decimal

def extract_sortable_value(value):
    # value is a list, so take the first element
    first_value = value[0]
    return decimal.Decimal(first_value.lstrip('$'))

numbers.sort(key=extract_sortable_value)

Equivalently, you could do:
print(sorted(numbers, key=extract_sortable_value))

Demo: https://repl.it/repls/MiserableDarkPatches


how to use BitmapFactory.decodeFile() to get the Bitmap

Question: i am trying to download image from internet in original quality. then trying to BitmapFactory.decodeFile() to get the Bitmap
to perform this task i tried this but i am getting this error:
The method decodeFile(String) in the type BitmapFactory is not applicable for the arguments (FileOutputStream)
code:
public void saveImageToSDCard(Bitmap bitmap) {
        String dirname = "/Amazing Wallpapers/";

        File myDir = new File(Environment.getExternalStorageDirectory()
                .getPath() + dirname);

        myDir.mkdirs();
        String str = currentUrl.substring(currentUrl.lastIndexOf('/') + 1,
                currentUrl.length());

        String fname = "Wallpaper-" + str + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists())
            file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap = BitmapFactory.decodeFile(out);
            out.flush();
            out.close();
            Toast.makeText(
                    _context,
                    _context.getString(R.string.toast_saved).replace("#",
                            "\"" + pref.getGalleryName() + "\""),
                    Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Wallpaper saved to:" + file.getAbsolutePath());

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(_context,
                    _context.getString(R.string.toast_saved_failed),
                    Toast.LENGTH_SHORT).show();
        }
    }

Answer: You should pass the file name to the function BitmapFactory.decodeFile()instead of the output stream


Average number of $U[0,1]$ random numbers to reach $x$

Question: Let $P(x)$ be a random process where you keep selecting random numbers, uniformly distributed between 0 and 1, until the sum reaches $x$.
From memory, the expected value of the number of terms needed by $P(x)$ is $e^x Q(x)$, where $Q(x)$ is a piecewise polynomial whose degree increases at each integer value of $x$.  If I remember, it was
$$Q(x) = \sum_{k=0}^{\lfloor x\rfloor} (-1)^k\frac{(x-k)^k}{(k+1)!}$$
My question is: This formula numerically gives $(2/3)+2x$ plus exponentially decaying but oscillating terms.  How do you go from $e^x Q(x)$ to $2/3 + 2x$ plus exponentially decaying terms?
Comment: See Byron's answer [there](http://math.stackexchange.com/a/198790/).
Comment: [Also answered on MathOverflow](http://mathoverflow.net/q/10567).
Answer:
Short version: do not use the formula for $Q(x)$.

Long version: let $U$ denote the first random number, then, conditionally on $U$, the mean number of draws needed to overcome $x$ is $1$ if $x\leqslant U$ and distributed like $1+P(x-U)$ otherwise. Thus,
$$
P(x)=1+E(P((x-U)^+))=1+\int_{(x-1)^+}^xP(t)\mathrm dt.
$$
The Laplace transform is
$$
L(s)=\int_0^{+\infty}\mathrm e^{-sx}P(x)\mathrm dx.
$$
Massaging the identity involving $P$ yields
$$
L(s)=\frac1{s-1+\mathrm e^{-s}}=\frac2{s^2}+\frac2{3s}+O(1),
$$
when $s\to0$. Since $P$ is monotonous, the $\frac2{s^2}$ term implies that $P(x)=2x+o(x)$, and a little more work is needed to show that the $\frac2{3s}$ term implies that $P(x)-2x\to\frac23$.
Comment: Thankyou, it's a little while since I did Laplace transforms, but I'll work through it.


Mysql keyword in command executed from a shell script

Question: I already know that in order to make Mysql understands a keyword as a column name we should add back ticks.
I am trying to execute this command from a shell script
echo "ALTER TABLE   partners.partners CHANGE COLUMN `name` `client_name` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL" | $MYSQL

Where $MYSQL is my databse connection command (which works fine for other commands).
What I am trying to do is rename the colomn named name to client_name but I have got this error :
 ./test_script.sh: 1: ./test_script.sh: name: not found

If I log to mysql console , execute the same thing , It works perfectly
Any one run into this problem before ?
Comment: Try escaping the backticks (IE: \\`name\\`). I think the backticks are being evaluated as shell commands - http://unix.stackexchange.com/questions/27428/what-does-backquote-backtick-mean-in-bash
Answer: Use single quotes to avoid interpretation of back-tick or ` which is otherwise used for command substitution:
$MYSQL -e 'ALTER TABLE partners.partners CHANGE COLUMN `name` `client_name` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL'

Comment: That should've been my first reflex ! It is exactly that


How to formally prove that $\gcd(a,1) = 1$ when $a \in Z$

Question: I was trying to prove that $$\gcd(2a+1,9a+4) = 1 , a\in Z$$
My proof went like this:
$$ (9a+4) = 4(2a+1) + a$$
$$ (2a+1) = 2(a) + 1 $$
$$ \Rightarrow \gcd(9a+4,2a+1) = \gcd(2a+1,a)=\gcd(a,1) = 1$$
The last line of reasoning seems intuitive for me; The greatest common divisor of any integer with 1 is definitely one because the only divisor of 1 is itself. However, the question of how to prove it formally arose.
Thanks for any suggestions!
Comment: $\gcd(1,b) = 1\,$ by $\,a=1\,$ in the linled dupe. $\ \ $
Answer: The formal definition for the greatest common divisor function is:
$$\gcd(n,m)=\max\{d\in\mathbb{N}:d\mid n \,\wedge\,d\mid m\}.$$
Set $m=1$. The only number $d$ that satisfies $d\mid n$ and $d\mid1$ is $1$. So we have
$$\gcd(n,1)=\max\{1\}=1.$$
Answer: Let $D_a$ be the set of divisors of $a$. Note that $-1, 1 \in D_a$. On the other hand, $D_1 = \{\pm 1\}$.
Thus, $D_a \cap D_1 = \{\pm 1\}$. By definition, the gcd is the largest element in this (finite) set. Since $-1 < 1$, we get $\gcd(a, 1) = 1$.

If your definition works with positive integers, then just remove $-1$ everywhere from the above argument.

Some also define $\gcd(a, b)$ (where at least one of $a$ or $b$ is non-zero) to be the smallest positive element in $$S_{a, b} = \{am + bn : m, n \in \Bbb Z\} \subset \Bbb Z.$$
With this definition, it is clear that $\gcd(a, 1) \ge 1$ (since $1$ is the smallest positive integer).
On the other, $1 \in S_{a, 1}$ since $1 = a\cdot0 + 1\cdot1$ and thus, $1 \ge \gcd(a, 1)$.
Again, we get $\gcd(a, 1) = 1$.

Note that all the above arguments are also valid if $a = 0$.
Answer: using Euclid's Lemma, GCD (a,b) = GCD(a,a-b), , You can continue like this ,by subtracting smaller number from larger number.

${(2a+1 , (9a+4-2a-1))=(2a+1,7a+3)...  (a,a-1)=1}$

-|  but there is a faster way to do this.

${ GCD(2a+1,9a+4)= (2a+1, 4(2a+1)+a)= (2a+1,a)= (a,2a+1)=(1,a)=1 }$
Comment: How does this answer the OP's question? He wants to prove the last equality formally.


Variance of Poisson distribution multiplied by a constant

Question: Assume I have a Poisson distribution $x=Poisson(X)$. It is clear that the mean and the variance will be equal to X.
In the case we have of  $B *Poisson(X)$ being B a constant, I would like to see a small proof showing why the variance is $B^2*X$ and the mean is $B*X$
Many thanks!! :)
Comment: Just a remark on your notation. Most probability textbooks use capital letters such as $X,Y,Z$ to denote random variables, small letters $x,y,z,a,b,c, \dots$ to denote real numbers / constants, and sometimes greek letters $\alpha, \beta, \gamma, \dots$ to denote the parameters of given probability distributions.

Using $X$ to denote the parameter of the poisson distribution is perhaps not the best choice of notation. More commonly you would see $X \sim Poisson(\lambda)$, when $X$ has a poisson distribution.
Answer: Hint: Makes use of the rules $\operatorname{E}[aX]=a\operatorname{E}[X]$ and $\operatorname{Var}(aX)=a^2\operatorname{Var}(X)$.
Where $X$ is a random variable and $a \in \mathbb{R}$.
Answer: @Maru_kai: If you want to prove the rules described in the previous answer you can easily do it by yourself
$$\mathbb{E}[aX]=\sum_{i}a x_i p(x_i)=a\sum_{i} x_i p(x_i)=a\mathbb{E}[X]$$
try by yourself to prove that $\mathbb{V}[aX]=a^2\mathbb{V}[X]$ by using the definition
$\mathbb{V}[X]=\mathbb{E}[X^2]-\mathbb{E}^2[X]$
Answer: I'm a bit confused by your notation but there's nothing unique about the Poisson in this regard.
Say you have a random variable X, with mean E(X) and variance V(X)
Then let $Y=cX$, for some constant c.
$\displaystyle{E(Y)=\sum_{y} y P(Y=y)=\sum_{x} cx P(cX=cx)=\sum_{x} cx P(X=x)= c\sum_{x} P(X=x)=cE(X)}$
Then $V(Y) = E(Y^2) - (E(Y))^2 = E(c^2X^2) - c^2(E(X))^2 = c^2(E(X^2)-(E(X))^2) = c^2V(X)$


Sum of Sine and Cosine to Higher Powers Is Constant (Recursion, Proofs)

Question: I have observed this empirically, but I have no idea how to prove it or if it has been proven before.  If this has been proven before, in any form, either more or less generic, please point me to such a proof.  If not, can you prove it?
Given:
$$ \begin{align}
& n\in \mathbb{\{1, 2, 3, \cdots\}} \\
& c_n=\left( \frac{1}{2}\right)^{2^n-1}\\
& f_1(x)=\sin(x)\\
& f_n(x)=f_{n-1}^2(x)-c_n\\
& g_1(x)=\cos(x)\\
& g_n(x)=g_{n-1}^2\left(x-\frac{\pi}{2^n}\right)-c_n \end{align}$$
Prove that:
$$f_n^2(x)+g_n^2(x)=\left( \frac{1}{2} \right)^{2^n-2}$$
Here are some graphs for reference: https://www.desmos.com/calculator/01pshoohrl
Answer: The trick here is that they're all versions of the Pythagorean identity. Your iteration $f_n(x)=f_{n-1}^2(x)-c_n$ and $g_n(x)=g_{n-1}^2(x-\frac{\pi}{2^n})-c_n$ is a double-angle formula. We have $f_2(x)=\sin^2 x-\frac12 = -\frac12\cos(2x)$, $g_2(x)=\cos^2(x-\frac{\pi}{4})-\frac12=\frac12\cos(2(x-\frac{\pi}{4}))=\frac12\cos(2x-\frac{\pi}{2})$
$=\frac12\sin(2x)$. By a similar process, $f_3(x)=\frac14\cos^2(2x)-\frac18=\frac18\cos(4x)$ and $g_3(x)=\frac14\sin^2(2x-2\frac{\pi}{8})-\frac18=-\frac18\cos(4x-\frac{\pi}{2})=-\frac18\sin(4x)$.
It stabilizes from there, and $f_n(x)=2^{1-2^{n-1}}\cos\left(2^{n-1}x\right)$, $g_n(x)=-2^{1-2^{n-1}}\sin\left(2^{n-1}x\right)$ for all $n\ge 3$.
To prove the result, then, we prove these formulas inductively. We do the special case calculations for $n=1$, $n=2$, and $n=3$, then do the inductive step to go from $n-1$ to $n$ for $n\ge 4$. In all of these cases, we're using the double-angle formulas $\sin^2 t-\frac12=-\frac12\cos(2t)$ and $\cos^2 t-\frac12=\frac12\cos(2t)$ and the translation formula $\cos(t-\frac{\pi}{2})=\sin t$.
Once we have the formulas, the result about the sum of squares is immediate:
$$f_n^2(x)+g_n^2(x)=\left(2^{1-2^{n-1}}\right)^2\left(\cos^2(2^{n-1}x)+\sin^2(2^{n-1}x)\right)=2^{2-2^n}$$
(and the special cases for small $n$)


Problems to configure hibernate and PostgreSQL

Question: I am new to Hibernate configuration, and I'm trying to setup a this test application but I am getting a few problems. I did everything as in this tutorial:
 http://www.laliluna.de/articles/java-persistence-hibernate/first-hibernate-example-tutorial.html  But it seems that I am doing something wrong:
See the log:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Apr 14, 2015 10:27:28 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Apr 14, 2015 10:27:29 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.8.Final}
Apr 14, 2015 10:27:29 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.service.allow_crawling=false, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.max_fetch_depth=5, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE, hibernate.bytecode.use_reflection_optimizer=false, hibernate.jdbc.batch_versioned_data=true, hibernate.connection.pool_size=5}
Apr 14, 2015 10:27:29 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Apr 14, 2015 10:27:30 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Apr 14, 2015 10:27:30 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Apr 14, 2015 10:27:33 AM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Exception in thread "main" java.lang.ExceptionInInitializerError
    at de.laliluna.example.TestExample.createHoney(TestExample.java:92)
    at de.laliluna.example.TestExample.main(TestExample.java:28)
Caused by: org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2165)
    at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:202)
    at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:47)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2077)
    at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:184)
    at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:47)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2056)
    at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:178)
    at de.laliluna.hibernate.SessionFactoryUtil.<clinit>(SessionFactoryUtil.java:32)
    ... 2 more
Caused by: org.dom4j.DocumentException: Error on line 14 of document  : The element type "session-factory" must be terminated by the matching end-tag "</session-factory>". Nested exception: The element type "session-factory" must be terminated by the matching end-tag "</session-factory>".
    at org.dom4j.io.SAXReader.read(SAXReader.java:482)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2157)
    ... 10 more

I got the Following Configuration:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

  <session-factory>

    <property name="connection.url">jdbc:postgresql://localhost:5432/firsthibernate</property>
    <property name="connection.username">postgres</property>
    <property name="connection.password">root</property>
    <property name="connection.driver_class">org.postgresql.Driver</property>
    <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>

    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

    <property name="current_session_context_class">thread</property>

    <property name="hibernate.show_sql">true</property>

    <property name="hibernate.hbm2ddl.auto">create</property>

    <mapping class="de.laliluna.example.Honey" />

  </session-factory>

</hibernate-configuration>

Class mapping:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="de.laliluna.example">
    <class name="Honey" table="thoney">
        <id name="id">

            <generator class="sequence">
                <param name="sequence">honey_id_seq</param>
            </generator>

        </id>
        <property name="name" column="fooname"/>
        <property name="taste" column="bartaste"/>

    </class>

</hibernate-mapping>

Comment: Check you application server has the same file and in logs it warn you as use http://www.hibernate.org/dtd/ instead of http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd I check your xml and it is valid.
Comment: @erhun I've checked and found that this was the problem, it seems that it's not a simple warning.

WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead.
Refer to Hibernate 3.6 Migration Guide!
Comment: @Edardox23Can you accept my answer as accepted answer so in the future people can easily find the solution to this problem.
Answer: Check you application server has the same file and in logs it warn you as use

http://www.hibernate.org/dtd/

instead of

http://hibernate.sourceforge.net/

I check your xml and it is valid.
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Exception in thread "main" java.lang.ExceptionInInitializerError
    at de.laliluna.example.TestExample.createHoney(TestExample.java:92)


OpenConnect can ping but can't resolve company websites

Question: Using network-manager-openconnect & network-manager-openconnect-gnome I have set-up a Palo-Alto Networks GlobalProtect VPN to connect to my company network.
This works fine and I can access all internal company websites. However I would like this VPN to only be active for company domains and addresses so I've tried setting up routes like this

But when I apply these changes and connect to the VPN I can't navigate to any of the company pages. When I try I get a This site can't be reached with DNS_PROBE_FINISHED_NXDOMAIN error in chromium. Oddly enough I can ping the IP addresses of these sites. Just the IP's, domains do not work.
This brought me to believe that there's a problem with DNS resolving so I tried adding the DNS server addresses to the DNS field and switching Automatic to off but that did not help.
What could I do to diagnose this issue? I feel like I am close to have it working but I am stuck.
Answer: Oh, you're going to love this: Chromium (and Chrome) will bypass your preferred DNS when connected to the open web to use their "secure DNS" services. You can disable this on Mac and Windows so that the "Use this connection only for resources on its network" is followed, but not Linux.
To illustrate this on Mac via Settings ⇢ Search "DNS":

Your Options

If you are 100% wedded to Chromium, all traffic will need to go through the VPN. Uncheck the "Use this connection only for resources on its network" option from the VPN settings.
If you want to use something like Chromium, consider switching to Edge, which does allow you to disable the "secure DNS" function as illustrated here:

Use Firefox

Hopefully one of these options will work for you
Comment: Thanks for the reply! I've tried both Edge with `secure DNS` disabled and Firefox but still no luck. I can open up Youtube or StackOverflow but I can't connect to the company site even though i can ping it's IP.


Attempting to output value of math formula applied to array is failing [Jquery]

Question: I'm attempting to get a coefficient of variation calculator working with jQuery, and can't seem to get it to output a correct answer.
My current code:
var fields = $('#cvform').serializeArray();
        var num = 0;
        var mean = 0;
        var m2 = 0;
        var total = 0;
        jQuery.each(fields, function(i, field){
        if (field.value > 0) {
            num++;
            var delta=(field.value-mean);
            var mean=(mean+delta/num);
            var m2=(m2+delta*(field.value-mean));
            var total=(total+field.value);
        };
        });
        var cov=(((Math.sqrt(m2/(num-1)))/(total/num))*100);
        $("Coefficient of Variation: " + delta + m2 + num + total + cov +  "").appendTo('#cvdisplay');

When I attempt to output the values after, it tells me that delta is undefined, mean m2 and total are = 0, and num is output correctly. Cov is simply output as NaN. The array of #cvform is simply text inputs that can only be numbers. Can anyone point me in the right direction of getting this to function?
Answer: You declare delta within a function, so it isn't visible outside the for loop. Move its declaration out of the each block and it will be found.
var fields = $('#cvform').serializeArray();
    var num = 0,
        mean = 0,
        m2 = 0,
        total = 0,
        delta = 0;
    jQuery.each(fields, function(i, field){
    if (field.value > 0) {
        num++;
        delta=(field.value-mean);
        mean=(mean+delta/num);
        m2=(m2+delta*(field.value-mean));
        total=(total+field.value);
    };
    });
    var cov=(((Math.sqrt(m2/(num-1)))/(total/num))*100);
    $("Coefficient of Variation: " + (delta + m2 + num + total + cov) +  "").appendTo('#cvdisplay');


Uninstalling Go (golang)

Question: I'm trying to install drive, which requires Go.
I did:
sudo apt-get install golang git mercurial

which successfully installed version 1.2.1. Unfortunately, when I tried to install drive with:
go get -u github.com/odeke-em/drive/cmd/drive

I encountered this error, and now I see I need at least version 1.4 of Go to make things work. The golang doc says you must first remove the existing version.
So I came across this question that says to simply use:
sudo apt-get purge golang

which gave me this output:
The following packages will be REMOVED:
golang*
0 upgraded, 0 newly installed, 1 to remove and 16 not upgraded.
After this operation, 92.2 kB disk space will be freed.
Do you want to continue? [Y/n] Y
(Reading database ... 263287 files and directories currently installed.)
Removing golang (2:1.2.1-2ubuntu1) ...

(no more output after the three dots—just back to the prompt).
But I still see the go directory in /usr/lib/, and there's also still a gopath directory in my home directory.
which I think was created when I did:
$ cat << ! >> ~/.bashrc
> export GOPATH=\$HOME/gopath
> export PATH=\$GOPATH:\$GOPATH/bin:\$PATH
> !
$ source ~/.bashrc # To reload the settings and get the newly set ones # Or open a fresh terminal

during the installation (to create the GOPATH).
So I'm not sure if the uninstall was successful and if it's safe to install a newer version of Go.
Ubuntu 14.04 LTS
Comment: To downvoter: Are you kidding me?
Comment: You get my upvote for the downvoter.  Stop that drive-by downvote crap.  This is a seriously annoying problem, I was glad to find the question, thanks.
Answer: I spent a whole morning fixing this, tried all different solutions, when I type go version, it's still there, really annoying...
This worked for me.
sudo apt-get remove golang-go
sudo apt-get remove --auto-remove golang-go

Check this original post :D
Comment: `--auto-remove` force it to remove all from linux-images which consumed around 10 minutes. @loukaswho
Answer: I realize that this is a little old, but the answers at https://golang.org/doc/manage-install#uninstalling may help you.
Essentially just removing the directories /usr/local/go or /usr/lib/go and modifying your path at /etc/profile or $HOME/.profile should be enough.
Answer: best way to uninstall is to open terminal and type
sudo apt-get uninstall purge golang*

this removes every package associated with go.
Then you can run
sudo apt-get update

But if you did that and nothing worked, you can do this
sudo rm -rf /usr/local/go

then try running the purge again.
But You should update to Go 1.8, which sets the GOPATH for you.
But hey! before updating first remove existing golang.
Answer: First you have to remove all the go-packages in your system by type this code from terminal
sudo apt-get purge golang*

Then follow the instructions to download and install golang
Official golang website
Comment: Thanks,  this was the only solution that worked
Answer: As mentioned in official docs

Firstly, delete the go directory. Mostly it will be /usr/local/go. If you are not sure check it using which go. So, run sudo rm -rf /usr/local/go.

Next you need to remove the Go bin directory from your PATH environment variable. i.e. remove GOBIN, GOPATH from ~/.bashrc.

Uninstalling Go (golang)


Was my water softener hooked up correctly?

Question: This is my third water softener post - I only intended to have one but I just started getting more questions as I was typing them up.
See
What is the white crystals in my water softener? and how to clean properly
Any idea what parts were replaced on my water softener?
I had a local plumber install my water softener in exchange for some computer work instead of having a professional. This was 2-3 years ago. I finally got it running a few days ago.
1) Does it look like it's hooked up correctly? Anything special I need to know about my setup?
2) Am I ok to replace the sheetrock around the huge hole he cut?
3) The manual that my water softener came with says "This manual provides a reference for operation and maintenance of the following WaterMax  water conditioning appliance models: 63MAQ, 63BEQ, 63MDQ, 62AMQ, 62APQ, 62AKQ, and 62AJQ. If you do not see your specific model listed here, your dealer has customized your WaterMax to solve additional water conditioning problems you may and and will be happy to explain an additional special features."
Mine is a Hague WaterMax 63BAQ, which is not listed and means that is has 'an additional special feature' according to the manual. Any idea what this means?
4) Are there any tools one can use to manually test the water? I read in the manual to leave it to the professionals, but I think it would be fun to learn about and have always wanted to test the water in my house, and after looking at all the settings on the digital display ( a lot of them referencing water testing) I am interesting in trying it myself.
5) Lastly, are there any tips, or general knowledge / tips you would like to share about my water softener / any water softeners in general?
Comment: You should probably split your questions into separate questions. Except number 5, that one is too broad and would not fit well in the Q&A format.
Answer:
I can't tell from the picture which is the inlet and outlet, so I will make the assumption it's not hooked up backwards..
However, there are a few things I see that I don't like:

The hole cut in the drywall is pretty unprofessional
There is a shut-off valve in the wall - which means you need an access panel. If the installer added that there, he's incompetent. If it was there before, he probably should have highly suggested to you he moved it out -- if he also did the plumbing (if he cut the hole as you said, then I suspect so) then this would have not been much extra work.
The overflow on the brine tank doesn't go anywhere (the black barbed elbow coming out the side). I have seen at least two basements who had a couple inches of water (ruining carpet, etc) due to a failed $10 shut-off float valve in the brine tank.

Yes you can fix the drywall, but don't cover the valve (or leave an access panel). The valve has the potential to leak, and doing that in the wall is bad. You may also need to shut it off at some point (eg, to disconnect the softener). The best option would be to replumb the valve so it's not in the wall.
Sorry I don't know enough details about this particular model or brand to answer specific questions about your model. See if you can find the manual, especially the installer's manual. A quick google search turns up some promising results.
You can get hardness test strips to check the hardness before and after. There's actually some fairly complex chemistry involved in "testing water" (which, frankly, most water treatment companies don't fully understand), and I could go on in a lot of detail about fully testing .. but I'm not even sure that's what you're asking about so I won't get into it.
To set up your softener correctly, you basically need to know the hardness of the water. It looks like your softener probably has a flow meter in it so it automatically recharges based on usage; some of the more basic models recharge based on a schedule and so you need to have a rough idea of your average daily usage as well to know how often to recharge them.
Softeners are pretty easy to maintain. Make sure there's salt in the brine tank. Every 10 years, you need to rebed the media in the filter. Make sure nothing is leaking, and that it's recharging (usually it does this during the night, anywhere from every day to once a week, though could be less if you use very little water).
Comment: (Not to mention, covering the valve without having an access panel is a building code violation, in addition to being a bad idea)
Answer: I only see one valve, incorrectly installed in the wall cavity at that, so there is no way to bypass the softener for maintenance or if a component fails. So no, its not installed correctly because a bypass is a standard part of any softener installation.
Without a bypass you are going to find that those cheap plastic components they make water softeners with are going to eventually fail and it will spring a leak. Hopefully the incorrectly installed valve you have now comes before the water reaches the unit. Then you'll at least be able to shut the water off from right there and not at the curb. However you'll then be without water in the house until you fix whatever issue your having with the softener. Below is a diagram of a standard bypass setup which your manual should also have.


Iterate over a list of values within a Hashmap

Question: Lexical Analysis program: with a text file, segregate each token under categories such as keyword, characters, digits, integers.
So I created a hashMap where Each key in the hash map have to be segregated in a way that i.e Keyword = [if, then, else], Special = [(,),.,;], Character = [a,b,c], so each key has it's own list.
But I also need to count the number of times each token appears within the text file, so I was thinking of iterating through each separate list and finding the occurrences of each word/character/digit there, however it's definitely a lot of bad code because I can't think of a way that's better than if list.contains(word) count++, and doing that for every single word/character/digit.

import java.io.*;
import java.util.*;

public class Main {

    private static HashMap<String, ArrayList<String>> map;
    private static ArrayList<String> keys;
    private static ArrayList<String> special;
    private static ArrayList<String> characters;
    private static ArrayList<String> integers;
    private static ArrayList<String> digits;
    private static Token k;

    public static void main(String[] args) {

        map = new HashMap<>();
        keys = new ArrayList<>();
        special = new ArrayList<>();
        characters = new ArrayList<>();
        integers = new ArrayList<>();
        digits = new ArrayList<>();
        k = new Token();

        executeAnalysis();
    }

    private static void executeAnalysis() {
        try {
            File file = new File("/Users/karinaabad/Desktop/HW311.txt");
            Scanner scanner = new Scanner(file);

            while(scanner.hasNext()) {
                String w = scanner.next();
                segregateTokens(w);
            }
            printSummary();
        } catch (FileNotFoundException f) {
            System.out.println("Invalid file input.");
        }
    }

    private static void segregateTokens(String w) {
        if (k.checkKeyword(w))
        {
            keys.add(w);
        }

        if (k.checkSpecial(w)) {
            special.add(w);
        }

        if (k.checkDigit(w)) {
            digits.add(w);
        }

        if (k.checkIntegers(w)) {
            integers.add(w);
        }

        if (k.checkCharacters(w)) {
            characters.add(w);
        }

        map.put("Keyword", keys);
        map.put("Special", special);
        map.put("Digit", digits);
        map.put("Integers", integers);
        map.put("Characters", characters);
    }

    private static void printSummary() {
        System.out.println("==========Summary Report==========");
        for (Map.Entry<String, ArrayList<String>> pair : map.entrySet())
        {
            System.out.println(pair.getKey() + " : " + pair.getValue());
        }
    }

    private static void checkCount() {
        for (Map.Entry<String, ArrayList<String>> key : map.entrySet()) {
            for (String value : )
        }
    }
}

Comment: It prints a newline, so that everything isn't printed on one line.
Comment: [`PrintStream#println()`](https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println())
Answer: The println() call prints a newline after the loop has completed (at the end of the line containing the integers).
If the println() was not there and the code were to try to print something else, it would appear on the same line as the integers.


How to abstract php database object class to work with variable columns

Question: I have a PHP class whose instances are rows in my database table. The class has methods that allow one to create, read, update, and delete rows corresponding to the given instance of the class. It works well as it stands, but I currently name each of the database columns explicitly in my code. As a result, when I add or delete columns (an occasional, but not trivially infrequent action), I must update the class to include those column names. I would like to abstract my code so that it queries the database first to determine what the columns it needs to fill in. (Incidentally, I'm working with PHP 7.2)
The code below is what I've got now, but I'm at a loss as to how to abstract it so that it is not tied to spelling out each specific column name.
<?php
class Example extends DatabaseObject {
    static protected $table_name = "data";
    static protected $db_columns = ['id','column1', 'column2', 'column3', 'column4'];

    public $id;
    public $column1;
    public $column2;
    public $column3;
    public $column4;

    public function __construct($args=[]) {
        $this->column1 = $args['column1'] ?? '';
        $this->column2 = $args['column2'] ?? '';
        $this->column3 = $args['column3'] ?? '';
        $this->column4 = $args['column4'] ?? '';
    }

    public function attributes() {
      $attributes = [];
      foreach (static::$db_columns as $column) {
        if ($column === "id") { continue; }
        $attributes[$column] = $this->$column;
      }
      return $attributes;
    }

    public function save() {
        // calls private methods to validate, sanitize, then create or update, acc. to context
        // to create, it preps an sql statement based on a call to attributes()
    }

}
?>

Answer: I'm not sure how far you want to take this. This is one way that you can abstract the data for a row.
You will notice that I use set and get functions to access the data.
class Example extends DatabaseObject {
    static protected $table_name = "data";
    static protected $db_columns = ['id', 'column1', 'column2', 'column3', 'column4'];

    public $id;
    protected $data = [];

    public function __construct($args=[]) {
        foreach(self::$db_columns as $columnName) {
            if ( isset($args[$columnName]) ) {
                $this->data[$columnName] = $args[$columnName];
            }
        }
    }

    public function set($columnName, $value)
    {
        if ( in_array($columnName, $this->data) && isset($this->data[$columnName]) ) {
            $this->data[$columnName] = $value;
        }
    }

    public function get($columnName)
    {
        if ( isset($this->data[$columnName]) ) {
            return $this->data[$columnName];
        }
        return null;
    }

    public function attributes() {
      $attributes = [];
      foreach (static::$db_columns as $columnName) {
        if ($column === "id") { continue; }
        $attributes[$columnName] = $this->data[$columnName];
      }
      return $attributes;
    }

    public function save() {
        // calls private methods to validate, sanitize, then create or update, acc. to context
        // to create, it preps an sql statement based on a call to attributes()
    }
}

Comment: This is very helpful. I don't know why I hadn't thought of this, but I appreciate the help.
Comment: Be cautious using a single class to represent a row in a table and the table itself.
Answer: You may need to look at the magic methods __get() and __set(). Basically, they are class methods that are triggered when trying to access a property that doesn't exist in your class, so you can have a fallback for them.
Please take a look at the documentation: https://www.php.net/manual/en/language.oop5.overloading.php#object.set


Inequality using coefficients of Taylor development of bounded holomorphic funciton

Question: Let $f: D(0,1) \rightarrow \mathbb{C}$ be a holomorphic function on $D(0,1)$ and let $\sum_{n=0}^{+\infty} a_n z^n$ be its Taylor series at $0$.
We suppose that the Taylor development converges in $D(0,1)$, that $f(0) \geq 0$ and that $\forall z\in D: |f(z)| \leq 1$.
I try to prove that:
$$\sum_{n=0}^{+\infty} \frac{|a_n|}{ 3^n} \leq 1 \, .$$
What I did:
Since $\frac{1}{3} \in  D(0,1)$, $|f(\frac{1}{3}) | \leq 1$ which means
$|\sum_{n=0}^{+\infty} \frac{a_n}{ 3^n} |\leq 1 $.
However what I need to prove is stronger since  $|\sum_{n=0}^{+\infty} \frac{a_n}{ 3^n}| \leq \sum_{n=0}^{+\infty} \frac{|a_n|}{ 3^n} $.
Could you please help with any technique or theorems I could use?
Comment: $a_n \ge 0$ need not be true, as $f(z) = \frac 12 - \frac i2 z$ is a possible function.
Comment: The condition $f(0) \ge 0$ looks unnecessary, because you can always consider $\lambda f(z)$ instead, with a suitable $\lambda$ of modulus $1$. – Or should it be $f(0) = 0$?
Comment: Actually it is a condition of the problem. I thought it could be used to prove that $a_n\geq 0$ for all $n\in \mathbb{N}$, since $a_0=f(0) \geq 0 $. $ f(0) =0 $ is  not mandatory in my case
Answer: This is "Bohr's theorem on power series" and
the number $\frac 13$ is the so-called "Bohr radius," after the Danish
mathematician (and soccer player) Harald Bohr:

Let $f$ be holomorphic in the unit disk $\Bbb D$ with power series
  $f(z) = \sum_{n=0}^\infty a_n z^n $, and $|f(z)| < 1$ for all
  $|z| \in \Bbb D$. Then
  $$
 \sum_{n=0}^\infty |a_n z^n| \le 1 \quad \text{for } |z| \le \frac 13 \, .
$$
  (The number $\frac 13$ cannot be replaced by any larger number.)

The following proof is taken from Why Bohr got interested in his radius and what it has led to, which also contains more information about the history
of this theorem and further developments.
The Schwarz-Pick theorem
states that
$$
 \frac{|f'(z)|}{1-|f
(z)|^2} \le \frac{1}{1-|z|^2} \, .
$$
In particular for $z=0$ it follows that
$$
 |a_1| \le 1 - |a_0|^2 \, .
$$
The crucial idea now is that the same relationship holds for higher
derivatives as well:
$$ \tag{*}
 |a_n| \le 1 - |a_0|^2 \quad \text{for } n = 1, 2, 3, \ldots
$$
Then
$$
 \sum_{n=0}^\infty \frac{|a_n|}{3^n} \le |a_0| + (1 - |a_0|^2) \sum_{n=1}^\infty \frac{1}{3^n} = |a_0| + \frac{1 - |a_0|^2}{2} \\
= 1 -\frac{(1- |a_0|)^2}{2} \le 1 \, .
$$
So it remains to prove $(*)$: For fixed $n\ge 1$, let $\omega$ be
a $n^{\text{th}}$ root of unity and set
$$
 g(z) = \frac{1}{n} \sum_{j=0}^{n-1} f(\omega^j z) = a_0 + a_n z^n
 + a_{2n} z^{2n} + \ldots = h(z^n)
$$
where
$$
 h(z) = \sum_{k=0}^{\infty} a_{kn} z^k
$$
is holomorphic in the unit disk, and also $|h(z)| \le 1$.
Therefore we can apply the Schwarz-Pick theorem to $h$ and conclude
that
$$
 |a_n| = |h'(0)| \le 1 - |h(0)|^2 = 1 - |a_0|^2 \, .
$$
This finishes the proof.
Remark: The condition $f(0) \ge 0$ is not needed.
Comment: Thanks for the detailed answer!


when I want to access the children of parsed tree using .contents I am unable to reach the childrens but with find i can find children why?

Question: using .contents
    `url="https://www.imdb.com/chart/top/"
     import requests
     from bs4 import BeautifulSoup
     re=requests.get(url)
     doc=BeautifulSoup(re.content,"html.parser")
     table=doc.find('tbody',class_="lister-list")
     print(table.contents[0])`

using find
    `url="https://www.imdb.com/chart/top/"
     import requests
     from bs4 import BeautifulSoup
     re=requests.get(url)
     doc=BeautifulSoup(re.content,"html.parser")
     table=doc.find('tbody',class_="lister-list")
     print(table.find('tr'))`

the .contents is not working why
Answer: Because .contents will give you all content of the node - that means string, tags, html comments etc.
If you do print(table.contents) it will print:
['\n',

...

so first item is string \n (and this will be printed with your script).
If you will do print(table.contents[1]) it will give you the
 tag.


How can declare variables on html page in angular js

Question: I want to declare my variable on outside from ng-repeat  and than inside the ng-repeat variable are added and at the bottom of ng-repeat value should be incremented like php loop work.
my html:-
{{t_val = 0}}

{{n}}

{{(t_age + $index + 1)-1}}

{{t_bcv}}

{{t_bcv}}

{{t_val}}

                {{t_val = t_val +n}}

Actually on php my code is like this
$begin_contract_value = 0;
for($i= 1; $i <= 30; $i++)
{
$Ending_contract_value = $begin_contract_value - $new_rider_cost - $Annual_withdrawals + $new_est_earnings;

<?php echo $begin_contract_value; ?>

 $begin_contract_value = $Ending_contract_value ;

}

I want my angular code like php code. but  I have no idea. I want to do it on html page not using app.js. is it possible ?
Comment: So you want to increment `t_val`?
Comment: yes, want my angular functionality should work like php code
Answer: Well, in this specific case you can use $index:

{{$index}}

or ngInit directive:

Comment: and than how to increment value in ng-repeat  like
$begin_contract_value = $Ending_contract_value ;
Answer: What I have used in my project to declare a variable (and abviously not displaying it):
{{newVariableName = oldVariableName; ""}}

Answer: use ng-init .

{{n}}

{{(t_age + $index + 1)-1}}

{{t_bcv}}

{{t_bcv}}

{{t_val}}

            {{t_val = t_val +n}}

for more details go to this link :  https://docs.angularjs.org/api/ng/directive/ngInit


Failed to parse plugin descriptor for org.apache.maven.plugins:maven-resources-plugin:2.4.3.. error in opening zip file

Question: I was using maven to build and compile a spring project and here's what I got an error about "error in opening zip file.". I attached the settings.xml here to show that I configured the proxy right and the pom.xml.
[SETTINGS.XML]
        <proxy>
            <active>true</active>
            <protocol>http</protocol>
            <host>XXXX</host>
            <port>8080</port>
            <username>XXXX</username>
            <password>XXXXX</password>
            <nonProxyHosts>localhost</nonProxyHosts>
         </proxy>

[POM.XML]
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.wrox</groupId>
  <artifactId>springfirst</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>springfirst</name>
  <url>http://maven.apache.org</url>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <testSourceDirectory>src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/java</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
                <filtering>true</filtering>
            </testResource>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <properties>
        <spring-version>2.0.6</spring-version>
        <junit-version>3.8.2</junit-version>
    </properties>

  <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring</artifactId>
            <version>${spring-version}</version>
        </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit-version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

[ERROR MESSAGE]
E:\DOCUMENTS\ETC\TUTORIALS\begspringcode_091809\src\chapter1\springfirst>mvn -X compile
Apache Maven 3.0.3 (r1075438; 2011-03-01 01:31:09+0800)
Maven home: C:\maven2.2.1\bin\..
Java version: 1.6.0_15, vendor: Sun Microsystems Inc.
Java home: C:\Program Files\Java\jdk1.6.0_15\jre
Default locale: en_PH, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "x86", family: "windows"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from C:\maven2.2.1\bin\..\conf\settings.xml
[DEBUG] Reading user settings from C:\Users\AMT\.m2\settings.xml
[DEBUG] Using local repository at C:\Users\AMT\.m2\repository
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10 for C:\Users\AMT\.m2\repository
[INFO] Scanning for projects...
[DEBUG] Extension realms for project com.wrox:springfirst:jar:1.0-SNAPSHOT: (none)
[DEBUG] Looking up lifecyle mappings for packaging jar from ClassRealm[plexus.core, parent: null]
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.wrox:springfirst:jar:1.0-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 42, column 12
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[DEBUG] === REACTOR BUILD PLAN ================================================
[DEBUG] Project: com.wrox:springfirst:jar:1.0-SNAPSHOT
[DEBUG] Tasks:   [compile]
[DEBUG] Style:   Regular
[DEBUG] =======================================================================
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building springfirst 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[DEBUG] Lifecycle default -> [validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-pack
age, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy]
[DEBUG] Lifecycle clean -> [pre-clean, clean, post-clean]
[DEBUG] Lifecycle site -> [pre-site, site, post-site, site-deploy]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.177s
[INFO] Finished at: Mon Oct 03 14:57:47 SGT 2011
[INFO] Final Memory: 1M/4M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to parse plugin descriptor for org.apache.maven.plugins:maven-resources-plugin:2.4.3 (C:\Users\AMT\.m2\repository\org\apache\maven\plugins\maven-resources-plugin\2.4.3\maven-resources-plugin-2.4.3.jar): error in opening zip file -> [Help 1]
org.apache.maven.plugin.PluginDescriptorParsingException: Failed to parse plugin descriptor for org.apache.maven.plugins:maven-resources-plugin:2.4.3 (C:\Users\AMT\.m2\repository\org\apache\maven\plugins\maven-resources-plugin\2.4.3\maven-resources-plugin-2.4.3.jar): error in opening zip file
        at org.apache.maven.plugin.internal.DefaultMavenPluginManager.extractPluginDescriptor(DefaultMavenPluginManager.java:212)
        at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getPluginDescriptor(DefaultMavenPluginManager.java:147)
        at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getMojoDescriptor(DefaultMavenPluginManager.java:261)
        at org.apache.maven.plugin.DefaultBuildPluginManager.getMojoDescriptor(DefaultBuildPluginManager.java:185)
        at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.setupMojoExecution(DefaultLifecycleExecutionPlanCalculator.java:152)
        at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.setupMojoExecutions(DefaultLifecycleExecutionPlanCalculator.java:139)
        at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan(DefaultLifecycleExecutionPlanCalculator.java:116)
        at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan(DefaultLifecycleExecutionPlanCalculator.java:129)
        at org.apache.maven.lifecycle.internal.BuilderCommon.resolveBuildPlan(BuilderCommon.java:92)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: java.util.zip.ZipException: error in opening zip file
        at java.util.zip.ZipFile.open(Native Method)
        at java.util.zip.ZipFile.<init>(ZipFile.java:114)
        at java.util.jar.JarFile.<init>(JarFile.java:133)
        at java.util.jar.JarFile.<init>(JarFile.java:112)
        at org.apache.maven.plugin.internal.DefaultMavenPluginManager.extractPluginDescriptor(DefaultMavenPluginManager.java:170)
        ... 25 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginDescriptorParsingException
'cmd' is not recognized as an internal or external command,
operable program or batch file.
E:\DOCUMENTS\ETC\TUTORIALS\begspringcode_091809\src\chapter1\springfirst>

Answer: Delete C:\Users\AMT\.m2\repository\org\apache\maven\plugins\maven-resources-plugin\2.4.3\maven-resources-plugin-2.4.3.jar or better still C:\Users\AMT\.m2\repository\org\apache\maven\plugins\maven-resources-plugin\2.4.3\ folder and try again.
Evidently, the jar file is incomplete or corrupted.
Comment: I have confirm that it's probably a proxy issue but I still want somehow to bypass the proxy using MAVEN. Any suggestions ?
Comment: In my case I need to delete the repository folder itself. then it worked like a charm
Comment: Thank you Raghuram! Actually, I think it must be have been because of the corrupted file because I did that under proxy. Now, at home it worked. Though now I have another problem.
Comment: I like the "evidently' :-)
Comment: Thank you so much, your answer helped me to resolved the same issue of different kind of plugin,
Answer: Deleting the repository folder solved the issue.
Answer: Got the same issue. This worked for me.
Check your maven version
HOME>> mvn -version
3.0.3

I updated this to maven 3.2.1 and change the path in bash_profile. Now check it again.
HOME>> mvn -version

If it is updated, delete the repository and close the terminal. Reopen the terminal and type
Project Path >> mvn clean install

If it not updated, then type following
HOME>> echo $JAVA_HOME
HOME>> which java
/usr/share/java(for e.g.)
HOME>> cd /usr/share/java
HOME>> open .

You will see maven old version contents in it. Replace the contents of this with new version contents.
Then delete the repository.
Project Path>> mvn clean install

Now all your maven jars will be downloaded.
Hope this will help you.


When printing HTML, how can I determine how much space is left before the end of the page?

Question: I'm printing HTML as PDF using PrinceXML.
I often print a series of images, some large and some small.
When I do this, I'd like to start with the largest image that will fit in the remaining space on the page.
How can I determine how much space is left before the end of the page?
Ideally using CSS supported by PrinceXML, though I understand JavaScript may be necessary.
Answer: How about you obtain the height of the document and substract all other elements height above it.
pseudo format :
total html document height -(your pdf/html height + header height+other element with height above page)
Comment: would require me to know what other elements are on this page (not just in the doc)


$ bundle update - error - Can't find the PostgreSQL client library (libpq) *** extconf.rb failed ***

Question: I'm trying to run
$bundle update, but it errors after going through several gems with the following:
Installing pg (0.11.0) with native extensions /Library/Ruby/Site/1.8/rubygems/installer.rb:483:in `build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb
checking for pg_config... yes
Using config values from /opt/local/lib/postgresql83/bin/pg_config
checking for libpq-fe.h... yes
checking for libpq/libpq-fs.h... yes
checking for PQconnectdb() in -lpq... no
checking for PQconnectdb() in -llibpq... no
checking for PQconnectdb() in -lms/libpq... no
Can't find the PostgreSQL client library (libpq)
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
    --with-pg
    --without-pg
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    --with-pqlib
    --without-pqlib
    --with-libpqlib
    --without-libpqlib
    --with-ms/libpqlib
    --without-ms/libpqlib

Gem files will remain installed in /Library/Ruby/Gems/1.8/gems/pg-0.11.0 for inspection.
Results logged to /Library/Ruby/Gems/1.8/gems/pg-0.11.0/ext/gem_make.out
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:446:in `each'
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:446:in `build_extensions'
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:198:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/source.rb:100:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:55:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:44:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:8:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/cli.rb:252:in `update'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `send'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor.rb:246:in `dispatch'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/base.rb:389:in `start'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/bin/bundle:13
    from /usr/bin/bundle:19:in `load'
    from /usr/bin/bundle:19

Have you seen this or have any ideas on what's breaking here? thanks
Comment: I need to use Postgres with rails 3. commenting out gem 'pg' #Postgres in the gemfile makes the bundle update work fine. Should I not be using the pg gem?
Answer: When you tried to compile a postgres gem to the ruby, you have to have installed a development version of Posgtresql library, in Ubuntu (Debian etc.) it is named libpq-dev and client library, which is named libpqx (x is the version of this library).
Answer: Worked by running:
sudo bundle install

Comment: I know this is a few years old, but these days (2014) bundler gives you a warning when doing this:

`Don't run Bundler as root. Bundler can ask for sudo if it is needed, and installing your bundle
as root will break this application for all non-root users on this machine.`


Make a button active at a particular hour

Question: I want a button that will become available at, say, 8 AM. I know how to check if the button is available when the view is loaded, but, if the user is looking at the button as the clock turns to 8 AM, how do I get the button to become active without loading the view?
Comment: Setup an `NSTimer` to go off at the desired time and update the button as needed.
Answer: The button should always be present. Use its hidden to hide and show it as necessary. Or you can use its enabled to enable or disable it as necessary, but this can require more work, because a disabled button might not automatically look disabled so the user won't understand that it isn't truly "available".
Thus we have three cases to deal with:

The user moves to this view controller, the view controller loads its view, and your code decides about the button state / visibility now. You've already handled this one.
The view controller is already present and the view is visible, and the availability-change moment comes. In this case you will need previously to have set up a notification to prompt the view controller to take action now. Do not loop perpetually watching the time. Use an NSTimer or similar (a local notification is also worth considering).
The view controller is covered by another view controller and then uncovered. Perhaps the state needs to have changed in the meantime. So you will also want to do this check generally in viewWillAppear:, not just in viewDidLoad.


Compressing a bitmap multiple times

Question: Android API provides the Bitmap.compress(format, quality, output) method for saving bitmap objects. I created a sample app, which loads a jpeg image (some noisy camera photo) into the bitmap, then compresses it back to the same file. Then, does it again 5 times.
Obviously, my bitmap accumulates the compression artifacts. Surprisingly for me, the amount of this artifacts depends on the quality of the compression in a weird way. When I set quality to 100 (which I expect to be the best quality), the artifacts are distinctly visible. When I drop quality to 90, the artifacts are significantly less visible. Quality setting of 80 gives me the best results. With the quality setting of 70 and below, the image degenerates quickly.
When I compress bitmaps with the 100 quality, the resulting file's size linearly increases on every pass. For the quality settings of 90 and 80, the size of the resulting file stays about the same on every pass.
I've tested this behavior on Android 5 device (HTC One) and on Android 6 device (Motorola Moto G) and it was quite consistent. On Android 7 though, (Samsung S7) I could not spot any difference in the resulting images.
So, my question is why does compressing with quality = 80 gives us better results, than quality = 90 and especially quality = 100. I really expected saving images with 100 quality to be almost lossless (like they are in, say, GIMP)
Answer: It's hard to tell without seeing examples, but I'm assuming the artifacts you're noticing are high-frequency components (characterized by sharp, steep changes in brightness that only last for a pixel or two). Although not mandatory, many .jpeg compression algorithms will use particular quantization matrices that attenuate high frequency components more at lower quality settings, thus making room for the lower-frequency stuff that you might consider more "fundamental" to the image.
So, it's not hard to imagine that, at lower quality settings, high-frequency components would be "cut out" of the image, lowering the gradients and producing an overall "smoother" look. And, it's also not hard to imagine that, with high (but imperfect) quality, some high-frequency components could be exaggerated, and even amplified (due to quantization errors), over successive runs.
Put another way, JPEGs macroblocks are made up of linear combinations of the following 8x8 primitives, and at lower quality settings, the primitives closer to the right and the bottom are less likely to be present, so: no sharp edges.

(Original image from Wikimedia, see here)
Comment: The original image is rather noisy. Your version sounds reasonable, thanks!
Answer: JPEG is a lossy compression algorithm. Even if you use 100% quality, the decoded image will not be identical to the original image. So if you are encoding and decoding same image multiple times, it is common to find artifacts.
Use PNG algorithm if you don't want any losses.
My answer is kind of incomplete because 80% should not have better quality than 100% and if that happened in your case, I don't know why.
The loss isn't observable while encoding using Photoshop or GIMP probably because they have improved the algorithm. Better result in Android 7 than that in lower version also might be the result of same.
Comment: Essentially, your answer is "I don't know", as my only question is "why do we have better results at 80% than at 100%". But thanks anyway.

Compressing a bitmap multiple times


Journalctl says: "Failed to search journal ACL: Operation not supported"

Question: When I run journalctl -xe as a non-root user, I get the following error:
bgeron@machine:~$ journalctl -xe
Failed to search journal ACL: Operation not supported
No journal files were opened due to insufficient permissions.

Answer: This can be caused by mounting ZFS with the wrong options. Journald requires access control lists, which are off by default in ZFS on Linux.
To enable access control lists, you must set the acltype=posixacl property on your filesystems. According to the zfs(8) man page, it is also recommended to set the xattr=sa property, which is more efficient, but only supported by "relatively new" ZFS implementations.
Set the properties as follows, for each filesystem:
zfs set acltype=posixacl poolname/path/to/fs && zfs set xattr=sa poolname/path/to/fs

After setting these properties, restart journald:
sudo systemctl restart systemd-journald

See also: https://github.com/NixOS/nixpkgs/issues/16954


Separating numbers processed with a foreach conditional into specific category of numbers

Question: This is a scenario: The $numbers array in the code below contains one thousand numbers(0 - 1000). I need to count how many of these numbers fit into each of the following categories:

how many of them are between 1 and 1000 inclusive,
how many of them are less than 1, and
how many of them are greater than 1000.

I have created a foreach loop to look at each number one after the other, but right now it's treating every number like it belongs in all three categories.
How do I get the counts correct? ie., how many numbers fit into the "Less than 1", "Between 1 and 1000", and "Greater than 1000" categories, respectively.
The current code:
$numbers = get_numbers();
$count_less_than_one           = 0;
$count_between_one_and_thousand = 0;
$count_greater_than_thousand    = 0;

foreach ($numbers as $number) {
   $count_less_than_one += 1;
   $count_between_one_and_thousand += 1;
   $count_greater_than_thousand += 1;
}

Comment: Where are your conditions? Are you expecting us to write them for you?
Answer: Very simply just include the conditions. You can just use if
foreach ($numbers as $number) {

    if ($number < 1) $count_less_than_one += 1;

    else if ($number >= 1 && $number <= 1000) $count_between_one_and_thousand += 1;

    else $count_greater_than_thousand += 1;
}