Montar tabela HTML usando JSON AJAX

Question: Tenho uma página de cadastro e logo abaixo do formulário tenho uma tabela que mostra os registros cadastrados. Essa tabela HTML é montada com os dados cadastrados usando JSON via jQuery. Até nesse ponto funciona perfeitamente, mas o que eu preciso é que a cada registro cadastrado seja atualizado nessa tabela HTML abaixo do formulário apenas o registro que foi cadastrado naquele momento e mantendo os outros que já estavam. Mas quando eu faço isso ele mostra o registro atual que cadastrei, mas ele duplica todos os outros registros cadastrados. Como posso resolver isso?
       jsonTreatments();

    $("form[name='form_register_treatment']").on('submit', function( event ) {
        event.preventDefault();
        $.ajax({
        url: "http://...",
        type: "POST",
        dataType: "json",
        data: $( this ).serialize()
        }).done(function( register ){
            if( register.verified === 'registered' ){
                swal( "Sucesso!", register.message , "success" );
                jsonTreatments();
            }else{
                swal( "Erro!", register.message , "error" );
            }
        });
        return false;
    });

    function jsonTreatments(){
        $.getJSON( "http://...",
            {id : 7 }, function( treatment ){
              var itens = "";
              $.each(treatment, function( key, val){
                  itens += "
";
                  itens += "" + val.treatment_date_register + "	";
                  itens += "" + val.treatment_procedure + "
 "+ val.treatment_covenant + "	";
                  itens += "" + val.treatment_teeth + "	";
                  itens += "" + val.treatment_faces + "	";
                  itens += ' <button class="btn btn-default btn-circle btn-sm"></button> <button class="btn btn-danger btn-circle btn-sm"></button> 	';
                  itens += "
";
              })
              $('#treatments_patient').append( itens );
        });
    }

                            Data
                            Procedimento
                            Dente(s)
                            Faces
                            Ações

Comment: Na função jsonTreatments está vindo só o de ID 7 mesmo ou todos?
Comment: Somente do usuário com ID 7
Answer: Você chama a função jsonTreatments() no carregamento e monta a tabela. Depois no primeiro Ajax você chama a função novamente fazendo um .append() com os mesmos dados vindos do segundo Ajax, com isso alimentando a tabela com os valores que já estavam lá.
A forma de resolver é esvaziar a tabela antes do append. Você resolve isso com o método .empty() antes do .append():
$('#treatments_patient').empty().append( itens );

Comment: Estava usando a class no lugar do document  e esse exemplo que me passou funcionou perfeitamente. Obrigado novamente @Sam
Comment: Obrigado Sam, deu certo!
Comment: na função jsonTreatments, tem a última TD onde tem ações de checar e deletar, mas não estou conseguindo o jquery não encontra as TRs da tabela  não ficam visíveis no DOM, devido a iteração feita pelo próprio jquery, como posso resolver isso?
Comment: Veja se é isto: https://pt.stackoverflow.com/a/274000/8063

Montar tabela HTML usando JSON AJAX


T-SQL: is there a way to force conformance to ANSI SQL?

Question: We are planning on writing a load process that uses SSIS and loads a SQL 2008 database. Transformations may be done in the packages or in stored procedures that are called from a package or directly from our job scheduler.
What can we do now while in planning stage to minimize the impact should we have to migrate the app to Oracle in teh future?
I picture the SSIS packages could be changed to use a different provider.
What about the SQL that we use?
Q: Is there a way to put, for example, a stored procedure in "ANSI mode" for lack of a better term to ensure that only standard SQL is used within to increase our chances that the SQL will migrate to Oracle?
Comment: Not sure why some random person has voted to close this as Off Topic.  Seems very programming related to me.
Comment: There has been an ongoing discussion over recent weeks in my office about related topics.  I will be watching this question.  1 upvote from me.
Comment: The data source is probably a CSC text file.
Answer: One thing you can do is SET FIPSFLAGGER FULL etc.  More info here: http://msdn.microsoft.com/en-us/library/ms189781.aspx
Comment: Interesting. I was hoping for some option that might be at a level lower than the database level, but this is still of interest.
Answer: I am not aware of any ANSI Standard for RDBMS programming languages.  And the constructs between TSQL and PL/SQL are quite different.
But can you use the Common Runtime Environment (I think that's what its called) in SQL Server to run JAVA?  If you can, and given that Oracle can run JA VA this might offer a pathway to what you want to acheive.
Comment: Actually there is a standard: SQL/PSM (Persistent Stored Modules). But the DBMS vendors ignore that even more than the regular SQL standard. The only DBMS that implements at least parts of it, is DB2. And I think there was a proof of concept implementation for Postgres.
Comment: Well you learn something every day :)  I have never come across it and I see from a quick google that its not to widely implemented.


Does 'default=...' in Django model fields set 'blank=True' by default?

Question: I have a question for the Django model field when applying the default setting. My problem is as follows:
# Model description
class aa(models.Model):
    a = models.FloatField(default=1)
    b = models.FloatField()

When inserting an entry into the database, I apply the following functions to do the validation without any error:
data = {'b': 1.1} # Just for demo...
p = aa(**data)
p.full_clean()
p.save()

Here is the problem, is the case that when I set the default value for a field, the blank is automatically set to True?
P.S. I know what are the differences between null and blank, I just want to figure out the issues related to the default.
Comment: Question title edited for clarity.
Answer: If you put default on a model field, actually it is not setting blank = True . When you initialize a Model like
instance = ModelClass(**field_data)

django will check for all fields and if the field value is not there, then it will try checkin default value by calling get_default() method (look for default value) on Field class.
Comment: So in this case, with the default values, the model instance will set all fields to certain values before the `full_clean` is executed?
Comment: Yup.You can check by `instance = ModelClass(**field_data); print instance.field` , field which have default value.
Comment: Thus is the case that the common usage of `default`, `blank`, and `null` with respect to a certain model field either sets `default=...` or the combination of `blank=...` and `null=...` without setting both `default` and `blank` values?
Answer: Django model fields default to required unless you specify blank=True and/or null=True. In your example, the model validates because you have defaulted a to 1 and set b to 1.1. Neither field is blank, so you're not encountering a situation that hits the question you're asking.
Try changing data = {'b': 1.1} to data = {'a': 1.1} and see what happens - you should get a field validation error.
Answer: Yes. Django always do that. If you don't need that feature simple make it set blank = False


What are the standard/recommended ways to store version-controlled, database data?

