Is the function $f:\mathbb C \to \mathbb C$ defined as $f(z)=\sqrt z$ uniformly continuous ?

Question: Is the function $f:\mathbb C \to \mathbb C$ defined as $f(z)=\sqrt z$ uniformly continuous ? Is it uniformly continuous on some non-compact restriction of the complex plane (other than $(0,\infty)$ ) ?
Comment: You can't even define a continuous square root on all of $\mathbb{C}$.
Comment: @HenningMakholm No, think about $e^{i(\pi-h)}, e^{i(-\pi+h)}$ for small $h>0.$
Comment: You haven't defined $f$, on $\mathbb C$. You've just given $f$ a different name, $\sqrt{z}$. How do you define $\sqrt{z}$ so that it is unique?
Comment: @DanielFischer : Umm why ? Yes , truely I haven't defined square root ...
Comment: @zhw: Hm, right. So we need to exclude a whole wedge of the complex plane, not just the negative real axis.
Answer: So the problem is that you can't define $\sqrt{z}$ to be even continuous on $\mathbb C$.
The reason is that, as you go along the circle $z=e^{i\theta}$ as $\theta\in[0,2\pi)$, if you want $\sqrt{z}$ to remain continuous (and $\sqrt{1}=1$) you'd need $\sqrt{z}=e^{i\theta/2}$. But then as $\theta\to 2\pi$, we have $z=e^{i\theta}\to 1$ and $\sqrt{z}=e^{i\theta/2}\to e^{i\pi}=-1$.
There are a number of ways around this sort of problem in complex analysis.

We can define $\sqrt{z}$ as a multi-valued function with two possible values. As you can see, in the above argument, we got $\sqrt{1}=\pm 1$, for example.
We can define $\sqrt{z}$ so that it remains undefined (or defined and discontinuous) on some line (or more generally a curve) starting at zero and going to infinity. The most common way to do this is to leave $\sqrt{z}$ undefined on the negative real line $(-\infty,0)$, which is simplest. (This always strikes me as funny because when we first learn about complex numbers, we are told $i=\sqrt{-1}$ and then we are told that $\sqrt{z}$ is left undefined at $z=-1$. But those are essentially two different usages of the "square root" symbol. In particular, $i$ is not actually defined as the square root of $-1$, that is just a motivating idea.)
We can define the notion of a branch of a function. This is a deeper concept, both related to the concept of the cut and the multi-valued view of the function.
Comment: As zhw pointed out above, the last paragraph is not true -- in particular the principal square root on $\mathbb C$ minus the negative real axis is not uniformly continuous.
Comment: Whoops, yes, of course. Thanks @HenningMakholm
Answer: An additional answer to clarify some minor details. Here's the Riemann surface of the square root map:

The map contains two branches. The two branches intersect at the negative-axis $(-\infty,0]$.
On this surface, you can preserve the notion of continuity using the convention of counterclockwise continuity. In other words, if you want to cross between branches, then you cross them in the order you stitched them together using a suitable branch cut.
In order to establish this convention however, you need to consider a cut that separates the two branches, which is the joining curve of the two sheafs. This way, the upper sheaf is smoothly connected to the lower sheaf, forming a single surface.
Precisely because the map $z^{1/2}$ is two-valued on $(0,+\infty)$ (i.e., $\sqrt{x}=\pm\sqrt{|x|}$), one convention is to use the positive real axis as the branch cut of this map (as in the second figure).
Then, if you constrain your $x,y$ in each branch separately, you can use the regular argument to prove that each branch is uniformly continuous on its respective domain.

If you allow however a domain such as the one shown on the pic above, either crossing your cut or crossing after encircling, you can see that there are going to be problems. In this case, you can choose your $x$ and $y$ to be very close on the complex plane, say $x=x_0+\epsilon i$, $y=x_0-\epsilon i$, with $x_0\in\mathbb{R}^+$ and some $\epsilon\gt 0$ and then uniform continuity will fail, because although $|x-y|=|x_0+\epsilon i-x_0+\epsilon i|\le 2\epsilon$, you use different branches of the map, so for any $x_0\in\mathbb{R}^+$, with $\sqrt{|x_0|}\gt\epsilon$:
$$|\sqrt{x}-\sqrt{y}|=|\sqrt{x_0+\epsilon i}-(-\sqrt{x_0-\epsilon i})|\gt |2\sqrt{x_0}|\gt 2\epsilon$$
The net effect of the above is that you are prevented from choosing a domain that wraps around the origin or crossing the branch, so continuity is preserved by the counterclockwise continuity convention and hence you can say the map $z^{1/2}$ is uniformly continuous on $\mathbb{C}$, which is qualified as saying that each branch of the map (i.e. the principal and the secondary branch) is uniformly continuous on its respective domain $\mathbb{C}\setminus (0,+\infty)$.


Tomcat's Index page showing on site when browsed by IP

Question: I have a Tomcat 5.0.27-2 server (I know... old) and Apache 2.0.46-77 server running and serving apps up just fine currently.  The problem we are experiencing is that if I navigate to http://www.mysite.com/index.jsp, I see the expected JSP.  However, if i navigate to (broken up for posting purposes) http:// 220.127.116.11 /index.jsp (the site's external ip address that is NATed to 192.168.0.20), I see the default "Tomcat welcome" jsp.  One additional tidbit, if i go to http:// 192.168.0.20 /index.jsp, I see the correct site.  It's only when going through NAT that i see the tomcat page.
I'm sure it's something in the server.xml or web.xml, but I don't know what.
Before you say "Upgrade your tomcat", I know we need to do that, but this is for an immediate issue and we don't have the time available for migration and thorough testing.  Eventually, we will upgrade to Tomcat6, just not today.
We are hosting several sites on the server, but for this site the server.xml has the following:
<Host name="mysite.net" appBase="/mysite_root/ROOT" >
   <Alias>22.214.171.124</Alias>
   <Context path="" docBase="" debug="0" reloadable="true" crossContext="true" />
</Host>

<Host name="www.mysite.net" appBase="/mysite_root/ROOT" >
   <Alias>18.104.22.168</Alias>
   <Context path="" docBase="" debug="0" reloadable="true" crossContext="true" />
</Host>

<Host name="mysite.com" appBase="/mysite_root/ROOT" >
   <Alias>22.214.171.124</Alias>
   <Context path="" docBase="" debug="0" reloadable="true" crossContext="true" />
</Host>

<Host name="www.mysite.com" appBase="/mysite_root/ROOT" >
   <Alias>22.214.171.124</Alias>
   <Context path="" docBase="" debug="0" reloadable="true" crossContext="true" />
</Host>

Answer: It's probably configured to do name based hosting... is there a Host tag in the server.xml with an appBase attribute?  If so, check what it is set to and what the default is.
Comment: I updated my original post with the server.xml for that host.  I've probably got something configured wrong.
Answer: This can happen when you have Tomcat answering on the host's IP address itself, rather than on 127.0.0.1.
If what you are aiming to do is have Apache act as your front door and proxy all requests to Tomcat, then you should make Tomcat bind to localhost, not to the host's IP address. Then you can use mod_proxy to forward requests, and not have anybody hitting Tomcat directly. This is well-described in the Apache docs and pretty common, so it shouldn't be too hard to change over.
Comment: I think this has something to do with NAT.  Internal IP works ok, NAT ip shows tomcat.
Comment: Those issues will probably go away if you bind Tomcat to `localhost` and let your RP do its job.
Answer: You can set a rewrite rule in apache that redirects all request that don't start with http://www.mysite.com to http://www.mysite.com.


MVC 3, Elmah and The view 'Error' or its master was not found

Question: I am working on a legacy website that uses MVC 3, elmah and nhibernate. The Elmah log has literally thousands of " The view 'Error' or its master was not found" errors.  I assume that it is covering up the real error.  I cannot figure out how to have the real error get logged by Elmah.
As a means to attempt to debug, I added  - return RedirectToAction("noWhere"); - to force an error.  Locally I get a .net screen that simply says "An exception occurred while processing your request..." on staging I get YOSOD screen telling me to set the web.config customerrors node.  Both have the customerrors set to on.
The web config has the following:
 <pages>
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.WebPages" />
  </namespaces>
</pages>
<httpModules>
  <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
  <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
  <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
</httpModules>

  <customErrors mode="On" defaultRedirect="~/Views/Shared/PageNotFound">
      <error statusCode="404" redirect="~/Views/Shared/PageNotFound" />
      <error statusCode="500" redirect="~/Views/Shared/PageNotFound" />
  </customErrors>

The Global.asax has:
 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
         filters.Add(new ElmahHandleErrorAttribute());
    }

The Elmah class has
public class ElmahHandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        base.OnException(context);
        var e = context.Exception;
        if (!context.ExceptionHandled // if unhandled, will be logged anyhow
            || RaiseErrorSignal(e)    // prefer signaling, if possible
            || IsFiltered(context))   // filtered?
            return;
        LogException(e);
    }

and the baseController class has:
protected ViewResult PageNotFound()
    {
        Response.StatusCode = (int)HttpStatusCode.NotFound;

        return View("PageNotFound", PageViewModelBuilder.UpdateSiteProperties(new PageViewModel()));
    }

    protected ViewResult PageBadRequest()
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return View("PageNotFound", PageViewModelBuilder.UpdateSiteProperties(new PageViewModel()));
    }

Any help on getting the correct errors to log would be appreciated....
Answer: Change "~/Views/Shared/PageNotFound" to "~/Views/Shared/PageNotFound.aspx" (or "~/Views/Shared/PageNotFound.chtml") in your web.config and make sure you have PageNotFound.aspx in your Shared folder.
Comment: yeah, change it to that then. I have edited my answer. Did it solve your problem? Please mark as answer if it did.
Comment: Thanks - but adding the cshtml causes a httpexception to be thrown and does not affect the original problem
Comment: What's the httpexception you are getting now? I think if you solve the error, elmah will only log related real erros.
Comment: System.Web.HttpException at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute -  statusCode="404"


objective c accessing public method

Question: I try to access a public method from another class. I already tried many examples I found in the web, but they didn't work in the way I wanted them to.
Class1.h
@interface anything : NSObject {

    IBOutlet NSTextField *label;

}

+ (void) setLabel:(NSString *)string;
- (void) changeLabel:(NSString *)string2;

Class1.m
+ (void) setLabel:(NSString *)string {

    Class1 *myClass1 = [[Class1 alloc] init];

    [myClass1 changeLabel:string];
    NSLog(@"setLabel called with string: %@", string);

}

- (void) changeLabel:(NSString *)string2 {

    [label setStringValue:string2];
    NSLog(@"changeLabel called with string: %@", string2);
}

Class2.m
- (IBAction)buttonPressed {

    [Class1 setLabel:@"Test"];

}