Question: I want to store a blog post in a database. I thought it would be nice to have different versions of that data, much like version controlling does for text files.
So, I imagine it working like a row in a table, that had version control. So, for example, you could retrieve the latest version of that row, or a previous version. You could even branch from that row.
Does anything like this exist?
Possibly useful info:
I am currently using Python, Django & MySQL. I'm experimenting with MongoDB
Edit for clarity/more context:
I'm looking for a solution more tailored towards "version control" of rows than of databases; I'm not so much interested in branching entire databases. For example, I would be able to query the content of blog post at 1/1/2011 and at 1/1/2010 (without switching databases).
Comment: Does this answer your question? [How to version control a record in a database](https://stackoverflow.com/questions/323065/how-to-version-control-a-record-in-a-database)
Comment: Have you considered using a version control system like git? Would be interesting to see pros and cons of such a solution.
Comment: @milan - since when git versions database **records**?
Comment: The question doesn't say *any* database record, it says blog posts, which are mostly text, so why not?
Answer: First off, I must say this is an interesting question.
In my line of work, I've to save versions of various user inputs. The way I do it, and by all means I don't really know if it's the right way or not, is the following:
I have a master table and revisions table. I chose these 2 names for the example's sake only.
What master does is stores the following info:

id (autoincrement)
version_id (int)

What revisions store is the following:

id
master_id
version_id
rest of the relevant data about entered entity (dates, etc)

What I achieved this way is that I had gotten an ID of, let's say a blog post. If someone edits the post, I'll store that info to revisions table. Via triggers I'm incrementing the version_id in revisions table. After that I update master table with the latest version_id number. That way I don't have to perform MAX() when I want to see what the latest version is.
That way I obtained simple, yet powerful version system of website's content. It's easy to see changes, and it's also extremely fast to obtain data if you abuse some MySQL cool features (in my actual tables, I'm abusing InnoDB's clustered primary key to the max. so the db design is slightly diff. than the one I posted here).
Comment: can you provide information on how master and revision are related?
Comment: Instead of having a "master.version_id" column and needing to update it each time, you can also query join the 2 tables WHERE "revisions.master_id" = "master.id" and use DISTINCT ON "revisions.master_id" and ORDER BY a "revisions.created_at" column which you add to "revisions".
Comment: @KernelJames just because you can use slower approach, it doesn't mean you should.
Answer: Version control is a complicated topic; doing it right is really challenging which is essentially why even using e.g. git can be tough. I wouldn't want to write a full blown version control system.
For simpler requirements, consider this structure, in pseudo-mongodb/JSON:
BlogPost {
    "_id": ObjectId("..."),
    "slug" : "how-to-version-my-posts",
    "author" : "cammil",
    "published" : date,
    "lastModified" : date,
    "publicVersion" : 32,
    "draftVersion" : 34,
    "teaserText" : "lorem ipsum dolor sit amet..."
}

BlogPostBody {
    "_id" : ObjectId("..."),
    "Version" : 32,
    "Text" : "lorem ipsum dolor sit amet..."
}

So the idea here is to store each version separately and a pointer to the current public version and the current version for editors, bloggers, etc.
My answer is a little MongoDB centric (because I built a MongoDB based blog engine for home use), but it should work similarly for any storage system.
Advantages:

No need to do MAX queries of the version number for either public or private posts
Does not correlate last edited to version numbers, which might not be desirable
Allows versioning even if a certain version is already published
Can fetch the teaser w/o having to fetch the entire article

Disadvantages:

Copies the entire text every time. Not a real concern for textual data I guess (try to type 1GB...). Will be a problem for bigger blogging sites, however. Mitigation: Compress text using deflate, delta-compression.
Needs to update two objects on update


Sample size determination for finding the "top 100" largest X among multiple datasets

Question: My data sources

Source A gives me a ranking of the top 1.000 largest X (say, companies).
Source B provides a similar ranking, comprising 7.000 X, with some differences to Source A (different values, different companies).
Source C has another list of the 5.000 largest X, again with discrepancies from A and B.

The result I want to achieve
I want to combine the three sources (A, B, C) together to generate a new ranking, one that is supposed to give the top 100 of the largest X.
I would manually determine the value for each X. (For example, one of the X -- called "XYZ" -- may have a value of 300 in source A, a value of 280 in source B, and a value of 279 in source C, but I would manually try to determine the "true" value of XYZ, which may actually turn out to be 400.)
This new list is supposed to be "better" because it corrects for each source's omissions.
The question: Sample size?
If I am content with generating a "top 100"-list (based on a combination of A, B and C), how large should my sample be (for manually determining the "true" values)?
Suppose that the the three lists (A, B, C) have 10.000 unique companies in total (unique X), but I do not have the resources to manually look up the values for all of them. As I am only interested in the final "top 100", can I just reduce my efforts to look at the "top 300" of each list (A, B, C) and then determine the final "top 100"? (Premising that there is nothing below the 300rd rank whose "true" value would propel it to the final top 100-list.)
Answer: It depends on the ranking you use for your combined list. If your ranking e.g. says that, to be among the top 100 in the combined list, you have to be, as a condition, among the first 100 of all of the original lists, then you save yourself a lot of work because it is sufficient to only consider those in the top 100 of all the source lists.
Now, let's say you use as ranking the sum of the ranks for all the original lists, where the company at the top of list A gets the rank 1 for this list (and you set the rank for a company that is not appearing in a list of 10,000 to 10,001 for this list). For instance, if a company F is at the top of list A and list B, but doesn't figure in list C, you give it a rank sum of 10,003. Then the worst case for a company that is at the top of list A would be to get a rank of 20,003. That is, there are a lot of possibilities how a company could get a better (i.e. smaller) rank, e.g. one that is at rank 1000 in each of the three original lists.
So, in this case, I would proceed as follows: check the top companies in the three lists round robin and assign as total rank their rank sum. Also, you count your steps, because this count is a lower limit of what rank can be achieved. E.g.: Let's say you compute the rank sum of the three companies at the top of the three lists. After that, you record the count $c=3$. And clearly, at this point, no company that has not yet been checked can get a rank sum better than (i.e. below) $c=3$. You continue like this until you have 100 companies with a rank sum below or equal to $c$.


Linking problems with AppKit

Question: I've created a class using XCode3.2.1 and I want to make it inherit from NSViewController (or any other AppKit entity) .
#import < Cocoa/Cocoa.h>

@interface myCustomView : NSViewController {}

@end

I've linked in the Cocoa libraries, but I get the error that it can't find the class header file
Undefined symbols: "_OBJC_CLASS_$_NSViewController", referenced from:
    _OBJC_CLASS_$_myCustomView in myCustomView.o

I have other classes in my project that are inherit Cocoa classes without a problem.   I don't have any errors if I make it inherit from classes that are part of Framework or CoreData (eg NSObject, NSArray, NSEntityDescription).
Any suggestions?
Comment: This should work. I built a new project and created a class exactly like you have it, can't duplicate your error. Check your project settings, something is fishy.
Comment: To extend JakeVA's point. this should work.  I had a similar problem the other day.  I created a new project and everything worked out fine.  I would create a simple new project if i were you and see if you could extend NSViewController. If so, just spend the extra time and work your project into it.
Comment: I made a new project as well and everything works fine.  I have the Cocoa framework added to the original project, I have another class in the same project inheriting from NSWindowController that doesn't complain.  I'd obviously prefer not to recreate the project class-by-class if it's just some XCode issue that I've screwed up.
Answer: Check if your subclassed NSViewController implementation file is in the "Compile sources" build phase of your active target.
Comment: It's there under compile sources.
Comment: Is that space after '<' charater in import statment a typo or actual code?
Comment: No, sorry, it was a formatting mistake.  Additionally, if I make the class inherit from NSObject, I can add a class variable of type NSViewController without a compiling error.
Answer: Somehow the some of the Frameworks become disconnected in XCode.
Under if you control-click Frameworks and select GetInfo, it the
box had a dash through it (meaning it was partially selected).
Clicking it again activated it for all classes.

Linking problems with AppKit


does a router in front of another router need to be as good as or better?

Question: If I have a server that is sitting behind two routers, does the first and foremost router have to be "better" than the one behind it that is connected to the server?
For example, if there was a server, doing whatever, averaging thousands of concurrent connections, and that server is connected to a beefy router (Router A), able to withstand anything, able to handle all those connections no problem. And that router is connected to another router (Router B), which lets say isn't quite as good. It's good, but if we directly connected it to the server it would probably crumble. That router is directly connected to a gateway to the ISP.
So: Server->Router A->Router B->Gateway to ISP

Is that setup okay/would it work?
Or does Router B need to best Router A or since Router A is the one directly connected to the server it is the only one that needs to be great in terms of hardware?
And in general, do routers that sit closer to the gateway need to be the best, or the ones that sit closest to the servers?
I have this same question for switches. If a switch upline must be better than one downline (closer to server)?

And if Router B does need to be better than Router A, then in enterprises, if they have Cisco Catalyst 6500 switches attached to each row of servers, then what could they possibly put in front of those to handle multiple Catalyst switches? It appears (an educated guess), that the routers and switches upline don't have to be able to handle the sum of the workloads of everything attached to it. But that's just a guess.
I don't have expert knowledge on routers so I can't say how the workload is handled, hence the question. Thanks to anyone who can shed some light on how this situation is handled!
Update: I think my example may have been too broad. To further specify it, my question is not about bandwidth requirements but the concurrency. I don't know what is involved on the router's part to handle concurrent connections, or which routers would be involved.
The server will hold, lets say 10,000 connections open to one public server outside the gateway. So the server will connect to ONE ip address, on 10,000 different ports, which means it needs to pass through Router A and Router B to get through the gateway.
That being said, will Router B have to be greater than or equal to the power of Router A?
Comment: where you put the word "router", do you mean router or firewall?
Comment: @cwheeler33 I don't think I mean firewall, although the router will have a firewall in it. I updated my question with a more specific example. Maybe it will help you understand my question better. Thanks
Answer: A router needs to be sized for the load it is expected to handle. In our campus network, the big 6500's in the middle of the networks are orders of magnitude more powerful than the router that links us to our ISPs. This is because most of our generated traffic is internal oriented. That border device is shoveling around 500Mb/s, but the backplane on our core routers are handling well above that, and multiple VLANs as well.
Concurrency isn't a terribly big issues so long as the router is just routing packets. Even small routers can handle terribly high concurrency rates. Internal tables are kept for routing, which networks are available on what interfaces, and the ARP table, which hardware devices are visible to each interface. The big 6500's at our core have ARP-tables around 10K in size, where the ISP border router is probably closer to 30 entries.
Once a router starts having to maintain connection-state for either firewall or NAT duties, that greatly increases the CPU and memory requirements for a router. Small home-routers doing FW/NAT can only go so far before the NAT table gets exhausted. Behind our border router is a Cisco ASA firewall, and that DOES have to handle all of our incoming and outgoing connections in memory. I don't know what the average connection-count is, but we're able to consistently do around 450Mb/s with simple web-browsing traffic so it has to be very high.
If we had a second firewall surrounding our server subnets specifically, that firewall wouldn't have to be as beefy as the one at our gateway. The Gateway firewall has to monitor all traffic to the server subnets as well as traffic leaving from all of the internal LANs with end-user generated outgoing connections.
Comment: That's interesting. But in the case of concurrent connections, if they are open from the server to the ISP, then based on what you just said, both of the routers in my example would have to be good enough to handle that amount of concurrency, would that be correct? It seemed plausible to me (who knows nothing) that only the nearest router would need to be able to handle the concurrency since it is the one holding the NAT and ARP entries (could be wrong there, don't know much about that either). Thanks for your input.
Comment: @Casey My perspective is skewed since we don't use NAT. Having a /16 means we don't need to worry about NAT table sizes. ARP entries only matter for the number of hardware addresses visible to a router, and for a border router that could be a few as 30, whereas our big core routers are up near 10K.
Comment: Ah ok. If it makes any difference I updated my question with a more specific example. Thanks for your help
Comment: Great, that sounds like an answer. So the limitation isn't really the router, it is the firewall. And if there are multiple firewalls, then in my example, the one closest to the gateway would have to be better than or equal to that one closer to the server (if there was one) if all the traffic was between it and a public server outside the gateway. Thanks!
Answer: If the traffic will pass through both routers, your traffic will only be able to go as fast as your slower router. Chances are your internet connection will be slower than your router can handle.
Other than that, we can't we answer your question. Which router will do more work? Will the internal one be routing between vlans or subnets in your network? Will the external one be using a routing protocol to share routing tables with your ISP?
For your second question, it depends on how much traffic, how many servers, etc...
Comment: In my example, just one server. I wasn't really asking for bandwidth reason, I was curious purely about the concurrent connections. I have seen some home routers crumble around 1,000. Obviously, there's better one that handle many times that amount.
Comment: @casey I just realized... are you talking about NAT capacity here?
Comment: @sysadmin1138 I might be, I'm not sure. I know that I would be if all my connections were to different IP addresses, but all of the connections are to the same ip, which means many ports. I don't know if each port counts as an entry in the NAT table or just ip address. I updated my question with a clarified example, it may help you understand what I mean.
Answer:
Yes the setup looks OK - you could also easily replace the word router with firewall.
You put the best for the job for where you expect the work to be. Most setups will be better bandwidth inside, and less for the gateway. If the internal network has gigabit, and the DMZ is gigabit, and the gateway is say 100mb; you will put a better router for A and a smaller one for B.
this appears to be the same as question 2.
Again similar to question 2. You put the best where the largest amount of traffic will be.

If you are going to spend taht much money on large switches, you should spend the moeny on a proper consultant to help you get the most out of your equipment. They can do so much more then good placement of the switches. depending on the options you purchased, the IOS can have major consequences on performance and security.


Influence of room acoustics on practicing (woodwind) instruments