Very strange is that in the NSLogs, everything is fine, in both NSLogs, the string is "Test", but the textField's stringValue doesn't change!
Comment: You mixed up class and object methods.

The example doesn't really make sense.
You just temporarily create an object in `+ setLabel:`, but you never do something with it/never return it.

Tell me what you want to do so I can help you.
Comment: Why are using a static method? Is that a singleton?
Comment: @RamyAlZuhouri No it's not singleton, that would require a static variable.
Comment: Yeah I see it well now, he's allocating a new class instance: non sense.
Answer: - and + don't mean public or private
- stands for methods that you can call on objects of the class and
+ stands for methods that can be called on the class itself.
Comment: In other words, `+` means static and `-` means non-static
Comment: Good answer, though technically these are *methods*, not functions.
Comment: ahh okay.. does that differ from java or did I get something totally wrong?
Comment: there basically are no private functions in objective-c... every function defined in the header is public... if you still want to define private functions so that they are mentioned somewhere, you add a block within your .m like described in http://stackoverflow.com/a/651852/232812
Answer: Here a short example for what you can do:

The Custom Class
@interface ITYourCustomClass : NSObject
@property (strong) NSString *title;

- (void)doSomethingWithTheTitle;
@end

@implementation ITYourCustomClass
- (void)doSomethingWithTheTitle {
    NSLog(@"Here's my title: %@", self.title);
}
@end

Using it
@implementation ITAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    ITYourCustomClass *objectOfYourCustomClass = [[ITYourCustomClass alloc] init];
    [objectOfYourCustomClass doSomethingWithTheTitle];
}

@end

Class and object methods
Declaring a method with + means, that you can call the method directly on a class.
Like you did it with [myClass1 setLabel:@"something"];.
This doesn't make sense. What you want, is creating a property.
A property is saved in an object, so you can create an object ITYourCustomClass *objectOfYourCustomClass = [[ITYourCustomClass alloc] init]; and setting the properties objectOfYourCustomClass.title = @"something". Then you can call [objectOfYourCustomClass doSomethingWithTheTitle];, which is a public object method.
Comment: okay.. I think I got something wrong with these + and - I am new to mac development, I develop iPhone apps for 2 years now. I connected Class1 and Class2 to two different nib files which are loaded and one contains a label and the other a textfield, I just want to change the label in the one window with the textfield in the other window. With the example you gave me, I get exactly the same thing as before: the NSLogs give me my changed title but the label itself doesn't change if I call -doSomethingWithTheTitle from another class
Comment: @VincentFriedrich So how do you use Class1 and Class2 in Interface Builder? You usually have a view controller, or a window controller where you manage such things. Or you can add objects to connect them like the `AppDelegate` class in the initial nib file.
Comment: yes, I added an Object and named it "Class1" and manage everything from there. In the windowController I don't do anything.. that's my first try on a mac app. I did this with the object because I had several problems using an nsviewcontroller or windowcontroller
Comment: Did you connect the text field to the outlet in your IB?
Comment: @VincentFriedrich Is there a chance for you to publish it on Github? It's really hard to find an error like this.
Answer: You're trying to access an instance variable with a class method. You should convert the +setLabel: method to -setLabel:, and call it like this:
[_myClass1Variable setLabel:@"Test"];

Additionally, what's -setStringValue? If you're just trying to change the text of the UILabel you need to call -setText:.
Answer: I guess label would be a NSTextField, and you are tring to set its value without loading that XIB, resulting that your awakeFromNib is not getting called. And the outlet will not be bound that that label.

objective c accessing public method


What is the name given to the set of numbers between quartiles

Question: It is my understanding that quartiles are the three points in a ranked data set which divide the data into four equal groups.
What are the groups called? How would I say a number belonging to the ranked data set belongs to a certain group? What are the various names given to the groups?
I also understand that quartiles might mean something else when applied to different fields, where they might use it not as the points but the range of data.
Comment: I've seen instantly forgettable distinctions between _tertile_ and _tercile_. I am the last person to sneer at Latin, which was a major part of my education and much enjoyed, but I think that it's unrealistic to expect people to know so many terms, or to expect that people will look them up. It's much simpler to introduce the term _quantile_ as soon as possible in people's education.
Comment: Terciles are used to describe 3 groups, quintiles for 5, deciles for 10, ventiles for 20. What's wrong with using quartiles for 4 groups? In terms of the information between the intervals, are you referring to *quantiles*?
Comment: Two possibilities: 1. Variable x stratified by quartiles: low, low-median, median-high, high
2. Quartile bins
Comment: The longest list of quantile terms I know is elsewhere on CV: https://stats.stackexchange.com/questions/235330/iles-terminology-for-the-top-half-a-percent I would be delighted to learn of (a) a more complete list or (b) additions to the list. To modify an old joke, minutiae are  just minutiae, but the cataloguing of minutiae is real scholarship.
Answer: I don't think there is a universally accepted answer.
Some people are happy also to call the groups quartiles; and are thus explicitly or implicitly optimistic that any ambiguity will not bite, or at least can be clarified quickly in context, e.g. by inspection of some suitable table, graph and/or algebraic definition. There is a long history of such usages, sometimes distinguished by nuance, e.g. that the quartiles (values) may be called the lower quartile, median and upper quartile, while the quartiles (bins) may be called the first, second, third and fourth quartiles. (Such practice reminds me of those who want means to be population quantities and averages to be sample quantities, which to me has never seemed very convincing, not least because I really want the freedom to refer to sample means.)
Others would regard quarters as an alternative term.
The verbal alternatives all appear to buy greater precision by being more long-winded (and to some tastes more pedantic), say quartile-based bins, classes, groups or intervals.
In many ways the best solution is to avoid special words altogether: to be simply quantitative and talk about the first or lowest 25%, second 25%, and so on. [Grateful nod to @Glen_b for reminding me of this common practice.]
Yet another alternative is to avoid any such terminology altogether, but this is not always possible. There isn't a universal notation for quantiles either: for example, there are many idiosyncratic notations for median, but none seems even common.
The same terminological problem arises with any quantiles.
EDIT 8 Oct 2020 In almost five years since this answer I've seen the bins, classes or intervals delimited by quartiles (quantiles generally) often called by the same names. The ambiguity between intervals and the levels that delimit them is unfortunate, but seemingly here to stay. In practice the ambiguity does not bite hard. The natural selection at work is that longer-winded terminology such as quartile-based bins evidently seems too fussy to find favour.
Comment: An excellent answer. I find it amazing, and somewhat amusing that we really don't have one widely accepted non-ambiguous term for it, but we don't. [I am not even consistent within myself -- I would lean toward calling them "quarters", (usually adding "of the data"), but given its lack of wide use I'm as likely to say something else, like "lowest 25%" for example, or some longer phrase like "below the lower quartile", "between the median and upper quartile".]
Comment: I'd recommend against it personally. That usage blurs a key term. The fact that there is not universal agreement on a single best terminology doesn't exclude there better alternatives.
Comment: @Glen_b Thanks, especially for the reminder about lowest 25% etc, which certainly deserves mention in any complete answer, as now edited.
Comment: Also **bucket**. Again, it can refer to either the subinterval (i.e. max and min values), or the set of values falling in that subinterval.
Comment: Thanks for the answer Nick Cox (+1) and @Glen_b for the additional info. I'm surprised there is no conventional term for the groups. It seems like an obvious thing to use once the quarters have been created and to talk about it with others. I will mark it as the answer in a couple days to see if there's any other responses.
Comment: Would it be considered wrong to use quartiles that way, where one would want to discuss which group one of the numbers belong to?


How to find all groups that have exactly 3 subgroups?

Question:
How to find all groups that have exactly 3 subgroups?

Any group must have identity and itself as subgroups, so we just need to find all the groups that only have one proper subgroup. I think that for a prime $p$ the group $\mathbb Z/p^2\mathbb Z$ has only one proper subgroup (for example, $\mathbb Z/4\mathbb Z$, $\mathbb Z/9\mathbb Z$). Are there any other possibilities?
Answer: Note that if two distinct primes divide the order of the group, then it will have subgroups of each of these orders, so only one prime can divide the order of the group.
Also, a $p$-group has subgroups of any order dividing the order of the group, so the order must be $p^2$.
Finally, a group is cyclic iff it has exactly one subgroup of any order dividing the order of the group, hence our group must be cyclic.
In conclusion, $\mathbb{Z}/p^2\mathbb{Z}$ is the only possibility, and these satisfy the property for all primes $p$.
(For infinite groups, it is easy to check that this property can never hold.)
Comment: @Jack No, it has $5$, when we include the entire group and the trivial subgroup (which we do here). We are not dealing with the subgroups up to isomorphism.
Comment: There might be something wrong with my understanding. I don't get the "cyclic" part of the argument. Why ${\mathbb Z}\big/p^2{\mathbb Z}$ is the only possibility? ${\mathbb Z}_2\oplus{\mathbb Z}_2$ has $3$ subgroups up to isomorphism.


Python script not downloading all PDFs in the page? (Although it appears as it is downloading them!) It stops after a certain number of them

Question: So, this is the code for downloading all the PDFs in the page:
import os
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

#Website with translations of hieroglyphs
url = "https://mjn.host.cs.st-andrews.ac.uk/egyptian/texts/corpus/pdf/"

folder_location = "MY FOLDER"

#If there is no such folder, the script will create one automatically
if not os.path.exists(folder_location):os.mkdir(folder_location)

response = requests.get(url)
soup= BeautifulSoup(response.text, "html.parser")
for link in soup.select("a[href$='.pdf']"):
    name = "".join(x for x in link.string if x.isalnum())
    filename = os.path.join(folder_location, name + ".pdf")
    print(filename)
    with open(filename, 'wb') as f:
        f.write(requests.get(urljoin(url,link['href'])).content)

The strange thing is that THE SCRIPT GOES ON WITH ALL 325 FILES, and in the console it prints the message as if it's downloading all the files, but the folder stops at 95 for some reason. As if it's processing all of them, but stops after 95 (i.e. after the 'books' section of the webpage).
No clue what's happening!
Comment: Have you checked that the filenames it's generating to save the results to are not overlapping? I.e. it's not overwriting a file it wrote previously for some of the later results?
Comment: The length of unique is 94 versus 325 total so overwrites.
Comment: Ooh, so the website actually contains repetitions, right? I thought they were all unique, but apparently it separates them by category and puts them more than once. Thank you, mystery solved!
Answer: what the other commentors said:
linklist = []
for link in soup.select("a[href$='.pdf']"):
    name = "".join(x for x in link.string if x.isalnum())
    filename = os.path.join(folder_location, name + ".pdf")
    linklist.append(filename)
filenames =  list(set(linklist))


Retrofit 2.0 - unable to invoke no-args constructor for interface

Question: I am creating an android app that would upload data to a database using Retrofit2. When I submit the data it goes to the database, but an error always says this unable to invoke no-args constructor for interface. I tried searching for different solutions but don't seem to work.
This is my API Class:
import javax.xml.transform.Result;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface RegisterAPI {

@FormUrlEncoded
@POST("insertText.php")
retrofit2.Call<Result> createUser(
        @Field("name") String name,
        @Field("age") String age);

}

And this is my InsertActivity Class:
public static final String ROOT_URL= "https://MYURL/";

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

    editTextName = (EditText) findViewById(R.id.editTextName);
    editTextAge = (EditText) findViewById(R.id.editTextAge);

    buttonRegister = (Button) findViewById(R.id.buttonRegister);

    buttonRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            insertUser();
        }
    });
}

  public void insertUser(){

    String name = editTextName.getText().toString().trim();
    String age = editTextAge.getText().toString().trim();

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    RegisterAPI service = retrofit.create(RegisterAPI.class);

    Call<Result> call = service.createUser(
           name,
           age
    );

    call.enqueue(new Callback<Result>() {
        @Override
        public void onResponse(Call<Result> call, Response<Result> response) {
            Toast.makeText(getApplicationContext(), "SUCCESS", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(Call<Result> call, Throwable t) {
            Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
        }
    });

}

Answer: It happens because javax.xml.transform.Result is an interface, so, when you get a response, the Gson deserializer will try to convert the response to that interface that cannot be created.
To solve it, you can pass an implementation of javax.xml.transform.Result.
By the way, I'm pretty sure you are using the wrong import for Result.
Comment: Yes sir you are correct. Thanks again for the help!


Does the NHL provide guidelines for collecting stats?

Question: Does the NHL or any other league provide guidelines for use by league statisticians?  E.g. for giveaways, takeaways, checks, possession, etc.
Comment: Ok, maybe this is something the NHL only discusses internally at training sessions or other meetings
Comment: I'd love to see this existing somewhere, I'm just not convinced it does.  MLB puts it in their official rulebook, but NHL doesn't.
Answer: No, there is no official manual for statisticians from NHL on the web. There are only some articles explaining some advanced stats like Corsi, Fenwick, PDO... (https://www.nhl.com/lightning/news/hockey-analytics-101-understanding-advanced-stats-and-how-theyre-measured/c-735819).
However there exists an ice-hockey statisticians manual from NCAA where the statistics rules are the same as in the NHL (http://fs.ncaa.org/Docs/stats/Stats_Manuals/IceHockey/2021.pdf).


Facebook login - stays at white web page SWIFT

Question: In my LoginViewController, I implemented the FBSDKLoginButtonDelegate and imported the FBSDKLoginKit & FBSDKCoreKit. My code in viewDidLoad is as appears:
    //setting up facebook login button
    var facebookLogin = FBSDKLoginButton()
    //want this button to conform to this protocol
    facebookLogin.delegate = self
    facebookLogin.readPermissions = ["public_profile", "email",   "user_friends"]
    facebookLogin.frame = CGRectMake(20, 359, 335, 30)
    self.view.addSubview(facebookLogin)

Here's the code for the button:
    public func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult
         result: FBSDKLoginManagerLoginResult!, error: NSError!) {

    if error != nil {
        print(error.localizedDescription)
        return
    } else {
      print("No error")
      self.performSegueWithIdentifier("loginToFeed", sender: self)
    }

}

After logging in, the page stays at this white screen instead of going back to the app. So I go ahead and press "Done" to manually go back to the app and my console prints that there is no error and it proceeds to going to the feed. Now the next part that's interesting is that I'm not logged in despite there being no error at login. Do you know what's going on here? Am I missing a step?
Comment: Turns out that on iOS 9 when UIApplicationDelegate's `application:openURL:options:` is implemented, `application:openURL:sourceApplication:annotation:` will not get called. http://stackoverflow.com/a/32300235/3052059
Answer: As stated above missing app delegate but in two places.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}

and
func application(application: UIApplication,
    openURL url: NSURL,
    sourceApplication: String?,
    annotation: AnyObject) -> Bool {
        return FBSDKApplicationDelegate.sharedInstance().application(
            application,
            openURL: url,
            sourceApplication: sourceApplication,
            annotation: annotation)
}

Answer: The AppDelegate was missing:
func application(application: UIApplication,
             openURL url: NSURL,
             sourceApplication: String?,
             annotation: AnyObject?) -> Bool {
  return FBSDKApplicationDelegate.sharedInstance().application(application,
                                                  openURL: url,
                                                  sourceApplication: sourceApplication,
                                                         annotation: annotation)
 }

Comment: I edited it so the last bracket was included. You might've copy and pasted it without it? Sorry, this was the fix for me. Run through the set up instructions and double check to see if you missed something. That's what I did, you never know!
Answer: Here's my situation: I could use myapp to login with fb. Then when I close the app (back to home screen) and enter the app again, it presents me a blank screen. And I solved it by these:
In the app delegate:
func applicationDidBecomeActive(application: UIApplication) {
    FBSDKAppEvents.activateApp()
}

Also, I'm using the bridging file from this article:
http://www.brianjcoleman.com/tutorial-how-to-use-login-in-facebook-sdk-4-0-for-swift/
The bridging file looks like this:
#ifndef Bridging_Header_h
#define Bridging_Header_h

#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

#endif /* Bridging_Header_h */


Send get form without special characters.

Question: I'm know this is simple, but I've been searching everywhere for the answer. I think I maybe over thinking it and making too complicated.
Have a form that sends a get request to populate a listings page, I noticed that when I have the URL String =

../view.php?keyword=a+b all works great.

However, when user enters special character on form and url changes to:

../view.php?keyword=a+%2Cb I get no return values.

I've tried using urlencode() rules and also FILTER_SANITIZE_ENCODED, but can't see to get the code to work with special charters. I've also made sure I am using charset UTF-8.
How can I make the get request to ignore the special charters in the url?
CODE:
  <?php

    if (isset($_REQUEST["water-selection"]) || isset($_REQUEST["city-selection"]) || isset($_REQUEST["bed-selection"]) || isset($_REQUEST["bath-selection"]) || isset($_REQUEST["keyword"]) || isset($_REQUEST["price"]) || isset($_REQUEST["pending"])){
        $where = " WHERE 1=1 ";
        if (isset($_REQUEST["water-selection"]) && $_REQUEST["water-selection"]!="Water Selection"){
            if ($where != ""){ $where .= " AND ";}
            $where .= " field_RESIBDWR = '" . $_REQUEST["water-selection"] . "'";
        }
        if (isset($_REQUEST["city-selection"]) && $_REQUEST["city-selection"]!="City Selection"){
            if ($where != ""){ $where .= " AND ";}
            $where .= " field_City = '" . $_REQUEST["city-selection"] . "'";
        }
        if (isset($_REQUEST["bed-selection"]) && $_REQUEST["bed-selection"]!="Bed(s)"){
            if ($where != ""){ $where .= " AND ";}
            $where .= " field_Bedrooms >= '" . $_REQUEST["bed-selection"] . "'";
        }
        if (isset($_REQUEST["bath-selection"]) && $_REQUEST["bath-selection"]!="Bath(s)"){
            if ($where != ""){ $where .= " AND ";}
            $where .= " field_Bathrooms >= '" . $_REQUEST["bath-selection"] . "'";
        }

if (isset($_GET['keyword']) && '' !== trim($_GET['keyword'])) {
  $terms = explode(' ', $_GET['keyword']);
  $fields = array('ZipCode', 'MLNumber', 'RESIBDWR',
    'ListingOfficeName', 'RESIADDI', 'MarketingRemarks',
    'StreetNumber', 'StreetDirection', 'StreetName', 'StreetSuffix', 'State');
  $criteria = array();
  foreach ($terms as $term) {
    if (!$term) continue;
    $term = @mysql_real_escape_string($term);
    $c = array();
    foreach ($fields as $field) {
      $c[] = 'field_'.$field.' LIKE \'%'.$term.'%\'';
    }

    $criteria[] = implode(' OR ', $c);
  }

  if ($criteria) {
    $condition = '('.implode(")\nAND (", $criteria).')';
    if ($where) $where .= ' AND ('.$condition.')';
    else $where = $condition;
  }
}

        if (isset($_REQUEST["price"])){
            $price = explode(";",urldecode($_REQUEST["price"]));
            if ($where != ""){ $where .= " AND ";}
            $where .= " field_ListingPrice between " . $price[0] . " AND " . $price[1] . " ";
        }
        if (isset($_REQUEST["pending"])){
            if ($where != ""){ $where .= " AND ";}
            $where .= " field_Status = 'Pending'";
        }
    }
    else{
        $where = " WHERE `field_ZipCode` IN (SELECT zip FROM zipcodes)";
    }

    $sql = "SELECT count(id) as count FROM rc_Data $where";

  $res = mysql_query($sql,$con) or die('Query failed: ' . mysql_error() . "
\n$sql");
    $records_per_page = 10;

    while($row = mysql_fetch_array($res)){
        $total_rec = $row["count"];
    }

    $total_pages = ceil($total_rec / $records_per_page);

    $curr_page = 1;

    if (isset($_REQUEST["page"])){$curr_page=$_REQUEST["page"];}

    $start_index = ($curr_page-1) * $records_per_page;
    if ($start_index  <0) {$start_index = 0;}
    //$sql = "SELECT *, round(3956 *2 * ASIN( SQRT( POWER( SIN( ( {$lati} - field_Latitude ) * pi( ) /180 /2 ) , 2 ) + COS( {$lati} * pi( ) /180 ) * COS( field_Latitude * pi( ) /180 ) * POWER( SIN( ( {$longi} - field_Longitude) * pi( ) /180 /2 ) , 2 ) ) ),0) AS distance FROM rc_Data order by distance, (`field_ListingAgentMLSID` = 'H10207') DESC, `field_ListingAgentMLSID`, field_ListingPrice DESC, id desc limit {$start_index}, {$records_per_page}";
    //$sql = "SELECT *, round(3956 *2 * ASIN( SQRT( POWER( SIN( ( {$lati} - field_Latitude ) * pi( ) /180 /2 ) , 2 ) + COS( {$lati} * pi( ) /180 ) * COS( field_Latitude * pi( ) /180 ) * POWER( SIN( ( {$longi} - field_Longitude) * pi( ) /180 /2 ) , 2 ) ) ),0) AS distance FROM rc_Data order by (`field_ListingAgentMLSID` = 'H10207') DESC, `field_ListingAgentMLSID`, distance, field_ListingPrice DESC, id desc limit {$start_index}, {$records_per_page}";
    $sql = "SELECT *, round(3956 *2 * ASIN( SQRT( POWER( SIN( ( {$lati} - field_Latitude ) * pi( ) /180 /2 ) , 2 ) + COS( {$lati} * pi( ) /180 ) * COS( field_Latitude * pi( ) /180 ) * POWER( SIN( ( {$longi} - field_Longitude) * pi( ) /180 /2 ) , 2 ) ) ),0) AS distance FROM rc_Data  $where order by (`field_ListingAgentMLSID` = 'H10207') DESC, field_ListingPrice DESC limit {$start_index}, {$records_per_page}";
    $res = mysql_query($sql,$con) or die('Query failed: ' . mysql_error() . "
\n$sql");
    //echo $sql;

    unset($_GET['page']);
    $qs = http_build_query($_GET);
?>

Comment: You use `urldecode()` as well on your `$_GET['keyword']` to convert it back.
Answer: I don't think the encode is the problem.
In this line:
$terms = explode(' ', $_GET['keyword']);

You explode the querystring keyword variable based only on space.
If you send keyword=a+%2Cb as a parameter, you can see by echoing $_GET['keyword'] that this is automatically translated to a ,b.
So when you split by space, you get two terms: a and ,b, which is not what you want.
Later you use $terms:
foreach ($fields as $field) {
  $c[] = 'field_'.$field.' LIKE \'%'.$term.'%\'';
}

So you basically add sql where constraints using LIKE '%a%', LIKE '%,b%'.
You must define which delimiters to split keyword, so something like:
$terms = explode(' ,', $_GET['keyword']);
would make that second example work (i.e. producing LIKE '%a%', LIKE '%b%').
EDIT
A stronger form of explode is preg_split. Try this:
$terms = preg_split("/[\s,]+/", $_GET['keyword']);

Comment: Hey Niloct, thanks for replying! I've added the explode update: $terms = explode(' ,',urldecode($_GET['keyword'])); still same issue with no results
Comment: Can you add `echo $sql;` below the line `$sql = "SELECT count(id) as count FROM rc_Data $where";` and paste the SQL output in the question ? I also changed the answer to a new try.
Comment: You **don't** need `urldecode` function around `$_GET['keyword']`!


Couldn't generate Excel sheet report using Jasper report library

Question: I tried to generate Excel report, using the below code.
import java.util.*;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.export.OutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleXlsReportConfiguration;

public class FirstReport
{
public static void main(String[] args)
{
    try
    {

        JRXlsExporter exporter = new JRXlsExporter();
        exporter.setExporterInput(new         SimpleExporterInput("FirstReport.jrxml"));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput("C://sample_report.xls"));

        SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();
        configuration.setOnePagePerSheet(true);
        configuration.setDetectCellType(true);
        configuration.setCollapseRowSpan(false);
        exporter.setConfiguration(configuration);
        exporter.exportReport();

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

}
}

This program is generating following exception
net.sf.jasperreports.engine.JRRuntimeException:            net.sf.jasperreports.engine.JRException: Error loading object from file :   FirstReport.jrxml
    at net.sf.jasperreports.export.SimpleExporterInput.(SimpleExporterInput.java:157)
    at FirstReport.main(FirstReport.java:33)
    Caused by: net.sf.jasperreports.engine.JRException: Error loading object     from file : FirstReport.jrxml
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:131)
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:103)
    at     net.sf.jasperreports.engine.util.JRLoader.loadObjectFromFile(JRLoader.java:94)
    at net.sf.jasperreports.export.SimpleExporterInput.    (SimpleExporterInput.java:153)
    ... 1 more
    Caused by: java.io.StreamCorruptedException: invalid stream header: 3C3F786D
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.(Unknown Source)
        at net.sf.jasperreports.engine.util.ContextClassLoaderObjectInputStream.             (ContextClassLoaderObjectInputStream.java:57)
    at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:126)
        ... 4 more
Comment: There seems to be a Problem with FirstReport.jrxml: StreamCorruptedException: invalid stream header: 3C3F786D
Answer: Parameter of exporter.setExporterInput() must be based on JasperPrint object (not jrxml file).
You can see it at net.sf.jasperreports.export.SimpleExporterInput class. Some code from this class:
/**
 * Creates an {@link ExporterInput} object with a single item wrapping the {@link JasperPrint} object that will be exported.
 * If you already have a JasperPrint object, you can pass it to the exporter using this type of input.
 */
public SimpleExporterInput(JasperPrint jasperPrint)
{
    if (jasperPrint != null)
    {
        this.items = new ArrayList<ExporterInputItem>();
        items.add(new SimpleExporterInputItem(jasperPrint));
    }
}

/**
 * Creates an {@link ExporterInput} object with a single {@link JasperPrint} item read from the provided input stream.
 * If you want to read the JasperPrint object from an input stream (like a web location), you can pass the stream to this constructor.
 */
public SimpleExporterInput(InputStream inputStream)
{
    if (inputStream != null)
    {
        JasperPrint jasperPrint = null;
        try
        {
            jasperPrint = (JasperPrint)JRLoader.loadObject(inputStream);
        }
        catch (JRException e)
        {
            throw new JRRuntimeException(e);
        }
        this.items = new ArrayList<ExporterInputItem>();
        items.add(new SimpleExporterInputItem(jasperPrint));
    }
}

JasperPrint object is result of execution method fillReport. For example:
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReportFile, reportParameters, dataSource);