Question: While practicing flute I noticed I find it much easier to have a good tone when I practice in my living room then when I practice in my normal (music)room. I was thinking that this could be because of how the room acoustics influence the sound.
My living room is spacious, while the other room is a lot smaller, more cluttered and has a large surface covered with textile.
I find it easier in my living room to get a big clear sound out of my flute, making me more comfortable and relaxed, which makes me sound even better. In the small room it's a lot more difficult to get a good sound, I have to push more and generally struggle in the high register.
I'm not sure if this can be attributed to the room accoustics and how it would influence my playing. I think I am less hesitant to play louder in the large room, which makes it easier to make a well supported sound, making all other aspects easier. But I also wonder if it's subjective because I maybe get more feedback in the small room and I'm more aware there of the faults in my sound. I'm only guessing and have no idea!
I ask this question to know what's the best room for efficient practice, and if I have to do something about the accoustics in my normal practice room? Is the best room to practice in the large living room, that encourages me to fill the room but maybe hides my faults, or is it the small room, where I instinctively make my sound smaller but makes me aware of how I sound?
There's another question that kind of asks the same for voice, but it doesn't really answer the question I'm asking here:
Room Acoustics for Singing
Comment: Surely playing louder would emphasise any faults that may occur. What are other rooms in the house like acoustically? The bathroom, for example, may be small, but have a big reverberation factor. Bright rooms give bright sound - it's good to have less sound soaking material like carpets, armchairs, curtains or soft furnishings. Try removing those from the practice room. Also where you stand will make differences. I think we all compensate, often without realising, when playing in different acoustical situations.
Comment: With regards to  playing volume: quality of sound in wind instruments is related to support. For playing louder it's natural to engage the midrif more. Because of that it sometimes is easier to find a good sound when you try to play louder, while it is more difficult for beginners (like me) to play soft and steady. So my theory is that in the bigger room I'm forced to play with more support. But I'm not sure.
Answer: While it's pleasing to play/practice in a room which enhances the acoustics, if you really want to improve the "source sound" (i.e. what you're generating), a well-damped or anechoic room is best.  It'll sound crummy, but will reveal the tiny faults in pitch or tone, allowing you to improve your technique.
Every now and then, switch to a place with great acoustics just to keep your spirits up.  I knew one trumpet player who would sit in a 4-story concrete stairwell -- the sound was excellent!
Answer: Particularly on flute the room acoustics have a huge influence on the way the instrument sounds. If you are playing in a larger room with a lot of reverb you think you are producing a huge sound, and if you are playing in a room with highly absorbent walls you think you are producing a weak sound. Really you are producing exactly the same sound, it just feels different. Practising in a room with  bad acoustics can be very disheartening, so it's best to find a room with just enough feedback that practising feels good. It sounds like you might need to make your practice room a bit 'livelier', maybe add a couple of wood surfaces, or reduce the amount of textile on the walls.
Answer: I would recommend practicing in a mixture of different settings. Personally, I used to have problems playing too quietly in small spaces, because it felt like I didn't need to play as loudly to fill the room. As a performer, I think it's important to get used to a lot of different environments, so that you can feel comfortable no matter where you are.
Answer: Room acoustics can be an important factor when practicing/performing music. If you are like me, I need to hear pleasant sound when I'm practicing or performing. That's part of what makes it appealing. But I also need to be somewhat versatile and be able to maximize the quality of sound in different environments. To accomplish that, I will practice in different environments focusing in part, at least, on what I can do to make things sound better to me in each environment. This helps me hear things in one room that I might not hear in another room and allows me to experiment and adjust. It also helps me develop a more critical ear which comes in handy when ear training. Stair wells and shower stalls are often fun places to practice too.
Answer: Both are suitable but I would recommend:

Practice room for normal practice
Living room as a treat

Which is exactly what you're probably doing. I used to habitually practice in the bathroom because the acoustics were excellent. It made me slightly lazy and a little physically weaker than I could have been. I didn't have to work hard, so I didn't flex my playing muscles. But I did develop a good ear.
A dampened room will make you work harder. You'll develop better muscles for playing through the hard work and you'll be able to play loudly with less effort.
An echoey chamber will develop your ear. You'll hear nuances in your tone and tuning that you can't hear in your normal practice room.
And just as a final note, if you're practicing loudly, please do consider earplugs (particularly if you end up on piccolo). You'll protect your hearing and you might find out different things about your playing.


If $a^{\frac {1}{x}}= b^{\frac {1}{y}}=c^{\frac {1}{z}}$ and $a$, $b$, $c$ are in AP then $x$, $y$, $z$ are in

Question: If $a^{\frac {1}{x}}= b^{\frac {1}{y}}=c^{\frac {1}{z}}$ and $a$, $b$, $c$ are in AP then $x$, $y$, $z$ are in
$a$. A.P
$b$. G.P
$c$. H.P
$d$. None.
My Attempt:
$a$, $b$, $c$ are in AP
$$\dfrac {a+c}{2}=b$$
$$a+c=2b.$$
Now,
$$a^{\dfrac {1}{x}}=b^{\dfrac {1}{y}}$$
$$a^{\dfrac {y}{x}}=b$$
$$2a^{\dfrac {y}{x}}=2b$$
$$2a^{\dfrac {y}{x}}=a+c$$
How do I proceed?
Comment: Hint: try a few special cases. $a=1,b=2,c=3$ and $x=1$ is a good starting point : what are $y$ and $z$?
Comment: $a=2,b=4,c=6,x=1$ is another informative one.
Comment: @StevenStadnicki Your first example is not a good one because there is no solution for $y$ or $z$ in the reals, so the initial condition cannot be met. Your second example is a much better one as $x = 1, y = 2$ but $z$ can be proven to be irrational because of prime factorisation, so $x,y,z$ can't be in H.P. (A.P and G.P. can be obviously ruled out).
Comment: I think the question should be like: If $a,b,c$ are in G.P. ...
Comment: @k.Vijay, You mean to say that instead of $a$, $b$, $c$ are in AP it should be $a$, $b$, $c$ are in GP??
Comment: Yes, there is a typo in your question
Comment: The correct choice is (b) G.P
Answer: There is a typo in your question. It should be "If $a, b, c$ are in G.P. and $a^{1 / x}=b^{1 / y}=c^{1 / t}$, then show that $x, y, z$ are in A.P."
Let $a^{1 / x}=b^{1 / y}=c^{1 / 4}=k$.
Then, $a=k^{x}, b=h^{y}$ and $c=k^{z}$.
Now, $a, b, c$ are in G.P. $\Rightarrow b^{2}=a c$
$$
\begin{aligned} \Rightarrow\left(k^{y}\right)^{2}=k^{x}, h^{2}=h^{x+2} \\ & \Rightarrow k^{2 y}=k^{x+z} \\ & \Rightarrow 2 y=(x+z) . \end{aligned}
$$
This shows that $x, y, z$ are in A.P.


Google AppEngine FTS is skipping results

Question: I have a problem with FTS on Google AppEngine. I have indexed in the last 2 days over 1000000 enitities.
Now I have the following problem: Some queries do not return my all my results.
Example:
For the following query: "owner=agent, month=10" I get fewer results for the day of 31 than "owner=agent, month=10, day=31".
(Both queries have the same order defined: by creation time as long descending)
It is possible that the indexes are still building for this documents? (The update finished 10 hours ago)
It is a known issue? If yes, is there a workaround?
EDIT
I have discovered that for every search I make I get only the last updated documents. The query returns only the last updated/inserted n (1000-2000) entries sorted by my SortOption field.
If I rise the Number Found Accuracy to 10000 then n is bigger and I get a larger set of entries sorted (but not all)
Answer: From App Engine documentation:

A call to search() can only return a limited number of matching
  documents. Your search may find more documents than can be returned in
  a single call. Each search call returns an instance of the Results
  class, which contains information about how many documents were found
  and how many were returned, along with the list of returned documents.
  You can repeat the same search, using cursors or offsets to retrieve
  the complete set of matching documents.


Inter rater reliability with multiple raters, multiple categorical variables with different levels

Question: Apologies if the answer to this question exists elsewhere, but I haven't found anything quite matching what I'm looking for.
I have a dataset wherein 3 raters independently assessed 10 subjects by answering an identical set of 27 questions. Of the questions, 11 have mutually-exclusive binary responses (either "yes" or "no"), and 16 have mutually-exclusive ternary responses ("yes, "no", or "unknown").
I would like to assess inter rater reliability (IRR) between the raters. I would like to know:
a) Is there is a single test I could use to assess IRR across all of this data at once?
b) If not, how is best to subset the data for applying an IRR test to parts of it? (e.g. pairwise comparisons between raters across all questions and research papers?)
I'm working in R, so if you have specific tests to recommend, I would also be grateful if you could point me in the direction of any good packages to perform them.
Thanks in advance for your help!
Answer: It is probably best to assess the raters' agreement per question separately. You could use any chance-adjusted index of categorical agreement for both type of question; you'd just have to decide how to treat the "unknown" option (e.g., as a third nominal option, as a third ordinal option between yes and no, or as missing data). If, for some reason, you really need to combine the reliability across the questions, then you can calculate the index per question and then average them.
If all of these questions are meant to be measuring the same exact thing in 27 different ways, then you could look into a generalizability (G) study implemented as a logistic mixed effects model (i.e., nesting responses within raters and questions). But that seems unlikely and probably overkill.
If you are using R, you can look at the following packages: irr, irrCAC, or agreement.


FormatConvertedBitmap with alpha

Question: I've a problem in WPF. I'm making a delete button with an image in it. When the button is disabled, however, I wanted to display a greyscale image.
I found the Thomas Lebrun implementation, but I don't want to add the whole class in my program. Instead I tried to mimic the behavior in this way:
BitmapImage img_Delete = new System.Windows.Media.Imaging.BitmapImage(new Uri("the png URI", UriKind.RelativeOrAbsolute));
ImageSource img_DeleteDisabled = null;

[...]
Button btDel = new Button() { Width = 20, Height = 20, ToolTip = "Delete", Margin = new Thickness(5), HorizontalAlignment = System.Windows.HorizontalAlignment.Right };
btDel.IsEnabled = isdeletable(obj);

if (!btDel.IsEnabled && (img_DeleteDisabled == null))
{
    img_DeleteDisabled = new FormatConvertedBitmap(img_Delete, PixelFormats.Gray32Float, null, 0);
}

btDel.Content = (new System.Windows.Controls.Image()
{
    Width = 16,
    Height = 16,
    HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
    VerticalAlignment = System.Windows.VerticalAlignment.Stretch,
    Source = btDel.IsEnabled ? img_Delete : img_DeleteDisabled
});

It behaves in the expected way, except.. Well, I'll show you:

The left one is enabled, the right one is disabled
As you can see the alpha channel is gone. How can I integrate it back?
Comment: So can you set `OpacityMask` in the `Image` constructor (like setting `Source`)?
Comment: @bars222 It looks that the opacity mask should be set in the button itself, not in the image source.. See my answer for details
Comment: what is alpha channel?
Comment: alpha channel includes transparency information: in the left the red cross has a transparent background, while the grey one has a black one..
Comment: try to set `btDel.Background = Brushes.Transparent;`
Comment: @StepUp Nope.. The button should keep its grey background, the image should have transparent instead of the black. If I put that, the grey behind the red cross goes away, and the black square remains
Comment: In referenced example mentioned about `OpacityMask`. You can try to use it `img_DeleteDisabled.OpacityMask = new ImageBrush(img_Delete);`
Comment: @bars222 the problem is that `ImageSource` does not contain `OpacityMask`; in fact the author inherits from `Image`. But the `Source` property of the button content can't be an `Image`; if I put `img_DeleteDisabled.Source = ...` and `img_DeleteDisabled.OpacityMask = new ImageBrush(bitmapImage);`, like in the example, then I'm forced to use `Source = btDel.IsEnabled ? img_Delete : img_DeleteDisabled.Source`, which does not use `OpacityMask`
Comment: The problem is not with the `Image` itself, but rather with the fact I need to pass `img_DeleteDisabled.Source` if it is an `Image`, and so there is no opacity mask (since `img_DeleteDisabled.Source` does not have opacity masks associated)
Comment: maybe you need to delete black background of your image using some paint editor?
Comment: @StepUp The original image (the png one) was already without background. I needed this because I did not want to add a new greyscale image for every image I have, but rather to have the program "calculate" it. In this calculation, however, the transparent background became black. Anyway I solved it (see my answer)
Answer: Helped by the comments, I figured out I was thinking about the wrong place where to apply the opacity mask.
The OpacityMask should be applied to the button, not to the image. This is because the opacity applies to the whole image rather than its source.
For this reason, the correct way to implement this is
btDel.Content = (new System.Windows.Controls.Image()
{
    Width = 16,
    Height = 16,
    HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
    VerticalAlignment = System.Windows.VerticalAlignment.Stretch,
    Source = btDel.IsEnabled ? img_Delete : img_DeleteDisabled,
    OpacityMask = new ImageBrush(img_Delete)
});