In this code jasperReportFile is object which corresponds with compiled report file (not jrxml). In your case FirstReport.jasper
Some code from net.sf.jasperreports.engine.JasperFillManager:
/**
 * @see #fill(String, Map, JRDataSource)
 */
public static JasperPrint fillReport(
    String sourceFileName,
    Map<String,Object> params,
    JRDataSource dataSource
    ) throws JRException
{
    return getDefaultInstance().fill(sourceFileName, params, dataSource);
}
....
    /**
 * Fills the compiled report design loaded from the specified file and returns
 * the generated report object.
 *
 * @param sourceFileName source file containing the compile report design
 * @param params     report parameters map
 * @param dataSource     data source object
 * @return generated report object
 */
public JasperPrint fill(
    String sourceFileName,
    Map<String,Object> params,
    JRDataSource dataSource
    ) throws JRException
{
    File sourceFile = new File(sourceFileName);

    JasperReport jasperReport = (JasperReport)JRLoader.loadObject(sourceFile);

    JasperReportsContext lcJrCtx = getLocalJasperReportsContext(sourceFile);

    return JRFiller.fill(lcJrCtx, jasperReport, params, dataSource);
}

HTH


Até que ponto devemos seguir o OCP?

Question: Ao desenvolver uma tela para uma determinada parte de um sistema, me deparo com uma situação clássica de possuir alguns ifs para determinar qual ação deverá ser executada. Logo associei esse caso a exemplos de violação do OCP.
Contudo, vi que a tela é bem coesa e com um escopo definido, onde não vejo, e nem a equipe vê em algum momento próximo, uma possível mudança nas ações. Ou seja, não serão, teoricamente, adicionados novas condições.
Em casos como esse, deve-se seguir o OCP fielmente, criar a classe base e suas extensões, ou manter os ifs? levando em consideração que não devem aparecer novas demandas?
Esse é o código atual que teoricamente viola o OCP.
Controlador:

        [HttpPost]
        public ActionResult InserirOrcamento(OrcamentoViewModel orcamento, string acao)
        {

            if (acao == "consultaCPF")
            {
                var retornoConsultaCPF = OrcamentoService.consultaCPF(orcamento);

                return Json(retornoConsultaCPF, JsonRequestBehavior.AllowGet);
            }

            if (acao == "listaTipoProduto")
            {
                var retornoTipoProduto = orcamento.lstTipoProduto = OrcamentoService.listaTipoProduto(orcamento);

                return Json(retornoTipoProduto, JsonRequestBehavior.AllowGet);
            }
        }

Service
 public class OrcamentoService
    {
        public static OrcamentoViewModel consultaCPF(OrcamentoViewModel orcamento)
        {
            using(ToqueEntities db = new ToqueEntities()){

                var retorno = db.PESSOA_FISICA
                                        .Where(x => x.PESF_CPF == orcamento.cpfPessoa)
                                        // .Join(db.CONTATOS, x => x.PES_CDID, c => c.PES_CDID, (x,c) => new { x, c })
                                        .Select(x => new OrcamentoViewModel
                                        {
                                            cpfPessoa = x.PESF_CPF,
                                            nomeClienteOrcamento = x.PESF_NOME,
                                            sobrenomeClienteOrcamento = x.PESF_SOBRENOME,
                                            PES_CDID = x.PES_CDID
                                        }).FirstOrDefault();

                    if (!retorno.Equals(null))
                    {
                        var lstContatos = db.CONTATOS.Where(x => x.PES_CDID == retorno.PES_CDID && x.CON_TIPOCONTATO != "EMAIL")
                        .Select(x => x.CON_CONTEUDO)
                        .ToList();

                            if (!lstContatos.Count().Equals(0))
                            {
                                foreach (var item in lstContatos)
                                {
                                    retorno.Contatos += item + ";";
                                }
                            }
                            else
                            {
                                retorno.Contatos = "";
                            }
                    }

                orcamento.nomeClienteOrcamento = retorno.nomeClienteOrcamento;
                orcamento.sobrenomeClienteOrcamento = retorno.sobrenomeClienteOrcamento;
                orcamento.cpfPessoa = retorno.cpfPessoa;
                orcamento.Contatos = retorno.Contatos;

                return orcamento;
           }
        }

Answer: Open Close Principle
Na minha visão o OCP é o princípio mais complicado de seguir dentro do SOLID. E frequentemente ele é adotado como receita de bolo. Por sorte está questionando ele.
Não sei se está considerando que escrito uma classe não pode mais mexer nela em hipótese alguma, se fosse assim que o princípio pregasse ele seria a coisa mais esdrúxula já inventada. Você pode mexer nela, só tem que tomar cuidado com os contratos.
Note que o que está falando não é mexer nem mesmo na classe, é apenas mudar o método, e até onde entendi muda a implementação sem mexer no resultado final.
Você sempre deve se questionar porque deve fazer algo que mandaram você fazer. Precisa ter uma justificativa, precisa ter um ganho colocar algo em um código, especialmente se ele complica o código e o valor não é muito aparente.
O código
Eu acho que segregar responsabilidades é muito mais importante, e de certa forma demonstra estar fazendo em um ponto (criando o serviço que não sei se deveria ser um, mas enfim, isola). Se você faz isso você isola onde deve fazer modificação.
Parece ter consciência que é necessário dar coesão. Não vou entrar no mérito se está completamente coeso neste caso até por não conhecer todos os detalhes do problema, e não existe fórmula mágica que determine se é ou não coeso. Coesão é importante, seguir princípios não são, pelo menos não na mesmo proporção.
Eu nem posso afirmar que há violação do OCP aí, mas é verdade que tem coisas esquisitas como tratar de uma ação dentro de um método que deveria ser uma ação, eu acho que o problema aí é ferir o SRP porque essa action faz várias ações. Claramente ali são 2 actions diferentes, então está preocupado com um problema que vem depois de outro mais importante. E aí pode ficar mais óbvio a violação do OCP.
O entendimento correto do OCP é que se alguém for fazer alguma outra coisa diferente desta que está fazendo, ou seja, esse mesmo objeto deverá ser criado em um contexto diferente deste, então não deveria tratar tudo no mesmo objeto, deveria criar uma classe herdada desta adicionando a nova funcionalidade, assim dá flexibilidade sem mexer no que existe. Mas isso tem lá seu problema, cria acoplamento, dependência, dificulta certa flexibilidade. Por isso tem uma forma de delegação de função (talvez usando lambda).
Não vejo essa necessidade neste código.
Pra que usar OCP?
Por que deve manter algo aberto para extensão? Se não tiver um motivo não deve. Por exemplo String é um tipo que não está aberto para extensão em condições normais (todos os tipos em C# estão abertos para extensão através dos métodos de extensão, quando criaram esse princípio nem consideraram que uma linguagem poderia ter um mecanismo assim). Há muita gente que defende que as classes deveriam ser sealed por padrão de tão importante que é não deixar aberto o que não precisa. Extensão é problemática, só deve ter isto se for muito útil.
Por que o seu caso precisa ficar aberto para extensão?
E por que esta classe deveria ser fechada para modificação?
Essa ideia foi criada para dar uma certa estabilidade, garantir que sempre que alguém chamar isso acontecerá o mesmo. É uma boa ideia, mas já viu engenheiros consagrados sair fazendo isso em todo lugar?
Eles são pragmáticos, eles sabem que tentar fazer isso é complicado, em muitos casos é melhor até ter que fazer outras coisa e tornar o atual obsoleto em alguns casos extremos do que complicar algo para dar uma possível estabilidade e flexibilidade que talvez nunca seja necessária.
OCP no MVC
Pro meu entendimento o jeito que se faz o MVC não costuma causar esses problemas que são ditos se manter a classe aberta para modificação. Claro que tem que tomar algum cuidado, mas não é algo complicado, e de fato as pessoas mexem muito nessas classes que são ações, estendendo a capacidade do controlador ali mesmo. O mecanismo nem foi tão pensado em para ficar fechado para modificação e aberto para extensão.
Se alguém apresentar um possível problema eu posso mudar de ideia.
Outros problemas
Nem vou falar esses Equals() que são horríveis, apesar de funcionar. Mas isso pode ser um indício que não estão pensando com clareza no que fazer. Pode ser só estilo ruim escolhido e ter sido pensado. Tenho mais medo desse acao.executarAcao() em um dado que é do tipo String que me parece errado demais. Então tem aí preocupações muito mais sérias. Também não falei do problema da concatenação de strings que é mais básico. E não olhei se outras partes não tem problemas, ou se o ToList() é necessário aí ou está usado indevidamente como quase todo mundo faz. Também não parece muito adequado um método chamado ConsultaCPF() modificar o conteúdo do orcamento, ou até se ele deve ser mudado, isso é muito pior que violar o OCP. Parece que o código tem muitos outros problemas mais básicos do que seguir a modinha do SOLID.
Coloquei no GitHub para referência futura.
Comment: Isso não é uma *view*, isso é uma *action* de um *controller*. EU ach oque não está sabendo usar o MVC corretamente precisa resolver isso, você não deveria colocar uma *action* dentro de outra *action*, precisa reformular do esse *controller*, mesmo eu não vendo o resto.
Comment: agradeço por comentar esse ponto do acao.executarAcao(), não tinha visto que havia colocado, ele n faz parte do código em questão, faz parte da minha tentativa de implementar o OCP, eu vou até editar.
Comment: Eu coloquei uma string acao pois são ações executadas via Ajax. Por exemplo, o consultaCPF é para quando o usuário digitar o CPF e tirar o foco do input, ai é feita a consulta e retornas os dados dessa pessoa nos respectivos inputs, como o nome e o sobrenome. Ou seja tudo tem de estar nessa View InserirOrcamento para que depois eu submeta o formulário e consiga dar o devido processamento. Mas vou tentar quebrar em 3 Actions diferentes, agradeço a observação.
Comment: Sim, eu acabei de refatorar esse Controller, separei as 2 actions que estavam dentro dele. Bem mais organizado e de melhor manutenção. Realmente o problema do SRP estava bem mais latente e poderia vir a dificultar uma manutenção no futuro.  Eu acabei me expressando errado na colocação acima, quando disse "_view_", me referia à _view_ vinculada àquele _controller_ . Separando melhor,  vi que poderia retornar apenas o JSON e deixar o JS lidar com o preenchimento dos campos.
Comment: Como está usando como WebAPI, nem *view* tem.
Comment: Na verdade não, é ASP.NET MVC mesmo hahaha, apenas não pus a _view_ e o Javascript pois não achei pertinente à pergunta.
Answer: Sugiro estudar um pouco sobre a diferença entre o Any(), All(), Count() e Count, para que não tenha problemas de performance no código e legibilidade.
Por exemplo, trocar "!lstContatos.Count().Equals(0)" por lstContatos.Any() ou caso a variável seja uma List (como nesse caso, mesmo achando que não é necessário que seja) pode ser utilizado lstContatos.Count > 0.
Na minha opinião "!retorno.Equals(null)" fica bem ilegível, talvez trocar por "retorno != null" seja mais interessante.
Outro problema é a concatenação de strings, estude o quantidade de concatenações que serão feitas, e dependendo dela, verifique a necessidade de utilizar StringBuilder (mais performática para grandes quantidades de concatenações).

Até que ponto devemos seguir o OCP?


Exception while passing extras through intent

Question: I want to pass a string from 1 activity to another, although I have taken reference from many accepted answers from other threads, I am facing problem that I am not able to debug. When I comment extras.putString as shown in code below, Toast message shows the correct address which means value is being set properly and code works fine but when I use extras.putString(), I get NullPointerException and application closes due to exception.  There are many \n characters in my address string. Infact even if I use extras.putString("userAddress", "test") I get NullPointerException
Here is my Main Activity from which I want to call FBShare Activity:
Intent mIntent = new Intent(this, FBShare.class);
Bundle extras = mIntent.getExtras();
String currentAddress = getCurrentAddress(ourLocation);
Toast.makeText(getBaseContext(), getCurrentAddress(ourLocation), Toast.LENGTH_SHORT).show();
extras.putString("userAddress", currentAddress);
startActivity(mIntent);

And in FBShare Activity I am trying to fetch values as follows
strAddress = getIntent().getExtras().getString("userAddress");

Here is one thread which is doing similar thing.
Comment: look at @akki's answer, you're missing the `mIntent.putExtras(extras);`
Answer: Try directly putting extra on the intent:
mIntent.putExtra("Key", "Value")
Also, you retrieve the extra using
Intene t = getIntent();
String k="key";
if (t.hasExtra(k)) {
  s = t.getStringExtra(k);
  ...
}

The are get/put for many var types
Answer: try my code
Intent mIntent = new Intent(this, FBShare.class);
Bundle extras = new Bundle();
String currentAddress = getCurrentAddress(ourLocation);
Toast.makeText(getBaseContext(), getCurrentAddress(ourLocation), Toast.LENGTH_SHORT).show();
extras.putString("userAddress", currentAddress);
mIntent.putExtras(extras);
startActivity(mIntent);

hope this will work.
Answer: Intent mIntent = new Intent(this, FBShare.class);
String currentAddress = getCurrentAddress(ourLocation);
Toast.makeText(getBaseContext(), getCurrentAddress(ourLocation), Toast.LENGTH_SHORT).show();
mIntent.putString("userAddress", currentAddress);
startActivity(mIntent);

Bundle is not need in your case because it seems that you are only pasing a string you can use the above code..


4095 Selectors Limit on IE. How to split the Drupal 7 CSS compressed files?

Question: Here is my problem. Using Sass (from Zen theme) and on top of that Brunch, our compressed css file has over 4095 Selectors and is then compressed by Drupal (and still has over 4095 selectors in one files).
Do you know if there is a way to tell Drupal to compress files in smaller files in order to avoid the 4095 selector limit per files ?
Comment: Sorry I didn't get it. In your sass file collection you have more than IE limit 4095. Then you compile it to css and merge them & minify them with Brunch. But you don't want to exceed the 4095 per stylesheet? So you want Drupal to break the css for you, after you combine them with Brunch? Or you have 3-4 files that Drupal aggregates them and then you have a single file with many selectors?
Comment: I don't know about Zen, but with sass in you include the _*.scss files in your main style.scss. Why you don't try to separate some logic on different files?
Comment: Actually we have a lot of different .scss files but we also have Brunch that aggregate all the generated css files in one.
Comment: We have 4 files compressed generated by Drupal. If we could have something like 8 files instead, it might work. We are also looking into brunch configuration and that might not be related to Drupal.
Answer: Lets say your my_theme.info have
stylesheets[all][] = css/my_theme_1.css
stylesheets[all][] = css/my_theme_2.css
stylesheets[all][] = css/my_theme_3.css
stylesheets[all][] = css/my_theme_4.css

And you don't want to aggregate these files in a single one (exceed IE limit 4095 selectors)(also I assume that is already minified by Brunch)
Remove the above lines from your .info or comment out.
Then add an html preprocess function (on the main template.php or if you have an html.preprocess.inc file)
function my_theme_preprocess_html(&$variables) {
  drupal_add_css(drupal_get_path('theme', 'my_theme') . '/css/my_theme_1.css', array('preprocess' => FALSE));
}

The drupal_add_css will add the css but 'preprocess' => FALSE will prevent Drupal to aggregate them.
(It's a bit hacky but it works)
Comment: Thanks, your solution is good. We modified Brunch to generate 3 files instead of 1 and added the files directly in the template (without going through .info) I also had an other problem on top of that because we were using the CDN module (so I had to have the proper url if CDN was activated) :-D But now everything works on IE.
Answer: I found a very interesting module that can handle the 4095 limit for drupal compressed files and many other css and js related things
Advanced CSS/JS Aggregation Module


Is there a difference between super.getX() and simply x?

Question: I have a class that has a protected value x and I have another class that extends that class.
In the extended class is there any difference between return super.getX() and return x?
They both can visibly see the variable right? and I was under the impression that the values were exactly the same so is there a reason that my professor said to use super.getX() instead of just returning x?
example:
public int getX(){
    return x;
}

vs
public int getX(){
    return super.getX();
}

The reason for why I have 2 getX methods is because the extended getX does checks and applies manipulations to the value x depending on other values.
Answer:
The reason for why I have 2 "getX" methods is because the extended getX does checks and applies manipulations to the value x depending on other values.

I can use the same reason to answer your question. What if the base class's getX() did some "checks and manipulations to the value of x" before returning a value? In that case, return super.getX() would return a different value than return x.
Even if at the moment the base class method simply returns x, that might change in the future. If you want your sub-class's getX() to return a value that depends on the value returned by the base class's getX() (which may or may not be simply the instance variable x), you should use super.getX() instead of accessing x directly.
Answer: When overriding a method to execute some logic before or after the overridden method, the last one is called with super.foo().
Since you are overriding getX() to do checks and apply manipulations to the return value, it is good practice to call the super method with super.getX() even if it is a simple getter, because that is what is done when overriding methods.
Calling the superclass method also lets you automatically execute any logic in case the super method is changed. Let's say one day you change super.getX(): the change will automatically be reflected when calling getX().


Determinant of a symmetric, positive semidefinite, sparse integer matrix

Question: I'm looking for an algorithm that calculates the (log) determinant of a symmetric, positive semidefinite, sparse integer matrix.  Does such an algorithm exist that can exploit both sparsity and integer structure for faster calculation, compared to more general purpose determinant calculating routines?
Comment: This is a sensible question with mathematical content, but you may find it more helpful to ask it on the Computational Science stack exchange site, where people who know LINPACK hang out.
Comment: You can start with a band-matrix algorithm and then use block determinant algorithm.
Answer: The folks in the linear programming space look at similar problems. They don't need the determinant, but a typical first step in computing a determinant is an LU factorization, and that they are interested in.
The QSOPT_ex Rational LP solver probably has some code in there that will do the job for you, but you'll have to dig around for it. This paper by Cook and Steffy, "Solving Very Sparse Rational Systems of Equations", talks about QSOpt_ex and other approaches. Unfortunately, the links in this paper are stale, but perhaps some Google sleuthing can turn up an updated location for the code and test problems.
I've also seen references to a "fraction-free" LU factorization. This paper (PDF) talks about how to do fraction-free LU factorizations. However, it does not deal with sparse matrices. You could could perhaps adapt some simple sparse factorization code, like CSparse, and to work with the fraction-free or rational values.
Once you have an LU factorization, say $PA=LD^{-1}U$, then the determinant would simply be $\prod_i L_{ii} U_{ii} / \prod_i D_{ii}$. Obviously you can use arbitrary-precision integer multiplication and division to compute that exactly.
EDIT: I'm really not sure why I missed that your matrix was symmetric positive definite. Of course you could do sparse Cholesky then instead of sparse LU. In that case, check out Tim Davis' LDL, which is a very compact sparse factorization engine, that I am sure could be adapted readily to rationals.


Are sampling weights needed?

Question: I am looking to build a regression model to understand the impact of signing up on a website with sales. I took a random 200k sample of active customers (out of the 30 million or so).. it turns out none of them signed up on the website. So then, I took the population of people who signed up on the website in a given month (~30k).
So I have a dataset that consists of a random sample of 200k customers who did not sign up and
30k customers who did sign up.... I want to build my regression off of this.
Is there anything I need to take into consideration here? Do I need to apply sample weights or something like that, or is my test design ok?
Thank you for the help.
Answer: The way you've constructed this, the test design sounds quite simply as sales=A*signup, where sales is your sales indicator, A is your parameter, and signup is your flag variable for signing up.
As far as weighting, think about reasons why you might weight your customers differently. Is a certain customer more important to your question? (Maybe people in a certain country, people who purchased in the month of interest, etc). If you can clearly identify that weighting factor and have the data for it, I'd recommend adding that factor in as an additional variable in your model rather than directly adjusting each unit by an arbitrary weight.
One thing jumped out at me immediately. The sampling method you used isn't the same between the 200k and the 30k. You found the 30k from a given month. To eliminate error due to unequal sampling and potentially time dependencies, I would recommend you sample another 30k non-signups from the same month. Run the model using these two groups of 30k and set the 200k aside.
Comment: When do people use survery weights or sampling weights then?
Comment: It usually makes a lot more sense when compiling descriptive statistics as opposed to running a linear model like you are. Sampling methods may have certain biases that would mess up your descriptive statistics, thus weights can be used to adjust. Let's say you were trying to profile your customer sales by country, but you knew your database has half as many European customers as you actually have (maybe half were deleted). So your random sample would underrepresent the Europeans by a factor of 2x. Thus you would upweigh each European customer by 2x.

Are sampling weights needed?


Routes em CodeIgniter

Question: Gostaria de saber como faço para criar rotas no CodeIgniter.No momento,tudo que consigo sao rotas do tipo " www.site.com/index.php/pagina2 ".
Gostaria de criar rotas como " www.site.com/pagina2 "
Já tentei usar o tutorial da documentação do CodeIgniter 3
" $route['pagina2'] = 'controlador_pagina2'; " no arquivo de rotas e nada....
Acho que são chamadas rotas magicas na comunidade do Code.
Alguem saberia ajudar?
Comment: Possível duplicada: https://stackoverflow.com/questions/7618633/routes-in-codeigniter-automatically
Comment: Talvez este link possa ajuda-lo: http://www.universidadecodeigniter.com.br/rotas-no-codeigniter-do-inicio-ao-fim/
Comment: Não é duplicado,esté topico está no stackoverflow americano,esse é PT.

Já olhei esse tutorial e fiz exatamente igual,porem não funcionou nao :/

Vou dar uma olhada nesse topico que você me disse!
Answer: Minha versão do codeigniter é mais antiga que a atual. então.... Mas segue o exemplo:
altere seu htaccess para:
<IfModule mod_rewrite.c>

    RewriteEngine On

    # Remove /index/
    RewriteRule ^(.*)/index/?$ $1 [L,R=301]

    # Remove trailing slashes (prevents duplicate SEO issues)
    RewriteRule ^(.+)/$ $1 [L,R=301]

    # Removes access to the system folder by users.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php/$1 [L]

    # If not a file or directory, route everything to CI
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]
    # RewriteRule ^(.*)$ index.php/$1 [L] # This is an alternative

</IfModule>

No teu config:
$config['base_url'] = "http://www.seusite.com/";
# or use $config['base_url'] = "";
$config['uri_protocol'] = "REQUEST_URI";
$config['index_page'] = '';

e no teu Routes: (https://www.codeigniter.com/userguide2/general/routing.html)
$route['default_controller'] = 'welcome';
$route['product/(:any)'] = "tuaconfig/action";
$route['404_override'] = "";

Caso sua versão seja a atual, eu vi na documentação atual ( https://www.codeigniter.com/userguide3/general/urls.html )e seguindo ela :
Na raiz do framework:
application/
assets/
system/
.htaccess
index.php

Em seguida alterar o arquivo application/config/config.php:
  $config['index_page'] = "index.php";
    $config['index_page'] = "";

Comment: Irei configurar desta tal forma e logo retorno com a resposta.Desde já,agradeço a atenção!
Comment: fiz uma edição colocando link para melhor você poder entender pela explicação do manual
Comment: Deu certo aqui,estou dando uma estudada melhor na documentação.Estava desenvolvendo um sistema em Rails 5,tudo pronto.E descobri depois de pronto que a hospedagem do cliente não suporta Ruby e nada faz com que ele mude de hospedagem.E tive que migrar para o PHP de uma hora pra outra...
Comment: de boa... Vai dá tudo certo. Sucesso

Routes em CodeIgniter


apache 2 - how to access "mydomain.com" OR "www.mydomain.com"

Question: I've recently set up a domain name through godaddy.com.  I edited my A record to point to my servers IP address.  I then set up a sites-available file and symlinked that to the site-enabled directory.   When I go to the url "mydomain.com" I get the index.html file in /var/www/index.html which just says "No Direct Access."  When I go to the url "www.mydomain.com" I get my app properly.  My sites-available file for the domain is fairly basic, looks like:
<VirtualHost *:80>
    ServerName www.mydomain.com
    DocumentRoot /path/to/my/app
    <Directory />
        ....
    </Directory>
    <Directory /path/to/my/app/>
        Option FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

When I try this sites-available file WITHOUT the www in the server name, I can not get to the app either way.  When I add the "www" to the server name (as it is above) I get the app, but can not then go to just "mydomain.com" or I get the "No Direct Access" error.  Anyone know how I can use either "www.mydomain.com" or just "mydomain.com" to access the site?
Answer: Add a ServerAlias.
ServerName www.mydomain.com
ServerAlias mydomain.com

Answer: Use:
ServerName mydomain.com
ServerAlias www.mydomain.com

Make sure both your root domain and www point to the web server in your DNS.


Natural Language Processing: Basic Dimension Reduction with SVD of a Co-Occurence Matrix

Question: Given sentences

I enjoy flying.
I like NLP.
I like deep learning

We can form a Co-Occurrence Matrix as follows:
Now we can apply Singular Value Decomposition to this matrix to get
$X = U \Sigma V^T$ where $U$ and $V$ are orthogonal and $\Sigma$ is diagonal and the singular values are sorted (I believe) so $\sigma_1 \geq \sigma_2 \geq \ldots \geq \sigma_r$.
My question is what do the matrices $U$, $\Sigma$, $V$ represent in terms of the words and/or sentences and the relationship between words.
If I think about matrices as linear transformations essentially SVD is taking some matrix $X$ and decomposing it into a (rotation)(stretch)(rotation).
I am ultimately looking for a way to think about the SVD decomposition of a co-occurrence matrix more intuitively.
Comment: Welcome to the CV community. I tried to show you the interpretation of the document-by-term matrix because it is much more general from the co-occurrence matrix while encapsulating very similar information.
Answer: I think that the co-occurrence matrix is not very relevant for an NLP application as the information it includes is readily available in the term-by-document count matrix.
Through the analysis of the document-by-term matrix what we would be describing would be a prototypical application of Latent Semantic Analysis (LSA) (some people refer to LSA as Latent Semantic Index (LSI) - it is the same thing). The original reference for LSA is Deerwester et al. (1990) "Indexing by latent semantic analysis" and it pretty much the application of  PCA to a term by document count matrix. Usually one does not use the raw count but some transformed count through TFIDF (term frequency-inverse document frequency) but the idea remains the same.
In short, we can think of the $U$, $\Sigma$ and $V$ representing a "document-to-concept", a "power-of-concept" and a "term-to-concept" (assuming an $m \times n$ matrix $A$ with $m$ documents and $n$ terms) respectively.
Co-occurrence matrices can be very helpful for image analysis (e.g. see Clausi (2002) "An analysis of co-occurrence texture statistics as a function of grey level quantization" as they can be used to encapsulate texture statistics but that is because texture does not have the same interpretation as actual word-terms. (I  recall seeing co-occurance data being used a metric for the purposes of MDS but again for an NLP we might as well use the term-by-document counts matrix to get the same info.)


What is the best way to work on my fret hand finger independence?

Question: As a beginner, I find my fingers going everywhere but the places I want them! This is especially true when I'm attempting scales/licks that use my 4th finger a lot or requires quick interchanging between my 2 and 3rd finger.
What is the best way to work on my fret hand finger independence?
Comment: If you are a beginner, don't worry about scales. Play basic chords, work on your timing, make you rhythm playing smooth and groovy. Finger independence is not that big deal. You will get there but first work on your basics.
Comment: I appreciate your reply but it doesn't actually answer the question. Rather it provides some useful info to 'Absolute' beginners on getting started.

Also doesn't the ability to form chord shapes also require finger independence?
Answer: I think the key is muscle memory. The only way to improve this is by specific repetitive movements. In your question you state: "quick interchanging between my 2 and 3rd finger." Presumably there is a song you are working on that requires this, so the part you are having trouble with, do that move over and over again until you no longer have a problem doing it. After a while, "rewind" a little and play the lead up to that bit and then play a little beyond it, repeating this on a loop.
The key is to do this with every movement you find yourself having any difficulty with. Identify it, repeat it, get comfortable with it.
Comment: @Mick: You could probably gain from practicing troublesome note/fingering sequences using different rhythmical patterns as well. I was taught to do this by a piano teacher and found it very productive in terms of learning difficult fingering sequences.
Comment: Another thing to keep in mind is the accuracy of the movement. It is good to initially practice this very slowly and accurately because you are training your fingers the correct movement and you want it to be correct if that makes sense.
Comment: Thanks for this! I like this logical thought process:
"Identify it, repeat it, get comfortable with it."

As regards the 2nd-3rd finger thing I have since learnt that these two fingers share a tendon in your arm. This makes it difficult to move one without the other moving also. As you have said, A lot of practice is needed to retrain your brain into moving these independant of each other.
Comment: @UlfÅkerstedt, I've found that technique useful on every instrument I've ever played. It prevents you from getting hung up on difficulties related to the rhythm, and it also better trains your muscles to play other phrases that are similar in the future.
Answer: Don't worry! Every new guitar player goes through this.
The key is to not disregard the 3rd and 4th finger and use them a lot especially when practicing dexterity exercises. Your thumb is close to your 1st and 2nd finger, so that makes those finger more capable of playing these exercises.
Don't disregard the 3rd and 4th finger, push through on your dexterity exercises and this will come to you.
Answer: A systematic set of exercises can help. Try to practice every possible move in isolation. Do these at each fret position to get comfortable all over the neck.
Index-Ring, Middle Pinky.
<code>$6 1 3 $5 1 3 $4 1 3 $3 1 3 $2 1 3 $1 1 3 2 4 $2 2 4 $3 2 4 $4 2 4 $5 2 4 $6 2 4
</code>
The "spider" (can be mirrored 4 ways):
<code>$6 1 2 $5 1 $6 3 $5 2 $4 1 $6 4 $5 3 $4 2 $3 1 $5 4 $4 3 $3 2 $2 1 $4 4 $3 3 $2 2 $1 1 $3 4 $2 3 $1 2 $2 4 $1 3 4
</code>
Buddy Holly riff (do it with Index-Middle/Index-Pinky and Index-Middle/Index-Ring).
<code>$5.1.$4.3 $5.1.$4.3 $5.1.$4.5 $5.1.$4.3 $5.1.$4.3 $5.1.$4.3 $5.1.$4.5 $5.1.$4.3
</code>
Drop D Power Chord Scales. Play with Index Barre, Middle Barre, Pinky Barre, and shift up to higher positions. You want to be able to go up and down each string as well as across all 6.
<code>$6.0.$5.0.$4.0 $6.2.$5.2.$4.2 $6.3.$5.3.$4.3 $6.5.$5.5.$4.5 $6.6.$5.6.$4.6 $6.7.$5.7.$4.7
</code>
Search for "The Steve Vai 10 Hour Workout" for a really excellent set of exercises.
Answer:
For finger independence in general. A good exercice is the following. Play frets 1, 2, 3 and 4 ascending on each string (one finger per fret, so i on 1, m on 2, a on 3 and x on 4) from the sixth string to the 1st. Only play these four notes per string, the point isn't to play a chromatic scale, it's just for left hand practice. The trick is this: Once you've played the 4 notes on the sixth string, to play the next note (first fret of the 5th string), only move the finger you need to move (index finger) and keep the others down in the position of the last note they played. For the next note (2nd fret of the 5th string) move your middle finger but not the other fingers (so a and x are still pushing down on the 3rd and 4th frets of the 6th string and i is pushing down on the 1st fret of the 5th string). Etc. Etc. You can also follow this pattern descending and can make a loop out of it. The idea is to only move one finger at a time, while the others are pressed down on the neck. You will probably feel some tension in your fingers as you're basically working against the sympathetic nature of the other muscles (for me, the hardest is the ring finger). I wouldn't overdo it with this exercice as it's really strenuous on the hand but it will do wonders as far as finger independence is concerned.
For finger independence on chords. A practical way of getting your fingers to remember where to go is to put your fingers in the position of the desired chord, push down (not even necessary to play the chord as you're only working on the fretting hand), then release, completely open your hand (while keeping your thumb on the neck), then place your fingers back in the chord position, release, open your hand, etc. etc. Repeat until your fingers know where to go on their own. It's a good way to stimulate muscle memory.
Answer: You need to practice slowly and with concentration.  It is not about training your muscles it is about training your brain.  You are learning how to move your hand in ways that you've (probably) never done before.  You need to go through the motions carefuly and slowly, consciously monitoring how you are moving your fingers, scanning for tension or strain in your hand, and trying to remain relaxed and fluid.  Doing this for a relatively short period (5-10 mintues, anything longer and it is hard to keep the high level of concentration up) every day over weeks to months will improve you ability to smoothly and independently move your fingers.


Solution for a more durable acoustic guitar G string?

Question: I've been playing guitar for 30 years and probably haven't broken a string for the past 20. However my G string consistently wears out much faster than all other strings; the wrap wears on the frets from bending and the tone and resonance of the string suffers noticeably. I'm not a frequent string changer, obviously, and actually prefer the tone of aged strings to that of fresh ones. Some times the wrap will actually break and the string will then buzz. Not optimal. Nowadays, when I start to feel little bumps over the frets of the G string, I know it's almost toast, and I'll change the whole set. Generally I use phosphor bronze 12s.
I've considered loading up on extra G strings, although I've never tried to buy single strings and I'm not sure how available they are. Plus I'm not sure how well the fresh G will sound next to the other aged strings.
Another consideration would be to use an unwrapped G string, something I've never tried. This might actually also benefit the aforementioned bending, but I'm not sure it would be sonically optimal for rhythm playing.
I'd like to know if anyone shares this dilemma and what your solution to it might be.
Addendum: A minute or so of this will show how much of a workout that string often gets.
Comment: Guitar strings are practically free.  Just replace them often.  (by way of comparison, a new set of strings for my cello runs around $300 US)
Comment: The problem is not the coin. It's the strings settling in to sounding good (to me) and one string breaking down consistently faster than the others. Like if one tire on my car wore out before the other three, I'd want to figure out how to fix that. Of course I could ignore the problem and rotate the tires, but I can't rotate guitar strings.
Comment: What guitar is it? Perhaps the frets need a fettle.
Comment: @Tim It's a Larriveé D-2. Probably wouldn't hurt, but when I run my thumbnail over each fret under G string, I don't detect any burrs.
Answer: Going for a plain G was my first thought. Its sound will be different - it's going to be a Marmite moment.
You don't say where on the string it breaks down, but if it's a particular fret wire, that may need a fettle. If it's all over, then I suspect you, like so many of us, are pressing too hard. It's an unconscious thing, and often needs addressing, as it has no advantage, and several disadvantages.
If you're bending and wobbling the G string a lot in your playing, and don't like a plain G (of whatever gauge), then it might well be that you resign yourself to changes more often. Strings are, after all, sacrificial, for the wont of a different term!
Yes, individual strings are readily available. I've used a hybrid set for 40+ yrs, and can only make it from individuals. So I'll buy 10x .022, at a time, for example. Slightly more expensive, but not as much as buying two sets, and not using all the strings from them.
Comment: Going unwound is certainly worth a try. I probably do press harder than I need to at times, but the string breaks down to some degree over every fret from 5 to 14, the area of the neck where bends and vibratos happen most when I'm playing acoustic. Good to know individual strings are available, I will see what I can find.
Answer: Based on positive consumer reviews regarding longevity, I've ordered a few sets of coated strings to try out. Will report back with results.
EDIT: After trying a set of coated strings, I can report that longevity is better, but G string still breaks down before the others. Plan moving forward will be to continue buying the coated strings along with a couple extra G's per set.


What is it called when a chord progression in a specific key uses root/tonic notes that are in-key, but other members of the chord are not?

Question: What is it called when a chord progression in a specific key uses root/tonic notes that are in-key, but other members of the chord are not?
For example, say I am in the key of C major and I pay C Maj, D minor, E Minor, and then F Minor instead of F Major. In this instance, F is in the key of C major, but the chord should be F major, but I am playing an F Minor...
A) Is this concept used often in music?
B) Does it have a name?
C) Are all of the notes that make up every chord in a given scale always in the scale themselves?
Answer: A) Is this concept used often in music?
Very often. Enough to say it's the norm.
B) Does it have a name?
The most general term would be "chromatic alteration", but there are other terms to describe specific uses. For example, the "F minor in C major" example would likely be attributed to "modal mixture" — the interchange of chords from the parallel major and minor modes. F minor is a part of C minor.
There is also the concept of "secondary chords", which are chords that function as though the music has moved to a different key. D major in the key of C major, for example, might very likely operate as a chord leading to G major.
Searching this site for terms like "chromatic chords" or "secondary dominant"
will give additional and more detailed information.
C) Are all of the notes that make up every chord in a given scale always in the scale themselves?
When we speak of a chord being "in a scale" (or more likely, "in a key") it means that all of the notes in the chord come from that scale/key. However, just because a piece of music uses a certain scale or key does not mean that every chord will use notes exclusively from that foundation.