This way the mask is applied to the button image. The result is what I needed:
Comment: It's ok, finally we're found the solution.
Comment: I'm glad that my suggestion is helped and setting the `OpacityMask` like `Source` is helped, maybe I'm not clear in the comment (I'm wrote in image constructor, but meaning initializing code).
Comment: @bars222 actually I did not think about the button content as an `Image`, so I thought you were saying to use it in the `img_DeleteDisabled = new Image` constructor... Sorry

FormatConvertedBitmap with alpha


JQUERY iFrame, Works with an Alert, doesn't work without an Alert - Strange? Why

Question: The following does not work on my page:
<code>$("#bob").ready(function () {
    $("#bob").contents().find(".findme").css("background", "red");

    $(document.getElementById('bob').contentWindow.document).find('.findme').bind("mousedown", function() {
        alert(  $(this).text() );
    });
});
</code>
But if I add an Alert, which I assume adds some type of delay to let the iframe run before JS continues, it DOES WORK?
<code>$("#bob").ready(function () {
    alert(1)
    $("#bob").contents().find(".findme").css("background", "red");

    $(document.getElementById('bob').contentWindow.document).find('.findme').bind("mousedown", function() {
        alert(  $(this).text() );
    });
});
</code>
Is the delay is what's making it work, shouldn't the ready be taking care of this? Also, is there a way to make the above LIVE, so the timing isn't an issue?
Comment: See [jQuery .ready in a dynamically inserted iframe](http://stackoverflow.com/questions/205087/jquery-ready-in-a-dynamically-inserted-iframe).  It should work if you use `load` instead of `ready`.
Answer: Try putting that in a
$(document).ready(function() {
Instead of
$("#bob").ready(function () {


Enviar requisição get e receber dados

Question: De acordo com o PagSeguro, preciso fazer um GET e depois receber os dados que vem no formato XML Documentação.
Estou enroscado nessa parte:

Para consultar uma notificação de transação, você deve fazer uma
  requisição à API de Consulta de Notificações, informando o código da
  notificação. A figura abaixo ilustra uma chamada à essa API, que
  utiliza o protocolo HTTP e o método GET (as linhas foram quebradas
  para facilitar a leitura).

Então fiz o seguinte:
string pagina = string.Format("https://ws.pagseguro.uol.com.br/v3/transactions/notifications/{0}?email={1}&token={2}",notificationCode, email, token);

Pesquisando cheguei a este código para estar fazendo um GET na pagina:
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(pagina);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";

Porém não sei como prosseguir.
O que eu fiz, está certo? E agora como posso estar recebendo os dados do Pagseguro?
Answer: O que eu fiz, está certo?
Aparentemente, sim. Só testando pra saber de verdade.
E como agora posso estar recebendo os dados do Pagseguro?
Enviando a requisição:
WebResponse response = request.GetResponse();

Veja como utilizar a classe WebRequest aqui.
Answer: Além da resposta do @Cigano, vc deve mudar o Method para "GET".
req.Method = "GET";

WebResponse response = req.GetResponse();

Enviar requisição get e receber dados


Há vantagem em linguagens que empacotam (.dll, .class, .exe) para linguagens de script (.php, .py, .js)?

Question: Há alguma vantagem em usar linguagens como o Java, .NET, C, C++ que geram um produto em que fica mais difícil de se alterar?
Por exemplo, se eu gero um .class, ou um .jar, haveria alguma vantagem em questão de segurança, privacidade, copyrights, de controle de código, ou de manutenção em relação ao uso de scripts em que o fonte fica aberto no servidor em produção?
Como é o caso do .php, ou .js?
Answer: Sim. E há desvantagens também, como em tudo.
Em questão de segurança não, pode ser ligeiramente mais difícil (mas em todos casos é possível acessar o código fonte, só não será um código tão legível, mas ainda extramente fácil para quem sabe quebrar a segurança.
Só para deixar bem claro, a suposta proteção é mínima, não é algo como fazer uma senha bem mais difícil de quebrar, para quem sabe fazer isso nem faz diferença a forma como está "protegido", ela perderá pouquíssimos minutos (quem sabe segundos) a mais em uma tarefa que levará dias para aproveitar o que conseguiu. E é possível ofuscar código em scripts de tal forma que pode ser tão difícil quanto outros meios de "proteger" o fonte (na verdade pode ser mais difícil porque você pode fazer um jeito personalizado que dificultaria um pouco mais quem for fazer isso já que ela teria que aprender como você ofuscou e não uma forma padronizada.
Esta técnica tem nome e pode até ser usada, mas não pode ser a única de segurança, ela é extremamente fraca. Importante ler essa pergunta sobre proteger código fonte.
Se está preocupado com alguém te roubar o código é claro que é mais fácil em scripts, ou seja, todos em JS são assim e, ao contrário do que as pessoas acham, isso não muda nada importante pra ela (as pessoas tem ilusões sobre roubo de código, isto só acontecerá se o código for muito bom, o que quase nunca é, e só será feito por alguém que nem saberá usar aquilo direito). Claro que se feito errado o fato de estar tudo fechado vai ajudar um tiquinho, se fizer certo não faz diferença.
Se a preocupação é que tem senhas, tokens ou outros dados que não podem ser divulgado, o problema já está aí, não pode ter essas informações no seu código. Sim, muita gente faz assim porque não ligam pra segurança, mas está errado.
Se a linguagem de script for usada para fazer script nada disso importa porque é algo que não produz nada tão relevante ou não tem nada que seja segredo. Se for usada para fazer aplicações tem tanta coisa errada nisso que este é o menor dos problemas.
Vamos diferenciar as linguagens de script. Veja a pergunta Usar validação via cliente é suficiente?. Não é só sobre validação, tudo que está rodando em um browser não pode ser confiável, nem mesmo se ele não tiver um código de JS. Na verdade mesmo que só possa ser acessado externamente e não tenha uma HTML. Então se colocou alguma informação em JS que possa ser aproveitada para fazer algo errado já tem algo extremamente inseguro. O mesmo vale, só pra citar um exemplo, você ter um ERP no desktop de alguém cheio de códigos .py. Você ter código PHP pode não ser um problema tão grande. Se alguém invadir ou acessar naturalmente seu servidor será um problema se ela quiser pegar informações ali, mas sem essa entrada não tem um grande problema. Claro é uma exposição a mais.
Em termos de privacidade acho que não tem vantagem, nem sei se usou essa palavra de forma adequada (pode ser que usou porque coloca senhas no código, mas isso não é sobre privacidade, parece um assunto não relacionado. E os outros termos usados também não parecem tem a ver.
Manutenção não influencia, embora algumas pessoas possam achar mais fácil fazer gambiarras em linguagens de script abertas (existem linguagens de scripts que são ou podem ser encapsuladas em algum container e tem essa suposta "proteção"). Aí você decide se poder fazer gambiarras direto em produção ajuda ou atrapalha a manutenção. Eu tenho uma posição muito clara, mas algumas pessoas podem achar que um ganho mínimo de produtividade por não ter que compilar é importante (em geral a pessoa ignora o quanto aquilo teve que ser pensado, testado e passar por uma boa avaliação que consumiu muito mais tempo e que esse ganho de não precisar compilar é mínimo, só provoca percepção que foi mais rápido).
Ter tudo em um container, especialmente se ele pode ser executado pelo sistema operacional de forma direta, torna sua aplicação mais confiável (não é segura) afinal não tem um monte de arquivo que pode ser perdido ou manipulado acidentalmente. Tem outras vantagens que geralmente esse tipo de linguagem possui, mas parece que não é o foco da pergunta.
Comment: container seria um Wildfly? ou um .exe gerado pelo compilador C?  Como ficaria mais confiável podendo ser executado diretamente pelo SO em relação a outro caso?
Comment: Qualquer coisa, mas penso mais em um executável. Fica mais confiável porque é uma coisa só, não várias partes que podem se perder
Comment: o fato de poder manipular o código acidentalmente não é um argumento forte para tornar uma linguagem de script de difícil rastreabilidade? por exemplo, ter a garantia de que o que está em produção realmente é a versão x?
Comment: Não faço ideia do que está falando sem detalhes.
Answer: Tudo tem vantagens e desvantagens, e muitos aspectos podem ser analisados, mas vou me focar na abordagem de segurança, que parece ser sua preocupação principal.
Deste ponto, sim há a vantagem de dificultar o acesso ao seu código fonte. Digo dificultar pois se procurar vais facilmente encontrar descompiladores para a maioria das linguagens, inclusive .NET e Java, que foram citadas.
Agora claro que é vantajoso compilar o código, do ponto de vista de segurança isso dá uma proteção a mais.
Vamos fazer uma analogia para pensar se vale o esforço: sua rede WiFi pode ser invadida, basta uma pessoa talentosa querer, agora, se elevar a dificuldade, usando um algoritmo de senha mais complexo, evitar senhas do tipo "123456", colocar proteções adicionais, vais reduzir em muito a chance de sua rede ser invadida, não garante 100%, mas dificulta, é a mesma coisa com o código, melhor que um código todo aberto é um código compilado, alguém já vai precisar de um conhecimento a mais para fazer uma engenharia reversa.
E falando em segurança, podes além de compilar usar um obfuscator, que irá dificultar mais ainda essa tarefa.
Ainda assim é possível descompilar, especialmente em linguagens da plataforma .NET e Java, que são executadas sobre uma camada de framework, e por isso estão mais distantes de código nativo da máquina, o que facilita a engenharia reversa, além do código compilado conter metadados, que são mais dados para ajudar no processo de engenharia reversa.
Um código compilado em linguagem C/C++ por exemplo é mais complexo para ser descompilado, para se fazer uma engenharia reversa, pois ele é compilado muito mais próximo da linguagem de máquina do computador.
Adicionalmente, o código compilado é executado mais rápido no computador pois não precisa ser interpretado em tempo de execução, mas em desvantagem precisa ser compilado contra a arquitetura da máquina que vai ser executado para tirar a máxima performance, enquanto o interpretado pode ser colocado e o interpretador faz isso.
Só como comentário adicional, compilar o código não protege efetivamente recursos como strings (textos, mensagens, etc) no seu código, que eventualmente podem até ser alterados sem descompilar o código, por isso se o ponto é segurança, salvar esses recursos em uma forma mais segura é uma boa prática (criptografar, serializar, mimificar, etc), o que pode inclusive ser feito com linguagens de script.
Comment: um código empacotado (com metadata) não seria uma garantia de que uma versão específica do fonte está implantada em produção, enquanto com script tal como php e js isso na prática se torna quase impossível de ser garantido?
Comment: isso não garante, mas diminui a chance de mudar a versão. quem fizer isso precisa ter o código fonte, alterar, compilar e colocar em produção, muito mais difícil do que alguém acessar o codigo no servidor, abrir num editor de texto qualquer e mudar, mas ainda assim não é 100% garantido. aliás, o acesso ao servidor deve ser bem controlado, independente do código que estive lá, mas sim, um código aberto em script é mais fácil de ser alterado pois o fonte está lá.


Show convergence of a sequence

Question: Let $\{b_n\}_{n \in \mathbb{N}}$ be a complex sequence, assume that $\{b_{2n}\}_{n \in \mathbb{N}}$ and $\{b_{2n-1}\}_{n \in \mathbb{N}}$ both converges towards $b \in \mathbb{C} $. Show that $\{b_n\}_{n \in \mathbb{N}}$ must also converge towards $b$.
It's quite easy to see that this is true, however I don't know how to show it rigorously.
Whould it be enough to argue that the union of the positive odd and even numbers are the natural numbers, and therefore it must be true for all $n \in \mathbb{N}$ where $n \geq N$?
Comment: Where does this N come from? You only have to argue for the existence such N.
Comment: Can you write down precisely what it means for $\{b_{2n}\}_{n\in \mathbb{N}}$ and $\{b_{2n-1}\}_{n \in \mathbb{N}}$ to converge? That might help.
Comment: The $N$ is chosen such that $|b_{2n} - b|< \epsilon$ when $n\geq N$
Comment: I just dont know how to combine the subsequences
Comment: For me the argument of union is sufficient, I don't see the need to do more.
Answer: Let $\varepsilon > 0$. We need to prove that there exists $N$ such that $|b_n - b| < \varepsilon$ for $n > N$. But for the subsequences $\{b_{2n}\}$ and $\{b_{2n-1}\}$ there exist such $N_1$ and $N_2$. So $N = max(N_1, N_2)$.
Comment: You have to be careful with $N_1$ and $N_2$. Do you mean for all $n >N_1$, $|b_{2n}-b|<\epsilon$? If so, your $N$ is not quite right.
Comment: It should be $N = 2 \cdot max(N_1, N_2)$ right?
Answer: Given an epsilon, and taking a maximum of the two $N$'s guaranteed to exist for the two sequences, we have for any $2n-1\geq k=\max\{ N_1,N_2\}$,
$$
|b_{2n}-b|<\epsilon/2\\
|b-b_{2n-1}|<\epsilon/2
$$
add those together, use the triangle inequality, and recall the Cauchy criterion.
Comment: That leaves me with $|b_{2n}-b_{2n-1}| < \epsilon $ which isnt sufficient to show its a Cauchy sequence
Comment: it certainly is. In fact it is stronger. To be cauchy, you are only required to find me a term somewhere further down the sequence which is arbitrarily close. Here that term is the next one in the sequence.
Comment: For it to be Cauchy it should be true for all m, n larger than N, not just be true for successive terms. But maybe im missing something ?
Comment: yes, what i have written is true for *any* $2n-1\geq k$
Comment: Oh, yes sorry, my bad. Thank you for your patience

Show convergence of a sequence


Transpose 2D array structure

Question: I don't think this can be done (with out my own function), however I'll ask any way.
I have a array in PHP like
array(
  'item1' => array(
               'Hello',
               'Good',
               ),
  'item2' => array(
               'World',
               'Bye',
               ),
  )

The individual fields come from a web form
I want to rearrange it to the following
array(
  array(
    'item1' => 'Hello',
    'item2' => 'World',
     ),
  array(
    'item1' => 'Good',
    'item2' => 'Bye',
     ),
  )

Make an array of objects from the field arrays
I could write a function to do this.
However I was wondering can one of the built-in array functions achieve this for me?
Comment: No, there is no built-in function that does *this particular* transformation. You could cobble together a few existing functions though to make them do that...
Answer: There is no built in function to do this - but here is a user-defined one that will:
function convert_array ($array) {
  $result = array();
  foreach ($array as $key => $inner) {
    for ($i = 0; isset($inner[$i]); $i++) {
      $result[$i][$key] = $inner[$i];
    }
  }
  return $result;
}

See it working
Answer: Most certainly not the most efficient, but as close to "one function" as you'll get. ;)
array_map(function ($i) use ($array) { return array_combine(array_keys($array), $i); }, call_user_func_array('array_map', array_merge(array(function () { return func_get_args(); }), $array)));

See http://codepad.viper-7.com/xIn3Oq.
Comment: Oh, and don't use this in production without 10 pages of documentation on what it does. ;)
Answer: No. There is no built in function that would do this.

Transpose 2D array structure


SQL Server : Subselect where IS NULL THEN 'VALUE'

Question: I am trying to return a string result when a value IS NULL in SQL Server.
An example of what I am doing is below. This is a sub select query...
SELECT
    stockitems.code AS StockCode,
    stockitems.description AS
ShortDescription,
    (SELECT
         CASE remaining
            WHEN NULL
               THEN 'NO LEVEL'
            ELSE remaining
         END
     FROM StockItemAlertLevels
     WHERE StockItems.ID = StockItemAlertLevels.StockItemID) AS RemainingLevel
FROM
    stockitems
WHERE
    StockItems.Attribute1 = '1'
ORDER BY
    StockItems.Code

No matter what I do, I cannot get the output result of the subselect to change if the result is NULL. Not all returned results from the SELECT statement will have returned results in the subselect - this is where I need the set the output to "NO LEVEL". The subselect will never return more than one result.
Hope this makes sense.
Comment: You're close - you need to write `CASE WHEN remaining IS NULL THEN ...`
Answer: I think you want COALESCE():
SELECT si.code As StockCode, si.description AS ShortDescription,
       (SELECT COALESCE(remaining, 'NO LEVEL')
        FROM StockItemAlertLevels sal
        WHERE si.ID = sal.StockItemID
       ) as RemainingLevel
FROM stockitems si
WHERE si.Attribute1 = '1'
ORDER BY si.Code;

I suspect, though, that your problem is not that remaining is NULL, but that there are no matches.  You can move the COALESCE() outside the subquery, but I would propose a LEFT JOIN:
SELECT si.code As StockCode, si.description AS ShortDescription,
       COALESCE(remaining, 'NO LEVEL') as RemainingLevel
FROM stockitems si LEFT JOIN
     StockItemAlertLevels sal
     ON si.ID = sal.StockItemID
WHERE si.Attribute1 = '1'
ORDER BY si.Code;


Qual a melhor forma de separar as duas listas em C# fazendo uma operação com cada lado do split

Question: Esse questionamento veio a minha cabeça em uma atividade que estava fazendo aqui no trabalho.
Qual seria a melhor forma de fazer esta operação?
O exemplo que trago seria digamos que temos um objeto T, e temos uma List, se eu operar por exemplo:
objeto.Where(o => o.Data < DateTime.Now).ForEach(o => fazX());

Teríamos nesse caso logicamente 2 listas, mas em código nós temos 1 só, se eu quisesse operar a outra parte eu teria de fazer outro where desta forma:
objeto.Where(o => o.Data > DateTime.Now).ForEach(o =>fazY());

Dessa forma se opera as duas partes da lista com funções diferentes, porém eu queria saber se existe uma forma de fazer tudo isto somente em 1 linha, acredito que seja possível já que me parece um problema simples e comum, só não consegui encontrar por aqui nem em outro lugar.
Answer: usando {} você pode criar um escopo dentro da função lambda, e lá dentro colocar um If
lista.ForEach(x=>  { if (x == "") FazX(); else FazY();});

No seu caso:
objeto.ForEach(o => { if (o.Data > DateTime.Now) fazY(); else fazX();});

ps. Acho que quebrando a linha fica mais legível.
Comment: Hum, não pensei nessa possibilidade, acreditei que teria algo + elegante com Linq ou algo do tipo, mas gostei dessa solução também.
Answer: A solução do Rovann funciona perfeitamente para o seu cenário, além do LINQ deixar "mais bonito" o código.
Porém utilizar o .ForEach do LINQ é muito mais lento do que utilizar o foreach convencional, que por sua vez, na maioria dos casos (não é sempre, então convém testar sempre) é mais lento que o for.
Sugiro utilizar o loop for para seu cenário e otimizar a performance do seu sistema.
for (int i = 0; i < lista.Count; i++)
{
     if (lista[i].Data > DateTime.Now)
         FazY();
     else
         FazX();
 }

Comment: A minha questão tinha realmente menos a ver com performance e mais com se existia um modo "ala javascript" de escrever o forEach...
E o LINQ realmente se aproxima do que eu esperava, mas sim, a performance para mim neste caso era bem importante tanto é que minha solução foi idêntica a sua pois precisava dessa velocidade na operação em questão.


Como importar mixins em single file components?

Question: Ao tentar importar o mixin ocorre o seguinte problema

Error in render: "TypeError: Cannot read property 'components' of undefined"

Porém não tem nada de anormal nos components pois ao tirar o mixin tudo funciona normalmente.
metodos/metodo_Div.js
export default {
  methods : {
        inserirDiv (event) {
            let componente = new flexdiv().$mount();
            this.$refs.filhosDoElemento.insertAdjacentElement('beforeend', componente.$el );
        },
    }
}

./App.vue
import { methodDiv } from './metodos/metodo_Div'
...
mixins : [methodDiv],
...

obs. estou usando browserify.
Comment: No teu código não vejo `components` em lado nenhum. Podes mostrar a linha que tem isso?
Comment: @Sergio, já arrumei, obrigado
Answer: Arrumei da seguinte forma
metodos/metodo_Div.js
export const metodoDiv = {
  methods : {
        inserirDiv (event) {
            let componente = new flexdiv().$mount();
            this.$refs.filhosDoElemento.insertAdjacentElement('beforeend', componente.$el );
        },
    }
}

./App.vue
import { metodoDiv } from './metodos/metodo_Div'
...
mixins : [metodoDiv],
...

Lembrando que o nome da variável instanciada no import tem de ser igual a const definida no mixin.
Answer: Vc pode simplismente remover o as {}, não seria suficiente? Creio que o componente iria funcionar. Ficaria
import metodoDiv from './metodos/metodo_Div'
...
mixins : [metodoDiv],
...

Comment: cara tentei tirar aqui e não funcionou, acho que é algum tipo de convenção pois não se trata da importação de um componente e sim de um simples mixin, o {  } ajuda a organizar melhor também.


Vertex Buffer Objects Open GL

Question: I am really new to Open GL and I am trying to build non deprecated code. Now what I can't grasp is VBO. This is all I got so far, can you please explain what I'm supposed to be doing. Also, I have the OpenGL programming guide, so if you can point out some pages to read that would be very helpful as well.
#include <GL/glew.h>
#include <GL/freeglut.h>

GLuint ID[2];
GLfloat PositionData[][2] ={{50,50},{100,50},{50,100}, {100,50}, {100, 100}, {50, 100}};
GLfloat Colors[][3] = {{0.1, 0.2, 0.3},{0.1, 0.2, 0.3},{0.1, 0.2, 0.3},{0.1, 0.2, 0.3},{0.1, 0.2, 0.3}};

void init(){
    glewInit();
    glClearColor(1.0, 1.0, 1.0, 0.0);
}

void display(){
    glClear(GL_COLOR_BUFFER_BIT);
    glShadeModel(GL_FLAT);
    glGenBuffers(2, ID);
    glBindBuffer(GL_ARRAY_BUFFER, ID[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(PositionData), PositionData, GL_STATIC_DRAW);
    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, ID[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Colors), Colors, GL_STATIC_DRAW);
    glEnableClientState(GL_COLOR_ARRAY);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(1);

    glDrawArrays(GL_TRIANGLES, 0, 12);

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDeleteBuffers(2, ID);
    glFlush();
}

void reshape(int w, int h){
    glViewport(0,0, (GLsizei) w, (GLsizei) h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0f, (GLdouble) w, 0.0f, (GLdouble) h);
}

int main(int argc, char *argv[]){
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("I don't get VBOs");
    init();
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return 0;
}

Comment: Please be more specific in your question… if you're asking for a full-fledged VBO tutorial this is not the place IMHO.
Comment: It would be nice, but I want to find out what's wrong with my code. Also, if you could post a link to a full-fledged tutorial, then this question will probably be answered by it.
Comment: If your code is not working as expected then please state that in your question. It's was not clear what you were asking for.
Answer: I did a quick look on your code, an one thing stood out: You're completely missing the point of VBOs. In each draw call you're creating the VBO objects, upload the data, try to draw them (it won't work, because the shaders giving the vertex attributes sense are misssing) and then delete them.
The whole point of VBO is to upload the geometry data into a GL object once and then only refer to it by it's abstract object ID handle and index arrays, which one would also place in a buffer object.
But there's so much else screwed in that code, like setting projection matrix in reshape callback. For one thing, in OpenGL-3 core you don't have those built-in matrices anymore. It's all shader uniforms. And then you set those matrices on demand in the rendering handler.
I think I should really write that definitive OpenGL-3 core tutorial, demonstrating the proper idioms.
Comment: Thanks for the answer, I am a complete newbie with Open Gl. But another question stands out to me, VBOs are the only way to draw things (the only way that isn't deprecated) right?
Comment: Yes, But that's no problem. The only other way would have been immediate mode, which was always problematic. VBOs are nothing else than vertex arrays with the data given into custody of OpenGL. Before there were VBOs the data had to be transferred from the application address space upon each rendering call. If you need to update the geometry, you can do this by having DYNAMIC_DRAW buffers.
Answer: You are setting up custom vertex attributes with indices 0 and 1, but I don't see a shader that uses them. If you don't have a shader yet, then it will not work, because Fixed-Function pipeline accepts specific attributes (set up by glVertexPointer and glColorPointer for your case).
If you decide to make a shader (your goal is to make it for GL-3 core, right?), don't forget to assign your vertex attributes with actual names you use in GLSL code before linking it:
glBindAttribLocation( program_id, attribute_id, attribute_variable_name )

Comment: `glVertexPointer` and `glColorPointer` should continue to work even with a custom shader.  As far as I've been able to determine, `glVertexPointer` is required to even get other attributes into the system, because `glDrawArrays` says "If GL_VERTEX_ARRAY is not enabled, no geometric primitives are generated."
Comment: @Ben Voigt. They will work for sure (did I state the opposite?). The need for `glVertexPointer` is a bit disappointing, but I believe you are correct with that.
Comment: "if you don't have a shader yet, it will not work" strongly suggests "what you're doing will work with a shader".  And I'd be quite interested to know if you find a way to render without `glVertexPointer`, because I want to calculate the coordinates from vertex ID and an attribute (need less memory if I can avoid explicitly storing x-values).  So far my best idea is to have one VBO for `glVertexPointer` and render it with a whole series of attribute VBOs, so I only need a fraction as much memory devoted to `glVertexPointer`.
Comment: @Ben Voigt. My "!A->!B" does not imply "A->B" :) As for the rendering without glVertexPointer I would advice you to go OpenGL 3/4 pure context.

Vertex Buffer Objects Open GL


Variance-Covariance matrix interpretation

Question: Assume we have a linear model Model1 and vcov(Model1) gives the following matrix:
             (Intercept)    latitude  sea.distance   altitude
(Intercept)    28.898100 -23.6439000  -34.1523000  0.50790600
latitude      -23.643900  19.7032500   28.4602500 -0.42471450
sea.distance  -34.152300  28.4602500   42.4714500 -0.62612550
altitude        0.507906  -0.4247145   -0.6261255  0.00928242

For this example, what does this matrix actually display? What assumptions we can safely make for our model and it's independent variables?
Answer: @Donnie has provided a good answer (+1).  Let me add a couple points.
Running down the main diagonal of the variance-covariance matrix are the variances of the sampling distributions of your parameter estimates (i.e., $\hat\beta_j$'s).  Thus, taking the square roots of those values yields the standard errors that are reported with statistical output:
SEs   = sqrt(diag(vcov(Model1)))
SEs
# [1] 5.37569530 4.43883431 6.51701235 0.09634532

These are used to form confidence intervals and test hypotheses about your betas.
The off-diagonal elements would be $0$ if all variables were orthogonal, but your values are far from $0$.  Using the cov2cor() function, or standardizing the covariances by the square roots of the constituent variable variances reveals that all variables are highly correlated ($|r| > .97$), so you have substantial multicollinearity.  This makes your standard errors much larger than they would otherwise be.  Likewise, it means that there is a great deal of information about the sampling distributions of the betas that is being left out of standard hypothesis tests ($\hat\beta_j/SE(\hat\beta_j)$), so you may want to use a sequential testing strategy based on type I sums of squares.
Answer: This matrix displays estimates of the variance and covariance between the regression coefficients. In particular, for your design matrix $\mathbf{X}$, and an estimate of the variance, $\widehat{\sigma}^2$, your displayed matrix is $\widehat{\sigma}^2(\mathbf{X}'\mathbf{X})^{-1}$.
The diagonal entries are the variance of the regression coefficients and the off-diagonals are the covariance between the corresponding regression coefficients.
As far as assumptions go, apply the cov2cor() function to your variance-covariance matrix. This function will convert the given matrix to a correlation matrix. You wil get estimates of the correlations between the regression coefficients. Hint: for this matrix, each of the correlations will have large magnitudes.
To say something about the model in particular, we need point estimates of the regression coefficients to say anything further.


Checking for orthogonality of $\cos(\pi x)$ on the set of functions ${\sin(n\pi x)}$ in the $[0,1]$ interval

Question: I'm trying to verify the orthogonality of the function $\cos(\pi x)$ to the set of functions $\{\sin(n\pi x)\}, n=1,2,3...$,on the $[0,1]$ interval, for which I have taken the integral obtaining the following result:
$$\int_0^1 \cos(\pi x)\sin(n\pi x) dx= \begin{cases}
  0 & \text{if $n \gt 1$, and if n odd} \\ \frac{n(1+(-1)^n)}{\pi(n^2-1)}  & \text{if $n \gt 1$, and if n even} \end{cases}$$
But the source I'm reading states (with no proving) that the result is:
$$\int_0^1 \cos(\pi x)\sin(n\pi x) dx=
0 \text{ if $n \neq 1$} $$
Is this the case? I've verified multiple times my calculations by hand and software and still my result differs from the one in the book.

More info:
The original part of the problem was the following claim about the fourier coefficients of the function $\cos(\pi x)$ respect the set of eigenfunctions $\varphi_n(x)=\sin(n\pi x)+n\pi\cos(n\pi x)$ with $n=1,2,3...$ in the interval $[0,1]$
$$a_n=\int_0^1 \cos(\pi x)[\sin(n\pi x)+n\pi\cos(n\pi x)]= \begin{cases}
  0 & \text{if $n \neq 1$} \\ \frac{\pi}{2}  & \text{if $n = 1$} \end{cases}$$
Comment: It is true, however, that $\cos(\pi x)$ is orthogonal to $\cos(\pi n x)$ on $[0,1]$ when $n\neq 1.$ I suspect that was what the book meant, but hard to say.
Comment: It seems like you should get zero when $n=1,$ since $\cos(\pi-y)=-\cos y, \sin(\pi-y)=\sin(y).$
Comment: When $n=1$ your integral is equal to $$\frac12\int_{0}^1\sin(2\pi x)\,dx=\frac{1}{4\pi}\int_0^{2\pi}\sin y\,dy=0
$$ It seems like something is wrong with your question. Are you sure this is the integral?
Comment: I think you're right. $\cos(n\pi x)$ and $\sin(m\pi x)$ form an orthogonal set on the interval $[-1,1]$, not on the interval $[0,1]$. (Although, I'm pretty sure that for $n=1$, it's still zero.)
Comment: @ThomasAndrews yep, pretty sure, same for the interval.
Comment: How are you getting $\pi/2$ for $n=1?$ Since $\cos(\pi x)\sin(\pi x)|<1,$ the integral cannot be greater than $1.$
Comment: Sorry, my bad, the $\pi/2$ comes from another result previous on the problem. I'll edit to ignore that case.
Comment: I'm still suspect. Why would the source say $n\neq 1,$ when it is zero when $n=1,$ too? What is the source?
Comment: @ThomasAndrews it is "Problems and exercises in integral equations by M. Krasnov" page 122 if you are wondering.
Comment: With your final addendum, you can see that the set of orthogonal functions that you are expanding in is $\sin(n\pi x)+n\pi\cos(n\pi x)$, and so really this has nothing to do with the orthogonality of $\cos(\pi x)$ and $\sin(n\pi x)$. The functions $\sin(n\pi x)+n\pi\cos(n\pi x)$ form an orthogonal set (and complete) set on $[0,1]$ (with some set of boundary conditions), and so the function $\cos(\pi x)$ can be expanded in that set. (Or something like that.)
Answer: $$\cos (\pi x) \sin (n \pi x) = \frac{1}{2} (\sin (\pi x + n \pi x) - \sin (\pi x - n \pi x)) = \frac{1}{2}(\sin (\pi (n + 1) x) + \sin (\pi (n - 1)x)$$
We consider only the case where $n \neq 1$.
Taking the integral from $0$ to $1$ gives $\frac{1}{2\pi} (\frac{1}{n + 1} (1 - \cos((n + 1) \pi)) + \frac{1}{n - 1} (1 - \cos((n - 1) \pi)))$.
When $n$ is odd, we have $\cos((n + 1) \pi) = \cos((n - 1) \pi) = 1$ and thus the integral is $0$.
When $n$ is even, we have $\cos((n + 1) \pi) = \cos((n - 1) \pi) = -1$, and thus the integral is $\frac{1}{\pi} (\frac{1}{n + 1} + \frac{1}{n - 1}) = \frac{2n}{\pi(n^2 - 1)}$.
Finally, in the case that $n = 1$, we see that we're integrating only $\frac{1}{2} \sin(2 \pi x)$ from $0$ to $1$. This integral works out to be 0.
So the integral is always equal to $0$ when $n$ is odd, and $\frac{2n}{\pi (n^2 - 1)}$ when $n$ is even.
Thus, both you and the book are wrong in the case $n = 1$. You are correct on all other cases.
Comment: $\frac{n(1+(-1)^n)}{\pi (n^2-1)}= \frac{2n}{\pi (n^2-1)}$ when $n$ is even
Comment: @ppmbb Right, but they both got the case of $n = 1$ wrong.
Answer: Generally, the functions $\cos\left(\frac{n\pi}{L} x\right)$ and $\sin\left(\frac{n\pi}{L} x\right)$ form an orthogonal set of functions on the interval $[-L,L]$. In the case of the OP, we have $L=1$ for the functions, but we are only integrating over half of the interval, i.e., $[0,1]$.  These functions are not generally orthogonal on the interval $[0,L]$, as the OP has demonstrated.  (Although $\cos(\pi x)$ and $\sin(\pi x)$ are actually orthogonal on $[0,1]$. Otherwise, the OP is correct.)
Comment: OP hasn't "demonstrated," merely asserted. The error when $n=1$ shows these assertions are suspect, and the fact that the book has the same error when $n=1$ implies we might not be getting the correct information.
Comment: @ThomasAndrews Well, okay, but the expression for $n>1$ ($n$ even) is correct, so I assumed they had calculated that, and that's where the problem with the book lies anyway, unless of course the OP just read the limits wrong.
Comment: I'm feeling like the OP likely is reading it wrong. The title in terms of orthogonality and the result given are the result of orthogonal if it's about $\cos(\pi x)$ and $\cos(n\pi x).$


How to ensure 2 injected interfaces are instantiated as the same object instance

Question: Given the following classes
public class RWRepository<TEntity, TEntityId> : IRWRepository<TEntity, TEntityId>

and
internal sealed class EagerLoadingRWRepository<TEntity>
    : RWRepository<TEntity, Guid>
    , IEagerLoadingRWRepository<TEntity>

I am registering these in my DI container like this (where service is IServiceCollection)
services.AddScoped(typeof(IRWRepository<,>), typeof(RWRepository<,>));
services.AddScoped(typeof(IEagerLoadingRWRepository<>), typeof(EagerLoadingRWRepository<>));

Say I inject both of these into 2 different handlers, both within the same scope. How I can ensure that both handlers will use the same object instance for each injected interface?
I.e. if both interfaces are injected, then both should use the same instance of EagerLoadingRWRepository, which inherits from RWRepository
Comment: RWRepository and EagerLoadingRWRepository are different classes, so they will never be the same instance. I assume you mean that both IRWRepository and IEagerLoadingRWRepository map to the  same EagerLoadingRWRepository instance.
Comment: It should be the very same instance in the same scope, that's what the scoped instantiation is about.
Answer: This will be very cumbersome to do with MS.DI (ASP.NET Core's built-in DI Container), because it requires you to make each closed registration explicitly.
For instance:
services.AddScoped<IEagerLoadingRWRepository<Person>, EagerLoadingRWRepository<Person>>();
services.AddScoped<IRWRepository<Person, Guid>>(
    c => (IRWRepository<Person, Guid>)c.GetRequiredService<IEagerLoadingRWRepository<Person>>());

services.AddScoped<IEagerLoadingRWRepository<Order>, EagerLoadingRWRepository<Order>>();
services.AddScoped<IRWRepository<Order, Guid>>(
    c => (IRWRepository<Order, Guid>)c.GetRequiredService<IEagerLoadingRWRepository<Order>>());

services.AddScoped<IEagerLoadingRWRepository<Shipment>, EagerLoadingRWRepository<Shipment>>();
services.AddScoped<IRWRepository<Shipment, Guid>>(
    c => (IRWRepository<Shipment, Guid>)c.GetRequiredService<IEagerLoadingRWRepository<Shipment>>());

Comment: Hi Bassie, I'm afraid that with MS.DI, there isn't. More mature DI Container might make this easier though.
Comment: Thanks Steven, I was hoping there may be some other way of achieving it, but I think this will work for my ~12 or so repos


Convert vector parametric equation to general form

Question: Given the equation of a plane $x$ is $$x(s,t)=(0,1,1)+s(1,0,1)+t(2,1,-1)$$
How can I convert this equation into the general form
$$A(x-x_0)+B(y-y_0)+C(z-z_0)=0$$
Thank you.
Answer: Hint: Write the equation as $$ax+by+cz+d = 0,$$ with $(a,b,c)$ being a normal vector to the plane. Then we find $d$ using one point of the plane, for example, $(0,1,1)$. This direction can be found computing the cross-product: $$a{\bf e}_1+b{\bf e}_2+c{\bf e}_3 = \begin{vmatrix} {\bf e}_1 & {\bf e}_2 & {\bf e}_3 \\ 1 & 0 & 1 \\ 2 & 1 & -1\end{vmatrix}.$$


Using model with heteroskedasticity for predictions?

Question: I am running a model with ordinary least squares regression, and am using robust standard errors (RSE's) because diagnostics tests indicated heteroskedasticity of the model. I'm a bit limited in the kinds of regression I can use because the data is non-normally distributed (I tried a few transformations but nothing really helped).
I will also be graphing the relationship between predicted values of y and values of different independent variables. I know the incorrect standard error issue affects interval estimates, but the coefficient values used in the regression equation remain the same after adjusting standard errors, so I am not sure if it would affect the predicted y values as well. My question is, since the model itself is still heteroskedastistic, would it still be "valid" to use the model for predictions? If not, is there a way I could adjust the actual model in R so that I could use it with the predict() function?
If it helps to have an idea of what I'm working with, here is the model without adjusted standard errors:
Call:
lm(formula = ortho ~ forb + sfdist + year, data = insect.ortho)

Residuals:
Min      1Q  Median      3Q     Max
-5.2720 -1.5416 -0.6649  0.7500 18.1564

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  3.140313   0.367324   8.549 3.76e-15 ***
forb         0.218135   0.051850   4.207 3.96e-05 ***
sfdist      -0.001098   0.000373  -2.943  0.00365 **
year        -0.762830   0.401225  -1.901  0.05876 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.603 on 193 degrees of freedom
   Multiple R-squared:  0.149,     Adjusted R-squared:  0.1358
   F-statistic: 11.27 on 3 and 193 DF,  p-value: 7.621e-07
And after using robust standard errors:
t test of coefficients:

             Estimate  Std. Error t value  Pr(>|t|)
(Intercept)  3.14031323  0.37927174  8.2799 2.017e-14 ***
forb         0.21813498  0.06895898  3.1633  0.001813 **
sfdist      -0.00109765  0.00033704 -3.2567  0.001331 **
year        -0.76282962  0.39007561 -1.9556  0.051956 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Comment: Personally, I would inspect the heteroskedasticity and my assumptions regarding the model error term a bit more. What is the reason for it? Should you possibly use a GLM or transform the DV? I might even try to fit a variance structure.
Answer: The prediction will not be altered in any way by using het-robust standard errors. It remains the same and is still valid.
It's the interval around that prediction (and any hypothesis tests about coefficients or the predictions) that will changed by the choice of of whether to use the het-robust errors or not. In general, if you have heteroskedasticity and use the non-het-robust errors, your intervals will be too small.
Answer: Is it possible you haven't chosen the correct transformation when you were testing them? I would suggest performing a Box-Cox test test on the data to see what the algorithm recommends (if you haven't already). The 'caret' package has a useful function called preProcess() which let's you run the Box-Cox, then fit it to your data using predict(). On a side note, when you perform a Breusch–Pagan test, what p-value are you getting (is it borderline?).
Comment: Hi- I've tried Box-Cox transformation on the model, and log and square root transformations on the response variable.  With Box-Cox, I get the message: "Lambda could not be estimated; no transformation is applied". For square root I get a TINY p-value when I perform Shapiro-Wilk on the response variable, and for log I get something not much better Interestingly, I get a "normal" value on the B-P test (0.3367) but a very small p-value with the NCV test (0.0015), and a graph of residuals vs. fitted values indicates heteroskedasticity so that's what I'm going with.
Answer: I would not use the model to make predictions because one of the assumptions of regression models is homoscedasticity. This problem might be better solved using something like a GLM.
Comment: The assumption of homoskedasticity can usually be relaxed with regression quite easily.
Comment: (-1) This is not correct.  Linear regression is still a consistent estimator of the conditional mean even when errors are heteroskedastic.  Also, the phrase "This problem might be better solved using gradient descent instead of regression" makes no sense to me.  That's an apples an oranges comparison.  Linear regression is a statistical/ML model, gradient descent is an optimization procedure.
Comment: Thank you for the replies! @MatthewDrury are you saying you think the model would be ok to use for predictions? Dimitriy Masterov, I'm not sure if you are saying I don't need to assume homoskedasticity (in which case I'm not sure what type of regression you mean) or that I can adjust the model itself, which is what I'm asking for technical advice on. I am posing this question because I've found plenty on how to find the robust standard errors, but nothing on how I could actually apply them to the model in R. Thank you
Comment: Yup, homoskedacity does not infringe on the predictive capabilities of linear regression.  There may be other, better models to use, due to either better capturing non-linear effects (ala logistic regression), or using the data more efficiently, but the concerns that lead to the homoskedactiy "assumption" are non-predictive in nature.
Comment: Thanks for the comments. I saw the t-test and assumed statistical inference was in order, not model prediction (should have read *all* the text!). Yes, Matthew is right--heteroscedasticity will not influence a model's predictive accuracy; homoscedasticity is only necessary for consistency and unbiasedness.


Lifetime of a spaceship run by three computers

Question: A spaceship is controlled by three independent computers. The ship can function as long as at least two of the three computers are functioning. Suppose the lifetimes of the computers are i.i.d. exponential random variables with parameter $N>0$. What is the probability that the ship can function for the first $t$ units of time?
My answer:
\begin{align*}
P(\text{ship function for t units})&=P(\text{ two or  three computers function})\\
&= P(\text{two function) + P(three function})\\
&=(3**C**2) P(X<t)P(X>t)^2 +(3**C**1)P(X>t)^3 \\
&=2(1-e^-Nt)e^-2Nt + 3e^-3Nt
\end{align*}
Can someone just check my answer, and reassure me this is correct?
Comment: It is not (fortunately since the answer is larger than 1 for some values of t...). To begin with, why are (3**C**2) and (3**C**1) involved?
Comment: sorry, not sure how notation works on here, 3C2 = (3!)/(2!1!)
Comment: Right, and why 3C2 and 3C1 are involved here?
Answer: Let $Z_i$ denote the lifetime of computer $i$, then the random variables $Z_i$ are independent and for each nonnegative time $t$, $P(Z_i\geqslant t)=\mathrm e^{-Nt}$ for every $i$.
Fix some time $t$ and define $p=\mathrm e^{-Nt}$. The event $W$ that the spaceship functions at time $t$ occurs if and only if at most one computer lifetime is less than $t$. Thus,
$$
W=U\cup V_1\cup V_2\cup V_3,$$ with $U=[Z_1\gt t,Z_2\gt t,Z_3\gt t]$ and, for every $i$ in $\{1,2,3\}$,
$$V_i=[\forall j\ne i,Z_j\gt t\gt Z_i].$$ These four events are disjoint and by symmetry $P(V_i)$ does not depend on $i$ hence $$P(W)=P(U)+3P(V_1).$$
By independence of the random variables $Z_i$,
$$
P(U)=p^3,\qquad P(V_1)=p^2(1-p),
$$
hence
$$
P(W)=p^3+3p^2(1-p)=3p^2-2p^3=3\mathrm e^{-2Nt}-2\mathrm e^{-3Nt}.
$$
Thus, the lifetime $S$ of the spaceship has density $f_S$ defined by
$$
f_S(t)=6\mathrm e^{-2Nt}(1-\mathrm e^{-Nt}).
$$


Dijkstra's algorithm vs relaxing edges in topologically sorted graph for DAG

Question: I was reading Introduction To Algorithms 3rd Edition. There are 3 methods given to solve the problem. My inquiry is about two of them.
The one with no name

The algorithm starts by topologically sorting the dag (see Section 22.4) to impose a linear ordering on the vertices. If the dag contains a path from vertex u to vertex v, then u precedes v in the topological sort. We make just one pass over the vertices in the topologically sorted order. As we process each vertex, we relax each edge that leaves the vertex.

Dijkstra's Algorithm
This is quite well known
As far as the book shows, time complexity of without name one is O(V+E) but of Dijstra's is O(ElogV). We cannot use Dijkstra's on negative weight but we can use the other. What are the advantages of using Dijkstra's Algorithm except it can be used in cyclic ones?
Comment: Both right. If the graph is a dag where each predecessor is linked to all of its successors, then the first vertex will relax V-1 edges, the second will relax V-2 edges, etc until the last vertex. In this kind of graph, then E ~ V^2, so O(V^2 + E) = O(V + E) = O(V^2)
Comment: @NursultanZarlyk. From The book: **The running time of this algorithm is easy to analyze. As shown in Section 22.4, the topological sort of line 1 takes O(V + E) time. The call of INITIALIZESINGLE-SOURCE in line 2 takes O(V) time. The for loop of lines 3–5 makes one iteration per vertex. Altogether, the for loop of lines 4–5 relaxes each edge exactly once. (We have used an aggregate analysis here.) Because each iteration of the inner for loop takes O(1) time, the total running time is O(V+E), which is linear
in the size of an adjacency-list representation of the graph.**
Answer: Because the first algorithm you give only works on acyclic graphs, whereas Dijkstra runs on graph with non-negative weight.
The limitations are not the same.
In real-world, many applications can be modelled as graphs with non-negative weights, that's why Dijkstra is so used. Plus, it is very simple to implement. The complexity of Dijkstra is higher because it relies on priority queue, but this does not mean it takes necessarily more time to execute. (nlog(n) time is not that bad, because log(n) is a relatively small number: log(10^80) = 266)
However, this stand for sparse graphs (low density of edges). For dense graphs, other algorithms may be more efficient.
Comment: Can you please enumerate efficient algorithms for dense graphs.
Comment: There is no absolute rule for this. First, the adjacency matrix is more suited to represent dense graphs. Then, from the literature, Dijkstra seems to be a nice choice for the single-source all paths problem in dense graph. For the all-pairs shortest paths, Floyd-Warshall is preferred.


What is the Cauchy's integral formula for this?

Question: $$\oint_{c : |z -\pi i| = 1} \frac{e^{iz}}{z(z-\pi i)^2} dz $$
I tried to solve it and the answer is $-\frac{1}{\pi} + i$
How can I make sure that the answer is right ?
Comment: I added a picture but it didn't appear
Comment: Edited your question, can you please check if the edit is correct?
Comment: Yes it is Thanks
Comment: The best way would be to post your work here, so that someone could check it. (It is not just the end result, it is the *work* that matters too.) I appreciate you may have trouble with typing your answer in MathJax (for that, see the guide: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference ). With that, you may want to add the `solution-verification` tag.
Comment: Thank you, this is my first post . I appreciate your help .
Answer: z = 0 is not inside the contour.  That leaves only one pole inside the contour at $z = \pi i$
Cauchy integral formula says that is $f$ is holomorphic, for every $a$ inside the contour,
$\oint \frac {f(z)}{(z-a)^{n+1}} \ dz = \frac {2\pi i}{n!} f^{(n)}(a)$
$\frac {d}{dz} \frac {e^{iz}}{z} = \frac {e^{iz}(iz - 1)}{z^2}$
Evaluated at $z = \pi i$
$\frac {2\pi i}{1!}\frac {e^{-\pi}(-\pi - 1)}{-\pi^2}\\
\frac {2ie^{-\pi}(\pi + 1)}{\pi}$
Comment: Yes it is $e^{iz}$ . Isn't it   $\oint \frac {f(z)}{(z-a)^{n+1}} \ dz = (2\pi i )/n! f^{(n)}(a) $ ??
Comment: Yes, you are correct about the statement of Cauchy's theorem, I will fix it.  Fortunately $n = 1$ in this case and 1! = 1.
Comment: Thank you very much. That's help a lot


Multiple inputs for paypal form?

Question: I have this code for a paypal form. It has 2 inputs: a text box and a select. Either one included in the code without each other works fine. When they are both included, it takes which ever one is on bottom. Is there a way to make it so that they are both valid, and will be added together if someone fills in both inputs?
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_xclick" />
<input name="business" type="hidden" value="RU48JVL7LR94Y" />
<input name="item_name" type="hidden" value="Donation" />

Donation of any amount

<input maxlength="60" name="amount" size="40" type="text" />

Send A Kid to Camp

<select name="amount">
<option value="0">$0</option>
<option value="250">1 Kid - $250</option>
<option value="500">2 Kids - $500</option>
<option value="750">3 Kids - $750</option>
<option value="1000">4 Kids - $1000</option>
<option value="1250">5 Kids - $1250</option>
<option value="1500">6 Kids - $1500</option>
<option value="1750">7 Kids - $1750</option>
</select>

Comments:

<input type="hidden" name="on3" value="Notes">
<textarea name="os3" rows="4" cols="50" placeholder="Notes" wrap></textarea>

<input name="currency_code" type="hidden" value="USD" /> <input alt="PayPal - The safer, easier way to pay online!" name="submit" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" type="image" />

</form>

Comment: well thats what happens when you call your form inputs the same name....change it to name="amount1" & name="amount2"
Answer: It is possible with some Client-side scripting. I have used Jquery .

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_xclick" />
<input name="business" type="hidden" value="RU48JVL7LR94Y" />
<input name="item_name" type="hidden" value="Donation" />

Donation of any amount

<input maxlength="60" id="donate_text_box_amount" name="donate_text_box_amount" value="" size="40" type="text" />
<input id="final_amount" name="amount" value="" size="40" type="hidden" />

Send A Kid to Camp

<select id="select_val">
<option value="0">$0</option>
<option value="250">1 Kid - $250</option>
<option value="500">2 Kids - $500</option>
<option value="750">3 Kids - $750</option>
<option value="1000">4 Kids - $1000</option>
<option value="1250">5 Kids - $1250</option>
<option value="1500">6 Kids - $1500</option>
<option value="1750">7 Kids - $1750</option>
</select>

Comments:

<input type="hidden" name="on3" value="Notes">
<textarea name="os3" rows="4" cols="50" placeholder="Notes" wrap></textarea>

<input name="currency_code" type="hidden" value="USD" />
<input id="submit" alt="PayPal - The safer, easier way to pay online!" name="submit" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" type="image" />

</form>

Basically, you will need to dynamically populate the amount parameter and pass it to PayPal.

Multiple inputs for paypal form?