JSP - passing a variable to a method from forEach loop

Question: I am trying to pass value in variable 'i' from the forEach loop to the parameter of method get(). I tried the below mentioned methods. But I was not successful.
Request you to help me in passing the variable i to the method get().
Try 1:

                           ${documentFactory.getTypeFor(entity.metadata()).flatten().getFieldsData().get(i).getType().resolve().getPrimitiveType()}

Try 2:

                           ${documentFactory.getTypeFor(entity.metadata()).flatten().getFieldsData().get(${i}).getType().resolve().getPrimitiveType()}

Try 3:

                           ${documentFactory.getTypeFor(entity.metadata()).flatten().getFieldsData().get(i).getType().resolve().getPrimitiveType()}

Try 4:

                           ${documentFactory.getTypeFor(entity.metadata()).flatten().getFieldsData().get(i-1).getType().resolve().getPrimitiveType()}

Try 5:
<c:forEach begin="1" end= "${documentFactory.getTypeFor(entity.metadata()).flatten().getFieldsData().size()}" var="i">

${documentFactory.getTypeFor(entity.metadata()).flatten().getFieldsData().get(${i}-1).getType().resolve().getPrimitiveType()}

</c:forEach>

Comment: Is this Java or JQuery?  What is that $ dollar sign doing there?
Comment: Its a JSP  with JSTL tags. Back end is Java.
Comment: Can you show the entire `foreach` loop?
Comment: I did post it and I don't know why the loop is not shown in the question :| Have posted the same below.

                            ${documentFactory.getTypeFor(entity.metadata()).flatten().getFieldsData().get(i).getType().resolve().getPrimitiveType()}
Comment: whats the error that you are getting?
Comment: Uncaught exception { org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/views/HomePage.jsp at line 72
    70:
    71:
    72:                                        ${documentFactory.getTypeFor(entity.metadata()).flatten().getFieldsData().get(i).getType().resolve().getPrimitiveType()}
    73:  /c:forEach>
Answer: How about using for each items?
<c:forEach items="${documentFactory.getTypeFor(entity.metadata()).flatten().getFieldsData()}" var='data'>
    ${data.getType().resolve().getPrimitiveType()}
</c:forEach>

Comment: I will try that and will reply back :)
Answer: How about setting the end and begin values in the variables as:
<%
   int begin = 1;
   int end = ${documentFactory.getTypeFor(entity.metadata()).flatten().getFieldsData().size()};
%>

<c:forEach var="i" begin="<%=begin %>" end= "<%=end %>" >
   ${documentFactory.getTypeFor(entity.metadata()).flatten().getFieldsData().get(${i}-1).getType().resolve().getPrimitiveType()}
</c:forEach>

I have done this because i think the problem is in the end parameter.
If possible check by placing direct value in the end parameter as
<c:forEach var="i" begin="1" end= "10" >
   ${i}
</c:forEach>

Just for the check.
Let me know if anything happens or for any query.
Comment: I tried this ->
${i}
  before too and it works fine. It was causing the error in the above statement that I posted in my question


How to attach MySQL database with java application by using Advanced Installer

Question: I have created a Desktop java application which uses (EasyPHP) MySQL database, now I'm trying to create an EXE file of the application by using Advanced Installer, I have problem with attaching the database with the exe file.
Can anyone help me how to do that? I have googled it and cant got solution.
Comment: It looks like you use EasyPHP because it comes with a bundled MySQL server, isn't it? But you don't need Apache and PHP neither.
Package and run MySql server in Windows environment is not easy.

You should Google "bundle/embed mysql server with java application"

Or try to find an alternative, like 100% Java database. Easy to start in the same (or separate) JVM
Comment: Dear @Destroyica thanks for your comment, Yes I'm usingEasyPHP, good recommendation,
Answer: Hi You can use Launch4J to wrap you jars into executable. Also you can invoke a batch to install the JRE and MySQL
Kindly check my blog post which describes how to install MySQL using a batch file
I hope this could help!
Comment: I hope this may help!


How to get updated class variable value in Django

Question: I'm having trouble getting the updated value of a class variable.
When ConnectTestAPI is called after the p_request function is executed, the class variables which are result and orderNo should updated in the post function.
Then I want to receive the updated value of class variables by looping while statement in the p_request function.
However, despite setting the values of class variables with the post request, when the while statement is run, the corresponding values are still empty and 0 value respectively,
So, the while statement cannot be terminated and results in a time out error.
Here is my source code. Thank you in advance!
class ConnectTestAPI(APIView):
   result=""
   orderNo=0

   def post(self, request):
      data = request.data
      ConnectTestAPI.result = data['result']
      ConnectTestAPI.orderNo = data['orderNo']
      print(ConnectTestAPI.result) # I could successfully get data from POST request here!
      print(ConnectTestAPI.orderNo) # I could successfully get data from POST request here!
      return HttpResponse("ok")

   def p_request():
      data = {
         "a" : 1234,
         "b" : 5678
      }
      data = json.dumps(data,ensure_ascii=False).encode('utf-8')
      con = redis.StrictRedis(outside_server['ip'],outside_server['port'])
      con.set("data_dict", data)
      while True:
         if ConnectTestAPI.result != "" and ConnectTestAPI.orderNo != 0:
            break
      res_result = ConnectTestAPI.result
      res_orderNo = ConnectTestAPI.orderNo
      return res_result, res_orderNo

Answer: You need to access the class variables using self:
class ConnectTestAPI(APIView):
   result=""
   orderNo=0

   def post(self, request):
      data = request.data
      self.result = data['result']
      self.orderNo = data['orderNo']
      print(self.result) # I could successfully get data from POST request here!
      print(self.orderNo) # I could successfully get data from POST request here!
      return HttpResponse("ok")

   def p_request():
      data = {
         "a" : 1234,
         "b" : 5678
      }
      data = json.dumps(data,ensure_ascii=False).encode('utf-8')
      con = redis.StrictRedis(outside_server['ip'],outside_server['port'])
      con.set("data_dict", data)
      while True:
         if self.result != "" and self.orderNo != 0:
            break
      res_result = self.result
      res_orderNo = self.orderNo
      return res_result, res_orderNo

NOTE: This usage of class attributes is not recommended. You are mutating a class attribute which has side effects on all instances of that class. In your case, an ordinary attribute initialized within __ init__() would be ok:
class ConnectTestAPI(APIView):
   def __init__(self):
      self.result=""
      self.orderNo=0

   def post(self, request):
      data = request.data
      self.result = data['result']
      self.orderNo = data['orderNo']
      print(self.result) # I could successfully get data from POST request here!
      print(self.orderNo) # I could successfully get data from POST request here!
      return HttpResponse("ok")

   def p_request():
      data = {
         "a" : 1234,
         "b" : 5678
      }
      data = json.dumps(data,ensure_ascii=False).encode('utf-8')
      con = redis.StrictRedis(outside_server['ip'],outside_server['port'])
      con.set("data_dict", data)
      while True:
         if self.result != "" and self.orderNo != 0:
            break
      res_result = self.result
      res_orderNo = self.orderNo
      return res_result, res_orderNo

Comment: Thank you for your answer!! I just tried both answers you uploaded, but still "self.result" and "self.orderNo" look the initial values... How can I solve?
Comment: You need to show the code where you instantiate and use the class, I think. The class as defined above is ok.


Auto sign-in to Organic groups homepage

Question: I have setup a site where users can register as a certain type of user. Once registered, an organic group node is created for them and they can then invite other users into their group.
Can anyone advice me how the group owner and the invited members to automatically login to the group page and how to restrict users to a single group?
Answer: The way I accomplished this was to use Rules to detect when a user logs into the site and also when content is about to be viewed.
Rules provides a programmatic  area in the "DO" feature of the Rule. I execute some php code to detect the group the user belongs to and redirect using drupal_goto.

Auto sign-in to Organic groups homepage


Why I got an TypeError: Cannot read property in my React app?

Question: I have arrays:

sportmen (like this: [{id: 1, surname: 'Williams', typeSport: 5}, ...])
sports (like this: [{id: 4, name: 'football'}, ...])

I using map function to send every sportsman from Main component to ListRow component:
{this.props.sportsmen.map(item => {
    return (<ListRow key={item.id} directory={item}/>);
})}

In ListRow component I print all data about every sportsman, but id value typeSport I changing to sport name. My realization is working, but I have an error in console.
showSport() {
    const tmpSport = this.props.sports.find(item => item.id === this.props.directory.typeSport);
    return tmpSport.name;  // error is here!
  }

render() {
    return (

{this.props.directory.surname}

{this.showSport()}

    );
}

Error:

Uncaught (in promise) TypeError: Cannot read property
  'name' of undefined

Why I get this error and how can I remove errors?
Comment: Can you debug `tmpSport` by doing a `console.log(tmpSport)` what is the result of this?
Comment: @Variable I have 6 calls: 4 undefined and 2 with data (which will show in row, like this: {id: 15, surname: 'Wilson', typeSport: 4})
Comment: @varit05 How can I fix it?
Answer: the sports array doesn't contain a sport whose id matches this.props.directory.typeSport. one solution would be to modify what is returned to handle cases where the sport doesn't exist.
return tmpSport ? tmpSort.name : 'not found'

or something like that


Dynamic ajax/php select tag

Question: Good evening,
I got a small issue with my dynamic select thing like already said in the title. My goal is to reach the following result:
If someone selects an instrument from the first select tag, the other tag called "Besetzung" should filter a list of users who play the selected instrument, for the second select tag like shown in the
screenshot
(Instrument = instrument; E-Bass = electric bass; Besetzung = occupation; Offen = open)
This works fine so far. But my problem is, that i got like 3 to 10 of these blue boxes (screenshot). You can add these boxes manually over a button. And every single box should contain these "individual" select tags... So i need something like a unique ID for each select tag, each time a box is added. So this is my function for the dynamic selection so far:
function fetch_select(val)
{
    $.ajax({
     url: 'get_data.php',
     type: 'POST',
     data: {
        get_option:val.value
     },
     success: function (response) {
       document.getElementById("studentSelect").innerHTML=response;
     }
  });
}

If the function succeeds the element with the ID "studentSelect" is changed. But what I need is something like an array or so, which is used in my html, php and ajax to change every single element... I got no idea how to give every single select tag a unique ID because the number of tags will change while someone is using the website.
I hope you understood what I mean, was a bit difficult to explain for me.
Thanks for any help in advance.
Answer: What you would normally do is use a common class for all elements involved.
Then within the change events you can get the specific instance of the select class that was changed and use that to traverse to the corresponding other select to poplulate
Repeating structure

   <select class="select-1"></select>
   <select class="select-2"></select>

JS
$(document).on('change', '.select-1', function(){
   // traverse to closest row, then look within that row for matching select
   var $otherSelect = $(this).closest('.row').find('.select-2');
    $otherSelect.load('get_data.php', {get_option: this.value})
            .fail(function(){ alert('Oops something went wrong')});
});

Comment: Got it.. Thanks a lot!
Answer: So you have two select lists, the second one depends of what is selected in the first one. That is a very usual task in questionnaires.
The first thing you did, is to change the second select list via ajax,trigger by a change in the first select list right? (that is fine)
So you basically need is the php(server side code) that returns the html of the 2d select list. Isn't it?
Whatever, what we need here is the list of options for each option of the first list. That info should  go server side in tables or arrays if you want.
if you provide the options list for each option of the first list then I or somebody else can help you with the php for it.
Comment: No...each list is basically the same. I already got some php code which is returning the fitting result to the first selection. The problem is that i need the same 2d selection many times, but each selection must be individual: http://i.imgur.com/nIqrLS8.png Each blue box in the screenshot has the same values in the first select list. Depending on what you choose in the first select it should change the second select tag. But my jquery will only change one select and not every single select in every blue box ...

Dynamic ajax/php select tag