NFS read-only export security considerations

Question: Almost all articles about NFS security refer to clients faking uids to access files they are not supposed to.
My concerns are different. My only export is read-only and effectively public (not exposed to the internet, but the data are not secret at all and their others' read bit is set). The data is rarely modified on the server, if needed, I can make sure they are modified only when nfs-server is turned off. I therefore do not need locking.
In what ways can completely malicious clients negatively affect the server? I am mainly interested in security problems (accessing files outside of the export, writing to any files, RCE…), DoS is not critical to me, but I would nonetheless want the know about its possibilities.
context: I would like to offer netboot in my network, serving read-only base root filesystems over NFS and the clients would create in memory overlays above it. I have little control over the client machines.
Answer: The read-only export is fully controlled by server independent from client sending a write request or faking the uids (assume, that server implementation is not badly broken). Thus, a malicious clients can't modify date in read-only export or escape the exported path. Moreover, you should export with squash_all option to map all users to nobody on the server independent from provided uids.
If you want to go completely paranoid about it, then you can mount the underlying filesystem system on the server as read-only before exporting it with NFS. A user-space NFS servers, like nfs-ganesha, that started with systemd can be additionally protected by the corresponding options ReadWriteDirectories=, ReadOnlyDirectories= and InaccessibleDirectories=


After Uploading html files its broken images

Question: I made an html file that is working fine but after uploading it to some free domain host some images are not loaded. This is the website and this is what its supposed to look like
<!doctype html>

<link rel="stylesheet" type="text/css" href="stylenav.css">

            Dexter Silva

Comment: can you post your code, so we can see what went wrong
Comment: You didn't upload images or images src is worg
Comment: i uploaded the images. wdym by the image src? its located properly
Comment: its a big file so i put the code that is one of the broken ones
Comment: Infinityfree free tier has this kind of problems.Once I used it for a school project and had lot of difficulties especially sending data from a GSM module to hosted page.Use Heroku.
Comment: i have used two free domains and still has the same problem
Answer: please check that all your files are uploaded... for instance i cannot find

images/logo.png on your server.
also icons/favorites.png should be in images/icons/favorites.png
so it cannot find the pictures.
Some servers are Case sensitive so make sure your html finds it
nice work by the way, keep trying
hint: your menu buttons open new pages. Better show your content in the same page
try something like https://www.w3schools.com/howto/howto_js_curtain_menu.asp
Comment: Thanks I'm gonna try that, BTW my teacher wont let us use jquery and css but i insisted to use css since html without css looks disgusting.
Answer: You images are in a nested folder, add images/
to the path to link to the correct folder:
src="images/icons/favorites.png"
instead of
src="icons/favorites.png"
Comment: i already did that in the first place cause i was making it from html scratch


Bracketed phrases in numbered notation

Question: I have some sheet music for a Hulusi (a Chinese instrument somewhat similar to a recorder), in numbered notation:

Some of the phrases are bracketed, like the "061 | 321" on the fourth line. What does this mean? I've never seen such a "bracket" notation on staff notation music.
Answer: In conventional notation, bracketed notes can be used for a number of purposes. Often they are used to show passages which are different when a section is repeated. At first, I thought this would most likely be the case here; however, the first use of bracketed notes is for all of the first two lines, which don't appear to be repeated.
Another use for bracketed passages in conventional notation, is to show notes which are not in the main melodic part (backing vocals in a vocal part, for instance). This seems to be the most likely use here, although I don't know this piece, so can't be sure. So, I would imagine that the bracketed notes are not to be played by the main instrument, and are therefore either optional or simply "cue-notes" showing notes heard in another musical part. This would explain the fact that there are both bracketed and unbracketed notes on line 9.
Comment: I think the second explanation makes the most sense. I listened to a recording of the piece and it sounds like the Hulusi does not play until the third line.
Comment: Yes. That makes sense to me. So, it is just showing another musical part for reference. I'll find an example of this from staff notation and post it later for other readers.
Answer: Bob actually has it down here; it's not uncommon for melodic content not played by your instrument to be written in curved brackets as cue notes, when dealing with JianPu notation.

Bracketed phrases in numbered notation


What's a good example for class inheritance?

Question: I'm writing documentation for an object-oriented language, and I wonder what kind of classes would be a good example for inheritance.
Some common examples:
class Person {
}
class Employee extends Person {
}

Currently my favorite, but I don't like Person->Employee because 'Employee' does not exactly look like fun.
class Bicycle {
}
class MountainBike extends Bicycle {
}

I found this in some Java tutorial, but it's not really obvious what attributes a bike should have.
class Animal {
}
class Bird extends Animal {
}

Same as the bicycle.
class A {
}
class B extends A {
}

Too abstract. The main problem is that such a class will need even more abstract attributes and methods.
Does anyone have a better example for a simple class hierarchy?
Comment: All these years and no one can give a legitimate business example. OOP is the dumbest thing I have ever seen. It was invented by people who do not have any problems to solve, or work for a living.
Comment: Here is an implementation of shapes in java. [Shapes implementation in Java](https://github.com/rajeevs1992/myCodes/blob/master/java/shapes/Shape.class "Shapes:Full code")
Answer: I like the Stream hierarchy. The idea is that anything can use a stream without usually caring what kind of stream it is, and individual subclasses handle the storage differently (e.g. NetworkStream, MemoryStream and FileStream in .NET).
If you're interested in interfaces, then IEnumerable<T> in .NET is a great one - you can iterate over any collection without caring what the underlying data structure is.
Comment: Isn't stream example of interface, not inheritance?
Comment: I have also thought about this (or rather Java's InputStream), but I think Streams are not something that everyone will understand. Especially for my target group, since I am writing a reference for JavaFX.
Comment: If someone is writing JavaFX they *should* understand core ideas like streams, IMO.
Comment: I am not sure, but I'd guess a large part of the audience are people who come from a design background, rather than a technical background.
Comment: @MK: No, because Stream isn't an interface - it's an abstract class.
Comment: @Jon Skeet yes, it is, but is there any sharing of state or methods of substance between them?  The purpose of extending Stream is to adhere to an interface contract, not to reuse some code from the parent.
Comment: @MK: How do you explain the presence of non-abstract methods in Stream then? Why do you think Stream *is* an abstract class instead of an interface?
Comment: @Jon Skeet I think it is abstract.  Both InputStream in Java and System.IO.Stream are abstract.  Even Bill O'Reilly can't explain that!
Comment: @MK: But I can... because there are methods in `Stream` which have implementations, so don't have to be overridden in individual subclasses. That's my point.
Comment: @Jon Skeet ah, ok I see your point.
Comment: I tend to agree with all of you. It's an illustrative example of sharing code (type inheritance) when you develop your own stream, but it's also a good example of having a common contract (interface implementation) when you write something that _uses_ a stream. However I would say the concept of streams could also be implemented with an `IStream` interface and a bunch of extension methods (`CopyTo` and friends).
Answer: I agree with Jon Skeet on his streams example. Perhaps it's not perfect, but it has one advantage over most of of the examples here:
It is realistic
Bicycles, persons or animals, shapes or weapons just wouldn't be modelled by inheritance in real projects. (shapes in particular, are downright dangerous, because it doesn't work.)
That's my pet peeve with inheritance. It is too often taught as something that must be used to express every hierarchy you can find. An employee is a person, right? So the Employee class must inherit from a Person class. But a person is also a LivingCreature, so we'd better have one of those classes too. And a LivingCreature is also an Organism, so there we have another class. And an Organism is.... feel free to continue.
I think it'd be nice if someone, somewhere, actually taught inheritance by explaining when it should be used, and not just how you can force it down over any hierarchy, whether it's beneficial or not.
Streams (or devices as in ChrisW's example) have the advantage that they make sense. You want to be able to treat all streams the same, whether they're connected to a memory buffer, a file or a network socket. And all hardware devices do have a lot of behavior in common that could plausibly be factored out into a Device base class.
Comment: I would +1000 this if I could, because I completely agree with you. I've always loathed the textbook examples of inheritance for exactly the reasons you mention here. Real, useful, and good examples of inheritance are few and far between, and CS classes tend to focus on inheritance without explaining how to use it appropriately.
Comment: If I sound a little excited, it's because I'm looking at a programming languages course textbook, and I just got to the Person class example (ugh). "True-to-life" inheritance sounds nice, but just doesn't work out very well in practice. Abstract concepts, like streams, seem to be better-suited as candidates for inheritance, because you don't have nearly as much ambiguity in terms. A FileStream is a Stream is an Object. It would take effort to dream up additional Stream superclasses in that hierarchy. Real-life objects tend to lead you down a rabbit hole of never-ending inheritance...
Answer: Auto Parts can be interesting for example you might have
class part
{
    OEM
    Manufacturer
    Number
    Description
}

class Tire extends Part
{
   Speed
   Rating

}

Comment: Wow, finally an example which could really occur, wouldn't better be written as an interface and isn't abstract.
Comment: Thanks, I spent almost 10 years working one code in the automotive industry. Lots of great examples when you deal with parts especially if your managing many manufacturers, aftermarket, refurbished....It's a complete mess
Comment: I was writing an article about jpa inheritance hence was thinking of some real world example and was thinking about the vehicular hierarchy. Your answer made me stick to my decision :)
Comment: I like this one because it makes sense without virtual functions, unlike most other suggestions. It does lack behavior though.
Answer: The Animal class is the classic example of class inheritance for a number of reasons.
First, there are obvious ways to extend the underlying animal class. You'll likely start with sub-classes such as Mammal, Bird, Crustacean, etc.
Some classes, such as Mammal, will extend Animal by adding attributes that are fairly obvious ("Warm-Blooded", etc.).
Other, more problematic, issues that are quite common in developing a class hierarchy are quite obvious if you illustrate with animal inheritance - and this is a good thing for purposes of explanation.  Birds fly, right?  Well, not all birds...  So, how do you represent flying?  There are, of course, classic solutions and a wealth of discussion information online about how to solve the problems and tradeoffs that each solution introduces.
Thus, I would highly recommend using "Animal" as your example because of the richness of available information and examples.
Comment: It also illustrates the "because we can" tendency to fit *everything* under the sun into the same big bloated hierarchy - a "feature" of inheritance that I'm not sure I'd want to highlight as a good example. It's lacking the pretty fundamental "but why would we do this", that other examples, like the Streams one, has. Does our application really need penguins and ostriches to share a base class?
Comment: What kind of programming application would you model such a hierarchy? A simulation, a database of animal facts, a farm tracking system?
Comment: then don't start with streams. But start with something *meaningful*, something where an inheritance relationship actually might be *useful*. And if you can't think of such a case, then perhaps everyone would be better off if you didn't try to teach inheritance *at all*. If you want to talk about "screwing newbies", then by all means tell them that an application *must* give penguins, ostriches, cats and dolphins a common base class. That's real helpful to someone trying to learn programming.
Comment: Ummm..jalf, I think the point is to demonstrate to newbies the foundations of Object Hierarchies in terms that are familiar to them. If you start with streams, you'll find that many people have no conceptual framework on which to build and thus you'll simply lose them.

It may well make sense to teach them the finer points once they get the hang of the basics.

Of course, if you simply enjoy the thought of screwing newbies because programming *should* be hard and, anyway, it proves how smart you are to demand hard examples, then you might want to consider downvoting my answer. Oh wait...
Comment: And also the classic Animal.Move() ...
Answer: Many people use the Shapes example, but that is in fact a dangerous one. The problem arises when you intuitively decide that a square is a subclass of rectangle.
When it comes to behavior, a square is more limited than a rectangle, breaking substitutability. For example, we could ask a rectangle object to change its height. If a square is a subclass of rectangle, that means we should be able to ask the same of a square. However, changing the height of a square would mean its not a square anymore! Of course, we could increase the width accordingly, but that's not what we would expect when we were to ask an object of declared type rectangle, which is actually a square underneath, to change its height.
It's called the Liskov substitution principle, and you should be aware of it when doing any serious OO development.
Squares are, of course a subset of rectangles, instead of a subclass. This is the difference between data-oriented and behaviour-oriented approaches.
Like Jon, I prefer Streams as an example. It's not difficult to explain, even to non-programmers, and its cleary behaviour-oriented, avoiding the counter-intuitivity of the shapes-example.
Comment: Just to clarify the Square vs. Rectangle example, this is only a problem if you have setter methods like setWidth(),setHeight(). Then the square can either a) break it's invariant (height=width) b) add behaviour to preserve the invariant (i.e. set two variables), both of which are undesirable. If the Rectangle and Square are immutable objects then you won't break LSP.
Comment: Can you give an example of when subclassing square from rectangle is a problem?  I would point out that since a square is a true subset anytime you can use a rectangle you can use a square.  The reverse is not true, but many many subclasses add functionality and constraints (as they should)
Comment: I've added an example. Remember we are concerned with substitutability of _behaviour_ instead of _data_. When you're talking about data, you're right; any method that can deal with some class of data should be able to handle any subclass of it. But, that's not what OO is about.
Answer: If you are into video games could be something like this:
class enemy{
  Health
  Posx
  posy
  Etc
}

class orc : extends enemy{
 speed
 Strength
 etc
}

Answer: What about a hierarchy of algebraic expressions. It is an excellent example because it uses both inheritance and composition:
public interface Expression {
    int evaluate();

    public class Constant implements Expression {

        private final int value;

        public Constant(int value) {
            this.value = value;
        }

        @Override
        public int evaluate() {
            return this.value;
        }

        @Override
        public String toString() {
            return String.format(" %d ", this.value);
        }

    }

    public class Negate implements Expression {

        private final Expression expression;

        public Negate(Expression expression) {
            this.expression = expression;
        }

        @Override
        public int evaluate() {
            return -(this.expression.evaluate());
        }

        @Override
        public String toString() {
            return String.format(" -%s ", this.expression);
        }
    }

    public class Exponent implements Expression {

        private final Expression expression;
        private final int exponent;

        public Exponent(Expression expression, int exponent) {
            this.expression = expression;
            this.exponent = exponent;
        }

        @Override
        public int evaluate() {
            return (int) Math.pow(this.expression.evaluate(), this.exponent);
        }

        @Override
        public String toString() {
            return String.format(" %s ^ %d", this.expression, this.exponent);
        }

    }

    public class Addition implements Expression {

        private final Expression left;
        private final Expression right;

        public Addition(Expression left, Expression right) {
            this.left = left;
            this.right = right;
        }

        @Override
        public int evaluate() {
            return this.left.evaluate() + this.right.evaluate();
        }

        @Override
        public String toString() {
            return String.format(" (%s + %s) ", this.left, this.right);
        }
    }

    public class Multiplication implements Expression {

        private final Expression left;
        private final Expression right;

        public Multiplication(Expression left, Expression right) {
            this.left = left;
            this.right = right;
        }

        @Override
        public int evaluate() {
            return this.left.evaluate() *  this.right.evaluate();
        }

        @Override
        public String toString() {
            return String.format(" (%s * %s) ", this.left, this.right);
        }
    }

}

Then you can provide a motivating example like:
public static void main(String[] args) {

    Expression two = new Constant(2);
    Expression four = new Constant(4);
    Expression negOne = new Negate(new Constant(1));
    Expression sumTwoFour = new Addition(two, four);
    Expression mult = new Multiplication(sumTwoFour, negOne);
    Expression exp = new Exponent(mult, 2);
    Expression res = new Addition(exp, new Constant(1));

    System.out.println(res + " = " + res.evaluate());

}

Which would yield:
(  ( ( 2  +  4 )  *  - 1  )  ^ 2 +  1 )  = 37

Comment: This is a great example; OTOH, it is an example of *interface* inheritance, not class inheritance :(
Comment: Yes, very practical example.
Answer: I think Shape is a good abstract class. There are both 2D and 3D shapes. The 2D shapes typically have area while 3D shapes have volume. Both can have a "location" or "mass center".
Some suggestions:
class Shape {..}

class Shape2D extends Shape {...}

class Circle extends Shape2D {...}

class Rectangle extends Shape2D {...}

class Polygon extends Shape2D {...}

class Shape3D extends Shape {...}

class Sphere extends Shape3D {...}

Comment: Actually, this is a pretty good shape example. Just avoid the square shape.
Comment: You can't put a square shape in around hierarchy!
Comment: Isn't a Rectangle also a Polygon? I assume both Triangle and Pentagon would go in Polygon, so why not Rectangle?
Answer: Being a counter-strike game admirer this is what I would love to share:
Comment: I like games. Warcraft might be good: types of soldiers, types of moving objects, types of objects you can destroy...
Answer: I use to show Chess pieces. The base class is the general ChessPiece, King, Rook, Bishop, etc inherits.
What I like about this example:

it is real, if you implement chess, this is a solution
in C++ you can show which function is virtual and which is not
abstract class can be shown
advanced example may develop towards common base class for directional pieces (Rook and Bishop) or even further to generalized directional pieces with step limit (everything but Pawn)
Answer: Webshop could be a good option as well.
Product(id, title, price, description)
Book(isbn, publisher, pageNr) extends Product
CD(company, duration, genre, taskList) extends Product

Comment: This is the example I found to be the best. It's not abstact like animals (abstract classes as 1st inheritance lesson would be an overkill), it's not a problematic hierarchy of shapes and it's a real-life example that can be easily understood.
Answer: I suggest 'devices'. Nobody really models animals using software, but they do model devices.
class Device
{
  void start();
  void stop();
  DeviceStatus status { get; }
}

class VideoDevice : Device
{
  ... methods for any/all video devices ...
}

class DiskDevice : Device
{
  ... methods for any/all disk devices ...
}

Comment: Devices would generally be modeled using an interface
Answer: I always was fond of:
class Shape {
}
class Square extends Shape {
}

But any of the top three you quote would be fine. MountainBike sounds the most exciting. You can do similar things with cars of course.
Comment: The square-example is problematic when rectangles come into play. The relation between rectangles and squares is a bit in counter-intuitive.
Comment: The classes Shape and Square are easy to understand, but what would be the attributes of a Shape? I couldn't think of any, only abstract methods. And abstract methods are something that I would like to introduce after inheritance, not in the same section.
Comment: The problem with using concepts as examples is: what do you program? What would a shape really DO in a business context? The problem with using real objects (animals etc) as examples is... they don't need any programming, animals already DO whatever it is that they do. So, we need examples of actual situations where it makes sense to write a program to accomplish a legitimate objective where a computer is the best choice, using hierarchy. I think that there are very few commonly understandable examples of that. Streams, devices, etc are not the first thing most people can learn about.
Comment: "Shape" is my favorite illustration of object orientation.
Answer: The best example that i have came across (and read in many books) is the one that uses Shape.
The best thing about this is that you can very easily explain all the concepts (including the tough ones ) related to OOPs like Class,Object,Inheritance,Abstraction,Encapsulation,Polymorphism,etc to any programmer irrelevant of his experience.
Answer: I like the idea of using Printers as an example. Say you're working for HP, Brother, Lexmark, or some other entity, and you need to come up with a program that is capable of generating driver specific modules for a variety of operating systems.
class Printer {
    private String brand;
    private String model;

    public void powerOn() {
        // Logic to power on
    }

    public void powerOff() {
        // Logic to power off
    }

    public void init() {
        // Bootstrap/prep the system
        // Check cartridge
        // Check paper
        // Ready for usage
}

class InkJetPrinter extends Printer {
    // Inherits fields and methods from Printer
    // Demonstrate method overriding and overloading
    // Add new InkJet specific behaviors, components etc.
}

class LaserPrinter extends Printer {
    // Inherits fields and methods from Printer
    // Demonstrate method overriding and overloading
    // Add new Laser specific behaviors, components etc.
}

class LabelPrinter extends Printer {
    // Inherits fields and methods from Printer
    // Demonstrate method overriding and overloading
    // Add new Label specific behaviors, components etc.
}

After demonstrating inheritance you can move towards abstraction and method overload/override.
The init method in Printer class is a good candidate for abstraction. Subclasses will need to implement their own initialization processes.
You can also extend this example and start demonstrating proper usage of Interfaces and Composition. What is the difference between a IS-A and HAS-A concept? Some printers may have WiFi and Bluetooth capabilities. Or, Some of the InkJet printers may have scanning capabilities while other only have feeders etc. How would you implement this?
I think using printers is more closely related to computers and computer science in general. You can use this example and even further demonstrate examples that deal with networking between embedded systems and PC's, SmartPhones, and other IoT's.
Answer: The best one I have always used has been Shapes.
You can then have
Shape --> Quadrilateral
Quadrilateral --> Rectangle
Quadrilateral --> Trapezoid
Rectangle --> Square
Shape --> Triangle

etc.
Methods are then also easy to guess at.
Shape::Area
Shape::Draw
Shape::Intersect (x,y)

Comment: Square is not a substitute of a rectangle, see one of the answers above.
Comment: You're not explaining but confusing.
Comment: While I understand the above comment I would still stick by this example as being perhaps the easiest to explain the principles of OO to new people.  You can just look at how many people used this example here to understand its power.
Comment: I don't understand why this has negative votes.
Answer: I like the vehicles example, as it allows for a relatively clean extension to include interfaces into the discussion (IAutomaticGearbox, anyone?)
Answer: What about
class Weapon
{
}

class Gun : extends Weapon
{
}

class Knife : extends Weapon
{
}

et.
Answer: Inheritance can be complex. Let's start with the simplest of 'em all -- behavior inheritance. Here you are inheriting behavior only and no state. E.g: Both Person and Animal are Animate objects which exhibit an IsAlive behavior. To use your example:
class LivingThing {
   /* We propose a new type */
  public:
    virtual bool IsAlive() = 0;
    virtual void Birth() = 0;
    virtual void Death() = 0;
};

class Person : public  LivingThing {
    /* A real living thing */
  public:
    virtual bool IsAlive() { return true; }
    virtual void Birth() {}
    virtual void Death() {}
    /* .. and has some special behavior */
    void Marry();
    void Divorce();
};

class Animal: public  LivingThing {
    /* A real living thing */
  public:
    virtual bool IsAlive() { return true; }
    virtual void Birth() {}
    virtual void Death() {}
    /* .. and has some special behavior */
    void Bite();
    void Bark();
};

I wrote this using C++ syntax, if you have problems understanding any of it, just say so!
Answer: Example:
The "Everything derives from Object" approach.
Dog --> Animal --> Living thing --> Object
A Dog is an Animal, which is a Living thing, which in turn is an Object.
Comment: while this may work in java, it is frown upon in c++
Answer: You can find good examples of class inheritance in design-patterns.

Abstract_factory_pattern :  Provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete class
Template_method_pattern:  It is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses.
Decorator_pattern: It is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class

Refer to below posts for real world examples:
When to Use the Decorator Pattern?
Template design pattern in JDK, could not find a method defining set of methods to be executed in order
Answer: Hierarchy of Shapes
I completely understand the concerns regarding the relationship between Rectangles and Squares regarding Liskov's substitution principle. However, there are ways to preserve this principle and still have Square as subclass of Rectangle. For example (Python), assume the following:
class Rectangle:
  def __init__(self, w, h):
     self.width = w
     self.height = h

  def setWidth(self, neww):
     if neww > 0: self.width = neww

  def setHeight(self, newh):
     if newh > 0: self.height = newh

We can define Square the following way:
class Square(Rectangle):
   def __init__(self, side):
       super().__init__(self, side, side) # width = height = side

   def setWidth(self, newside):
       super().setWidth(self, newside)
       super().setHeight(self, newside) # force height to match

   def setHeight(self, newside):
       super().setWidth(self, newside)  # force width to match
       super().setHeight(self, newside)

This way we can always use an Square instance whenever a Rectangle instance is needed, thus preserving Liskov's.
Now, from my experience, we can also use Inheritance to enforce a policy (usually restrictive). For example, assume we have a Shape class with a color property and corresponding setter (setColor).
class Shape:

   def __init__(self, ..., color, ...):
        # ...
        self.color = color
        # ...

   def setColor(self, newcolor):
        self.color = newcolor

   #...

Assume we want to create a "RedShape" class. How can we prevent client code from changing the color? Answer: de-active the setColor method by overriding it.
class RedShape(Shape):
   def __init__(self, ...):
      super().__init__(self, 'red', ...)

   def setColor(self, newcolor):
      pass

We redefined setColor in RedShape to do nothing.
The setColor in RedShape overrides the one in Shape so client code cannot change the color of RedShape instances. In a way, we created a more restrictive subclass because we do not have the ability of changing its color, but it does not violate the substitution principle.
This model is useful when we have base classes that are generic (not abstract) and we create specialized classes to control or limit the features available in the base class. You can create a chain of subclasses increasingly enabling features available in the base class, or you can create classes that offer different combinations of features available in the base class.
Before I get flamed, let me reiterate that this usage is a pragmatic model that takes advantage of the mechanism of inheritance and polymorphism for control. It is far removed from the romantic notion of inheritance of creating new classes by enhancing or refining existing ones.


Connection between Twitter status and Ruby on Rails

Question: I'm trying to bring my latest status from Twitter to my Rails app. I have the config details stored in an initialiser and have it displaying my latest tweet, but I want to also bring the date of this tweet. I have the following code and not sure whether to try and amend it or start again.
initializers.twitter.rb
module TwitterStatus
 $client = Twitter::REST::Client.new do |config|
  config.consumer_key        = "##hidden##"
  config.consumer_secret     = "##hidden##"
  config.access_token        = "##hidden##"
  config.access_token_secret = "##hidden##"
 end

 def user_timeline(qt)
  $client.user_timeline(count: qt)
 end

end

controllers/application_contorller.rb
include TwitterStatus

def index
 @tweets = user_timeline(1)
end

main/index.html.erb
<% @tweets.each do |tweet| %>

<%= link_to tweet.text, "https://www.twitter.com/#{tweet.user.screen_name}" %>

<% end %>

Any help would be appreciated, ideally, I'd like to be able to pull all the tweet info (img, name, etc...) and just use what I need.
Comment: That brings all the information such as 'screen_name', 'created_at'! Thank you so much. I can then simply call <%= tweet.created_at %> etc.. to show any info I need, Excellent!
Comment: Seems `@tweets` has the info you need already. Have you checked what it holds exactly?
Comment: Hi Mischa, I'm not sure what I would do to find what it holds. Can you provide more info?
Comment: You can add the following after you have set `@tweets` in the index method: `logger.debug @tweets.inspect` and then check your log file to see what `@tweets` holds.
Comment: Another option would be to look at the documentation for the Twitter client you're using.
Comment: When trying to raise and inspect @tweets, I only get the tweet Id. I've looked through the client documentation and it seems a bit high level for me, so i'm trying to work through it bit by bit.
Comment: Instead of inspecting `@tweets`, try inspecting the first tweet, like this: `raise @tweets.first.inspect`.
Comment: That seems to still only bring the tweet ID :(
Comment: That's strange. What do you get when you try the following: `raise @tweets.first.to_yaml`
Answer: Answer provided by Mischa
To view the tweet attributes

Then use the attributes as follows

<%= tweet.created_at %> etc


Pros/cons: custom build rackets (for hobby/casual players)

Question: I'm considering whether or not it's worth the time or the money to invest in getting parts and put together a racket for a hobby/casual player. I am not horrible in the sport but it's pretty obvious I'll never compete in a respectable tournament. :)
So my question is all the fuss about equipment, how much of it would be useful for a player like myself and how much is marketing mumbo-jumbo? Of course it's impossible to give a quantitative measure to it, but I was wondering if there are other casual players who did end up buying better equipment (~100+ euros) and whether or not there was a difference to their overall gameplay.
Any feedback is welcome!
Comment: Could the down-voter please explain his/her motivation for the down-vote?
Comment: I didn't vote you down (voted you up back to 0) but they don't like shopping questions.
Comment: I'm also voting to close. My suggestion would be to rephrase asking about the benefits of custom paddles rather than a "is it worth it" which is entirely subjective and not exactly constructive.
Comment: your suggestion is fair, and I can go along with the edit. However I do not think this question is a "shopping question" as I am not asking for a brand/model comparison. All I wonder is if there are people out there who might have experience on the matter, and if according to their experience it's a sound investment. If it turns out that you need to have a pretty advance level to make good use of more expensive equipment that's rather valuable piece of information for casual players like myself. I'll edit the question title...
Comment: Hmm, I read "custom build rockets" and wondered why it was on Sports.SE
Answer: When I was competing at school I built my own one, and the end result not only felt just like one of the better ones I could buy, it cost me about the same.
It also took me a lot of time and effort to ensure the layers were correctly affixed and smoothed.
This is a very small statistical sample, but I would suggest buying a nice bat that feels good to you.
Comment: So you're suggesting that it's not worth that hassle, or have I misunderstood?
Comment: Correct - unless you really want to do it, I wouldn't bother.


CruiseControl.NET build fails when SVN is not available

Question: We have an SVN repository hosted externally and our build server is currently internal.  Occasionally (probably 1 or 2 times a day) the build server is unable to find the SVN repository due to a network outage, a timeout or some other random reason.  With an externally hosted repository this is hard to avoid, however when it fails to find the SVN repository it fails the build!
I would like to find a way for it to just try again at the next interval and ignore any errors relating to an unfound repository.  Does anyone know how I can do this?
I have posted my config for reference below.
<code><project name="MyProject" queuePriority="0">
<workingDirectory>C:\RemovedForPost</workingDirectory>
<artifactDirectory>C:\RemovedForPost </artifactDirectory>
<sourcecontrol type="svn">
  <trunkUrl>http://RemovedForPost \</trunkUrl>
  <workingDirectory>source</workingDirectory>
  <username>myuser</username>
  <password>*****</password>
</sourcecontrol>
<triggers>
  <intervalTrigger name="BuildAMinute" seconds="60" buildCondition="IfModificationExists" />
</triggers>
<tasks>
  <msbuild>
    <executable>C:\Windows\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable>
    <workingDirectory>C:\RemovedForPost</workingDirectory>
    <projectFile>C:\RemovedForPost\RemovedForPost.sln</projectFile>
    <buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs>
    <targets>Build</targets>
    <logger>C:\Program Files\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll</logger>
    <timeout>120</timeout>
  </msbuild>
  <nunit>
    <path>C:\Program Files\NUnit 2.5\bin\net-2.0\nunit-console.exe</path>
    <outputfile>C:\RemovedForPost.xml</outputfile>
    <assemblies>
      <assembly> RemovedForPost </assembly>
    </assemblies>
    <timeout>60</timeout>
  </nunit>
</tasks>
</code>

Thanks
Comment: Definitely lame.  I have that problem too.  +1.
Answer: Correction. All of what you want is in the new settings
CruiseControl.NET docs
You can set it to not report a failure until max retries is set. So make max at 3 and set it to only move onto the publisher (ie fail the build) unit it hits the limit. So 1 or 2 misses will be ok, but then 3 fail the build something is wrong.
Comment: But if you are having THAT many failures, don't you think you should be addressing the root cause of your problem?  I mean, this happens to me sometimes, but it's usually during scheduled downtime of the SCC provider for upgrades and the like.
Comment: Well it would fail only once 95% of the times, only twice in a row the other 5% so that trigger isn't going to be much use to me, but if I can't fix this I'll have to get rid of CC.NET.  With only 1-2 checkins a day we are getting a 50% build fail rate.
Comment: Well, I don't know where you would go. It would seem to be to be a basic priniciple of continuosu integration that if you cant reach the source control server you should fail the build. Is there a system you are thinking of that lets you configure this?
Comment: Good question, I don't know yet as I am fairly familiar with CC.NET and haven't had this problem with local repositories, only recently with remote ones, so I haven't tried others.  I'll see if I get any more responses first though as I'd hate to get rid of CC.NET.
Comment: My repository is off site, hosted in another country actually.  I could reduce the errors significantly if I changed the interval from 60sec to 30 mins, but I would rather not.  I am not surprised that 1 out of 1440 web requests fail on our network.
Comment: Mate that's awesome, that documentation wasn't there the last time I searched for it.  Exactly what I needed, though I won't know if it works for a few days it certainly appears like it will.  Thanks!
Comment: np, just remember thats for the latest release so you may have to upgrade ;)


A student answers a multiple choice examination question that offers four possible answers.

Question: Suppose the probability that the student knew the answer to any given question is $.8$, and the probability that the student guessed at the answer is $.2$. Assume that if the student guesses, the probability of selecting the correct answer is $.25$.
So I know how to do a). I'm just stuck on b).
a) What is the probability that the student really knew the correct answer? (that is, what is the probability that the student knew the answer, GIVEN that the student got the answer correct)
A= correct answer, C= answered correctly
$$P(A \mid C)= \frac{P(C \mid A)P(A)}{P(C \mid A)P(A)+ P(C \mid A^c)P(A^c)}$$
(1) $\dfrac{(.8)}{(1)(.8) +(.25)(.20)}$
b)  Suppose there is a third option. The student knew the answer with probability of $.7$, the student guessed with probability $.2$, and the student(incorrectly) thought they knew the answer given that the student thought they knew it is $0$. The conditional probability of a student getting the correct answer given that they guessed is still $.25$. Using this information, calculate the probability that the student really knew the correct answer.
Comment: So you know that $P(C|A) = 1$ in part a) - it is the probability that the student answered correctly given that he thought he knew the answer. Now it change to...
Answer:
Suppose the probability that a student knew the answer to any given question is $0.8$, and the probability that the student guessed is $0.2$.  Assume that if the student guesses that the probability that the student selects the correct answer is $0.25$.  What is the probability that the student knew the correct answer given that the student got the answer correct?

You obtained the correct value.  However, labeling the event that the student knew the correct answer as correct answer is misleading given that the other event is that the student answered the question correctly.
Let $K$ denote the event that the student knew the answer.  Let $C$ be the event that the student answered correctly.  We wish to find $P(K \mid C)$.
\begin{align*}
P(K \mid C) & = \frac{P(C \cap K)}{P(C)}\\
& = \frac{P(C \mid K)P(K)}{P(C \mid K)P(K) + P(C \mid K^C)P(K^C)}\\
& = \frac{1 \cdot 0.8}{1 \cdot 0.8 + 0.25 \cdot 0.2}\\
& = \frac{0.8}{0.8 + 0.05}\\
& = \frac{16}{17}
\end{align*}

Suppose the probability that a student knew the answer to any given question is $0.7$, the probability that the student guessed is $0.2$.  Otherwise, the student incorrectly thinks he or she knows the correct answer, in which case the student gets the question wrong.  Assume that if the student guesses that the probability that the student selects the correct answer is $0.25$.  What is the probability that the student knew the correct answer given that the student got the answer correct?

Let $K$ and $C$ be as above.  $T$ be the event that the student incorrectly thought he or she knew the answer. Let $G$ be the student guessed the answer. We wish to find $P(K \mid C)$.
Observe that $P(T) = 1 - P(K) - P(G) = 1 - 0.7 - 0.2 = 0.1$.
\begin{align*}
P(K \mid C) & = \frac{P(C \cap K)}{P(C)}\\
& = \frac{P(C \mid K)P(K)}{P(C \mid K)P(K) + P(C \mid T)P(T) + P(C \mid G)P(G)}\\
& = \frac{1 \cdot 0.7}{1 \cdot 0.7 + 0 \cdot 0.1 + 0.25 \cdot 0.2}\\
& = \frac{0.7}{0.7 + 0 + 0.05}\\
& = \frac{0.7}{0.75}\\
& = \frac{14}{15}
\end{align*}


Song structure in classical music vs EDM

Question: I've been playing piano for a few of months, and of the couple of pieces I know, neither of them are particularly repetitive. I mean they definitely have repetition, but much less so than EDM (electronic dance music). I guess it makes sense since dance music should be really repetitive to keep the groove and familiarity. You have stuff like chorus and drop in EDM but an ABAB ABCB etc. structure doesn't seem to be really relevant to piano. But it's more than that, there doesn't seem to be a beat that you can dance along to.
Sorry if this is all vague, but I was just wondering if people can point out to me some other more obvious differences between classical and EDM.
Comment: I'm voting to close this question because its focus is too broad: "music for piano" is a vast body of a few centuries worth of work (as well as more centuries that have been arranged for it), and even EDM is difficult to make generalizations about.
Comment: There are many, many structures in classical music, and some have more repetition and steady or prominent beat than others. Check out esp. the work of modern composer Steve Reich (and other "minimalists"), which relies heavily on repeating small musical chunks (or even samples) many times, and often has a strong and steady beat. Many electronic artists have said they're influenced by him.

But meanwhile, I'm afraid "list all the differences between two genres" is both too broad and [too subjective](https://music.stackexchange.com/help/dont-ask) to work as a question. Voting to close, sorry!
Comment: What are some of the piano pieces you know? You might get better replies, if we can compare to something specific.
Comment: Classical music not repetitive? What about the first movement of Beethoven's 5th symphony? Has anybody counted how many times that 4-note theme occurs?
Comment: Both "classical music" and "EDM" are umbrella terms covering many different styles. Details like composition structure can vary a lot between them. The question needs to be more focused to be answerable.
Comment: @Peter without counting I would say it repeats much less than the 2-note theme in Higher State of Consciousness :)
Answer:
But it's more than that, there doesn't seem to be beat where you can dance along to.

The entire baroque period is based on dance.
It essentially owes its existence to two phenomena, one of which is the development of meter: a beat you can dance along to.  This came from popular dance forms of the 16th century and was incorporated into more classical contexts such as opera (which was then a new form), and church music.
Of course, they were dancing somewhat differently, so their idea of "a beat you can dance along to" was somewhat different, too:

A popular form in the baroque period was the suite, which is a series of dance movements of various types: allemande, courant, gavotte, sarabande, minuet, gigue, and more.  These pieces typically had two sections that would both be repeated, and often they would come in pairs, where you'd play the first one again after playing the second, so twelve similar sections in a row.  This is seen as so superfluously repetitive by some modern performers that they neglect to perform the repeats.
This dance heritage survives into the classical and romantic periods in the sonata form, which is defined by a particular formal arrangement of repeated sections.  Since those pieces weren't intended for dance, the repetition is reduced and stretched out somewhat, so it is less noticeably related to dance, but it is nonetheless.

but a ABAB ABCB etc structure doesn't seem to be really relevant to piano.

Look at Mozart's Rondo alla Turca or any other rondo.  The form may not be exactly the same, but the principles are there.
Comment: @t_t The "rondo," as phoog mentions, is one of the repeating-est classical forms. It basically has a "refrain" that keeps coming back, like "ABACADA" etc.
Answer: In the way that you're asking, the primary difference is the scale of repetition. In classical music, entire sections of a piece might repeat, giving the piece its overall form. But small-scale repetitions — say, of just a few notes — are relatively limited, at least in the sense of defining the piece's overall structure.
EDM more often concerns itself with very small cells of repetition. Rather than forming the large-scale structure, they serve to anchor the other aspects of the music. The larger scale structure of EDM comes more from the sound design — the layers of sound, timbres, electronic effects — rather than the melodic or harmonic elements.
Where classical music intersects more closely with EDM is in some minimalist music, in which the repetition and evolution of small-scale elements form the core of the music. Composers like Philip Glass and John Adams have good examples of this, and you can hear it especially in many modern film scores in which the music is melodically repetitive, but the variations of orchestration (i.e., sound design) provide the musical interest.
Comment: @Edward That's true, but there is much greater focus on the "bar" scale that in common-practice classical music.
Comment: Lots of EDM has repetition both on the "bar" scale and the "section" scale- with multiple drops or verse sections that are similar to each other.
Answer: A very common form for "classical" keyboard compositions is ternary menuet da capo, or sometimes called things like trio da capo form. The sectional form could be something like this...

  Menuet            Trio
||: A :||: B :||  ||: C  :||: D :|| da capo (repeat menuet without repeats)

The menuet may use a key change at the end of A or its B section. There is a formal stop between menuet and trio. The trio is meant to contrast musically with the menuet and its A and B sections may involve a key change like the menuet. The form does not strictly need to be menuet. Many other small dances take this form.
Rondo form has similar sectional labels as menuet da capo, but the transition between sections is handled differently; there is no formal stop between sections. A common example is...

| A | B | A | C | A |

...where the A section is usually a repeating section fairly easy for a listener to recognize. The transitions from A to contrasting sections B, C, etc. often involve key changes.
Superficially, the A, B, C, D sections of those forms look like similar labels for verse, chorus, bridge, etc. in pop songs. But I see two differences in what those lettered sections represent.
First, in a pop song those sections might be only 2 to 4 bars in length, while in the classical forms those sections will usually be 8 or more bars in length. Also, the two styles usually differ in the harmonic content of their sections.
In a pop song a section may repeat a short chord progression many times. For example, an A verse in a pop song might repeat a four chord progression three or four times.
Sections tend to not change key in pop music, but in classical form, after a beginning section that stays in the opening key, it is very common for each section to transition away from its beginning key and end in such a way to prepare for a key change in a subsequent section.
In my opinion it is the handling of key changes that really distinguishes classical and pop form. In classical form key changes are the principle way to define formal sections. Pop music typically does not rely so strongly on key changes to define formal sections.
Many people focus on the brevity of thematic material — mostly melodic and chord progression ideas — in pop music and the tendency to repeat that brief material many times to expand the length of a song. In many cases that approach is due to a focus on rhythm and groove, and the prominence of drum kit percussion, in a way that is fundamentally different than classical style.
But, there are two "classical" forms that should be mentioned involving greater repetition of material. Both are types of variation form: ground bass and theme with variation.
In both cases the main material may be only 8 bars in length and it will be repeated with variation anywhere from 3 to 30 or more times. Ground bass will repeat a bass line many times while playing varied melodic material above it. Theme and variation also involves melodic embellishment and variation, but the whole texture can change, and the bass isn't unchanging like in ground bass.
Formal labelling might simply identify an A section of maybe | A | B | which will be repeated many times. From the harmonic perspective these are classical forms that may be as harmonically simple as some pop songs.

You have stuff like chorus and drop in EDM but a ABAB ABCB etc structure doesn't seem to be really relevant to piano.

Both styles can label sections with letters in a superficially similar way. Beyond the obvious differences in rhythm and instrumentation between the two styles, the big difference is how key changes define such sections in classical style.


Upper and lower indices when identifying tangent space vectors with underlying vector space

Question: Given an $n$-dimensional manifold $M$, we can construct a basis for each tangent space $T_pM$ from a local coordinate basis $\{x^i\} \subset \mathbb{R}^n$ as
$$\vec{e}_i = \left( \frac{\partial}{\partial x^i} \right) \quad \forall\, i \in \{1,2,\ldots,n\}$$
(as is done e.g. here). It is then conventional to denote vectors $\vec{v} \in T_p M$ in this basis as $\vec{v} = v^i \vec{e}_i$, where we can interpret the raised index in $v^i$ as a sign that the vector is contravariant, or that it is a $(1,0)$ tensor that assigns to the tangent basis vector $\vec{e}_i$ a value $\in \mathbb{R}$.
Now, if $M$ is a vector space $V$, we can identify the tangent vectors $\vec{v} \in T_p V$ at any point $p \in V$ with vectors from $V$ itself. My main question is whether there is any justification for, or anything deep that can be understood from, the fact that when we perform this identification, the indices are somehow not where they should be. If we take the local coordinate basis $x^i$ from before as a global basis in $V$, then it seems that:
$$\vec{v} = v^i \vec{e}_i \in T_p V \quad \text{can be identified with} \quad \vec{v}' = v^i x^i \in V \quad\text{(or should it be }v_i x^i \in V\text?).$$
Since the position of the index is significant when applying tensors to these quantities, I want to make sure I don't just gloss over this as just an artifact of the notation. Specifically, the position of the index in the tangent space basis vector $\vec{e}_i$ seems to clash with the corresponding vector space basis component $x^i$ when we identify one as the other.
Is the answer just to always cleanly separate between the elements of $T_pV$ and $V$ itself, even if there is a bijection between them?
Context: Took a mathematical introduction to manifolds and am trying to reconcile the concepts and notation used in (special) relativity, where the distinction between $M$ and its tangent spaces is routinely dropped, with the notions from manifold theory.
Answer: If $\{\xi_1, \dots, \xi_n\} \subset V$ is a basis for a vector space $V$, then it gives rise to a dual basis $\{x^1, \dots x^n\}$ for the dual space. i.e $x^i:V \to \Bbb{R}$ are linear functions, which means each $x^i$ is an element of $V^*$, NOT $V$. So, given any vector $\vec{v} \in V$, we can always write it as a linear combination of $\{\xi_1, \dots, \xi_n\}$ as
\begin{align}
\vec{v} &= \sum_{i=1}^n v^i \xi_i
\end{align}
and by unwinding the definition of the dual basis, you can check for yourself that $v^i = x^i(v)$, i.e the evaluation of $x^i:V \to \Bbb{R}$ on the vector $\vec{v} \in V$. So, using the summation convention,
\begin{align}
\vec{v} = v^i \xi_i = x^i(v)\cdot \xi_i \in V
\end{align}
You're probably getting confused because of your own terminology; for example in the very first line you write the misleading statement:

... can construct a basis for each tangent space $T_pM$ from a local coordinate basis $\{x^i\}\subset \Bbb{R}^n$ as...

It is not true that $x^i \in \Bbb{R}^n$, so it is definitely not true that $\{x^i\}$ forms a "local coordinate basis". What it is, is a local coordinate system/chart. When we intuitively speak of coordinates, what we think of is that every point has associated to it a certain set of numbers; so if we translate this directly into more formal language, what it amounts to is $n$-functions $x^i: M \to \Bbb{R}$.

Note that it is perfectly fine to identify $T_pV$ with $V$, because you get this isomorphism simply from the existing data of the smooth structure (i.e if $(M=V, \mathcal{A})$ is your smooth manifold and $\mathcal{A}$ is the maximal smooth atlas containing the identity chart $(V,\text{id}_V)$, then this automatically induces an isomorphism of each tangent space with the underlying vector space).
However, what is not fine is to arbitrarily invoke isomorphisms of $V$ with $V^*$, without any further structure (like a pseudo-inner product). Also, in some cases, for example if you have a basis $\{\xi_1, \dots, \xi_n\}$ of $V$ and the dual basis $\{x^1, \dots, x^n\}$ of $V^*$, then yes, you can get an isomorphism $V \to V^*$. But, just because you can do so, doesn't mean you should (I for one never like to mix up my vector space with its dual, because it is very easy to quickly get confused about what is actually going on).
Comment: @MrArsGravis Sure, if you want to express it in that way, but I personally find that very confusing terminology, which is very easily misunderstood. $\frac{\partial}{\partial x^i}(p)$ means every smooth function $f$ gets mapped to the real number $[\partial_i(f\circ x^{-1})](x(p))$. Which means you take the $i^{th}$ partial derivative of the chart representative function $f\circ x^{-1}$, and then evaluate at the point $x(p)$. I highly recommend you watch [this lecture](https://www.youtube.com/watch?v=pepU_7NJSGM), (especially 50 minutes onwards)
Comment: I finally got around to watching the lecture and I did enjoy it. Essentially, he gets around the issue by defining $x^i$ as the $i$-th component of the chart function $x: M \to U \subset \mathbb{R}^d$, which is a clean way to do it and circumvents my whole confusion surrounding the index placement. As for SR, I'll try to keep in mind that Minkowski space itself is really an affine space and always distinguish between the tangent vectors and the points.
Comment: I was referring to a basis of the subset of $\mathbb{R}^n$ generated by a chart that covers a neighborhood of the point $p \in M$, yes. So you're saying I could fix the issue by redefining the basis in the tangent space as $\vec{e}_i = \frac{\partial}{\partial \xi_i}$? That would seem reasonable to me, but for some reason the index in the denominator is always raised in other sources...?
Comment: (which isn't really redefining as much as it is "renaming" according to a different convention, one where the index is lowered)
Comment: @MrArsGravis The tangent vector is denoted $\frac{\partial}{\partial x^i}(p) \in T_pM = T_pV$. The $x^i$ always has an upstairs index to make thing work out nicely with summation convention, but really you shouldn't really focus on the index placement so much. More important is to understand what each object is, which space everything lives in, what structure you have, and what are the isomorphisms available. The isomorphism between $T_pV$ and $V$ is given by sending $\frac{\partial}{\partial x^i}(p) \mapsto \xi_i$.
Comment: Ahh, I believe the issue is that I thought the derivative is taken with respect to an element the basis of $V$, but it is actually taken with respect to a coefficient of such a basis vector, which can be related to the dual vector to that basis vector. Does that seem correct?


Cumulative Distribution Function of $X = Y*I + Z*(1-I)$

Question: I have a random variable $X = Y*I + Z*(1-I)$ where $Y~N(u, sigma^2)\,,\,\, Z~N(u, sigmac^2)$, and $I~B(1,1-p)$.
What I can't seem to figure out is how to get a cumulative distribution function for $X$. Any help would be greatly appreciated!
Answer: \begin{eqnarray*}
  \Pr \left[ X \leqslant x \right] & = & \left( 1 - p \right) \Pr \left[ Y
  \leqslant x \right] + p \Pr \left[ Z \leqslant x \right]\\
  & = & \left( 1 - p \right) \Phi \left( \frac{x - u}{\sigma} \right) + p
  \Phi \left( \frac{x - u}{\sigma_c} \right)
\end{eqnarray*}
where $\Phi$ is the cumulative distribution function of the standard normal
distribution.
As Stefan Hansen points out (many thanks), this is assuming independence of the underlying random variables.
Comment: Assuming that $I$ is independent of both $Y$ and $Z$.
Comment: @StefanHansen Many thanks for improving the answer!
Comment: You're welcome :) +1
Comment: As usual it was more straightforward than I thought. Not to ask another question entirely, but do you guys know how I could get the probability density function from this? My thinking is that maybe you could distribute the Φ((x−u)/σ) through the (1-p). Then maybe the p's can be multiplied by the given normal distributions' probability density functions. Does that make sense? Thanks again in advance for any help!
Comment: @Spencevail Take derivatives with respect to $x$ to get the pdf.


how to download jwplayer streaming video?

Question: i subscribe to drupalize.me .but due to my slow internet connection i am not able to see video tutorials properly.i think this site use jwplayer and site provide no downloading option for videos.can anyone tell how to find direct downloading link of streaming video? if anyone give direct downloading link of drupalize.me free sample video it will be great.please help me
Answer: There is a way that works for me.
In an addition I removed <code>-a vod</code> option because it caused an error.
Comment: rtmpExplorer (GUI for rtmpdump) is just awesome. It allowed me to paste the url of main page and gave the option to download the video directly!!!
Answer: Real player has a browser plugin that does that, (works well only in IE)
Also IDM (internet download manager) does the same (again IE only) I've disable both plugins on chrome after having problems with it.
http://www.internetdownloadmanager.com/
https://www.youtube.com/watch?v=xY_7HRgsw8g
Real Player is free IDM is not (other than the cracked versions on torrent ;) )
IDM allows to select what video stream to download
(if you change resolution on youtube, you'll see 2 files for download, 1 for each resolution)


wording of modular arithmetic

Question: Should we say find the inverse of a residue modulo n or find the inverse of an integer modulo n? I am trying to get the precise wording for an elementary number theory course.
Answer: $ab \equiv 1 \pmod n$ is read $ab$ is congruent to $1 \pmod n$
and $b$ is the modular multiplicative inverse of $a \pmod{n}$ such that:
$a^{-1} \equiv b \pmod{n}$
Comment: Is it wrong to say b is the inverse of the residue a mod n?
Comment: It wouldn't sound that bad at all, but I've never seen nobody using that sentence before. The inverse operation is called modular multiplicative inverse.
Comment: Thanks for clearing this up. My only reservation is modular multiplicative inverse is bit of a mouthfull and not clear what it actually means but if this is the correct term then I'll use it. Much appreciated.

wording of modular arithmetic


Unable to deserialize Json that contain 2 objects with the same ID using jackson

Question: I have used jackson JsonIdentityInfo to handle the recursive object reference in spring mvc.
I came across one issue i.e., Unable to deserialize Json that contain 2 objects with the same ID.
<code>{

    "organizations": [
        {
            "organizationId": 1,
            "organizationName": "org1",
            "enterprise": {
                "enterpriseId": 1,
                "enterpriseName": "ent1",
                "organizations": null
            }
        },
        {
            "organizationId": 2,
            "organizationName": "org2",
            "enterprise": 1
        }
    ]
}
</code>
if you see above, both organizations are mapped with enterprise "1". For the first organization it is whole enterprise object but for organization 2, it is giving ID only.
I need to get the whole object for organization 2 as well.
My POJO declarations:
<code>@Entity
@Table(name = "organization")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "organizationId")
public class Organization implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "organization_id")
    private Long organizationId;

    ...

    @ManyToOne
    @JoinTable(name = "enterprise_organization", joinColumns = {
            @JoinColumn(name = "organization_id") }, inverseJoinColumns = { @JoinColumn(name = "enterprise_id") })
    private Enterprise enterprise;

    ...
}

@Entity
@Table(name = "enterprise")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "enterpriseId")
public class Enterprise extends BaseEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "enterprise_id")
    private Long enterpriseId;
    ...

    @OneToMany(mappedBy = "enterprise")
    private List<Organization> organizations;
    ...
}
</code>
I searched google and SO but no luck.
What are the changes needed to deserialize Json that contain 2 objects with the same ID ?
Comment: what happens if you change `private List organizations;` to `private Set organizations;`
Comment: @Patrick I have changed List to Set. Still same issue. FYI, I am using mapping table. So NO issue with the datatype.
Comment: @Krishna Dont think you can do that in a simple generic way. Probably can try https://stackoverflow.com/a/24684251/1032167 or implement custom id Generator, but i think it will be much harder to read and understand then custom serializer/deserializer.
Comment: @Krishna btw if you need only deserialization, you can look at https://github.com/varren/JsonIdentityInfoAlwaysAsObjectSerializationJackson had similar problem back in the days. It is more like a hack that a solution...
Comment: @varren thanks for your response. In the link you provided, it is hard coded with "id", how can I do it for different id names like "enterpriseId", "organizationId" etc.. ?
Answer: After a lot of tries, @JsonIgnoreProperties solved my problem.
example: "@JsonIgnoreProperties(allowSetters = true, value = { "enterprise" })"


Problem with beautifulsoup.find() in Python

Question: I'm new to web development and I'm trying to make a web crawler of this website.
I want to grab the main content in
 so I tried this code:
main_content = soup.find_all("div", class_="entry-content")

but it always cut off at the middle of the Jukugo table.
However when I inspect the page and copy the
 and paste it out to another file, the whole thing was displaying just fine, no cut off.
Could you help me identify what is the problem here? How should I go about crawling this site?
Thank you so much.
Sorry if my question is roundabout, English is not my native language.
What I wanted to crawl:

What I crawled:
Comment: Maybe the rest of the table is added by JavaScript?
Comment: I'm not sure, but I think the part I'm trying to scrape doesn't have javascript in its table.
Comment: I actually tried preloading the website and I got all of the contents! So I guess there is javascript in the page after all. Thank you so much for the suggestion!
Answer: I just tried scraping the page using the select function of BeautifulSoup and think this gives your desired result:
soup.select("div.entry-content").
Note that with the select function you can use CSS selectors (e.g., div.entry-content) to easily reach nested elements.
Comment: Thank you for taking a look, but the table got cut off halfway just like my code.
Comment: Why do you think `select` would return anything different from `find_all`?


Getting interface MTU under Linux with PCAP

Question: I am interested in storing packets I sniff using PCAP.
As I preallocate the memory I need - i.e. a multiple of the MTU of the interface I am sniffing from, I would like to discover how much memory I need before opening the live session.
Is it possible to query PCAP for getting the MTU of the sniffed interface ?
How can I get this information otherwise (possibly using system libraries) ?
Thanks
Answer: One option on linux would be the sysfs file mtu in /sys/class/net/devicename
$ cat /sys/class/net/eth0/mtu /sys/class/net/lo/mtu
1500
16436

Answer: There is not a straightforward way to do so in PCAP (no API).
However, for Linux >=2.6 Solvent posted a simple solution that is reading a file like the following: /sys/class/net/INTERFACE_X/mtu. It is trivial to do it in C.
int getMTU(char *name) {
FILE *f;
char buf[128];
char *line = NULL;
ssize_t count;
size_t len = 0;
int mtu;

snprintf(buf, sizeof(buf), "/sys/class/net/%s/mtu", name);
f = fopen(buf, "r");
if(!f) {
    perror("Error opening:");
    exit(EXIT_FAILURE);
}
count = getline(&line, &len, f);

if (count == -1) {
    perror("Error opening:");
    exit(EXIT_FAILURE);
}
sscanf(line, "%d\n", &mtu);
fclose(f);

return mtu;
}

Reading the PCAP source, I found out that the PCAP developers used a more complex, yet elegant solution to read the interface MTU invoking ioctl. This is a simplified version I wrote:
#include <sys/ioctl.h>
#include <net/if.h>

int get_mtu(int fd, const char *device) {
struct ifreq ifr;

if (!device)
    return 65535;

memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));

if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
    perror("Error opening:");
    exit(EXIT_FAILURE);
}

return ifr.ifr_mtu;
}

For further references, man netdevice is suggested.


R Logistic regression and correlation

Question: I'm having trouble understanding the output of this logistic regression in R.
Data
dat <- data.frame(
  var1 = c(2, 2, 2, 2, 2, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1,
    1, 2, 1, 1, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2,
    2, 1, 2, 1, 1, 2, 2, 2, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 1, 1,
    2, 1, 2, 2, 2, 2, 2, 1),
  outcome = c(1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0,
    0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0,
    1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0,
    1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0,
    1, 0, 1, 1, 1, 0, 1, 0),
  var2 = c(70, 86, 80, 88, 74, 75, 76, 82, 79, 80, 80, 79, 81, 79, 77,
    75, 77, 75, 70, 65, 67, 86, 87, 70, 81, 66, 76, 62, 62, 73, 65,
    66, 65, 85, 82, 76, 64, 68, 66, 83, 69, 73, 82, 65, 86, 74, 62,
    68, 64, 81, 72, 74, 63, 63, 76, 79, 82, 73, 78, 70, 68, 72, 72,
    60, 73, 73, 74, 86, 77, 81, 63, 79, 74, 76, 83, 85, 61, 83, 73,
    71, 72, 59, 77, 73, 67, 80, 84, 77, 79, 73, 86, 75, 79, 78, 82,
    80, 78, 58, 82, 74, 77, 78, 67, 68, 82, 72, 65, 85, 83, 69, 73,
    78),
  stringsAsFactors = FALSE)

Regression:
fit <- glm(outcome ~  var1 + var2 ,
           data = dat, family = "binomial")
summary(fit)
Call:
glm(formula = outcome ~ var1 + var2, family = "binomial", data = dat)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-2.61347  -0.00006   0.31030   0.41875   0.74162

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept)  -47.79642 3650.08385  -0.013    0.990
var1          22.03545 1825.04048   0.012    0.990
var2           0.08264    0.05621   1.470    0.142

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 145.993  on 111  degrees of freedom
Residual deviance:  45.062  on 109  degrees of freedom
AIC: 51.062

Number of Fisher Scoring iterations: 18

From the results, the var1 has a very high p value, so my understanding is that in contribute poorly in predicting the 'outcome'.
But when I look at the correlation between the 2, they are highly correlated. And the inverse is true, var2 has a lower p-value but not a good correlation with 'outcome'
Can anyone explain, why ? This is probably trivial, but I can't find the answer.
cor(dat)
             var1   outcome      var2
var1    1.0000000 0.8671209 0.1029565
outcome 0.8671209 1.0000000 0.1587125
var2    0.1029565 0.1587125 1.0000000

Answer: First of all, there's nothing wrong with your model.  You haven't told us anything about the nature of the data (which appear to have been invented for the sake of demonstration) or the purpose of your model, so I don't see any point in talking about "improving" the model.  It sounds like you would benefit from a better understanding of how correlated predictors affects a regression model.
Let's start with an illustration that may give you a better feeling for what goes on:
Consider a situation in which you're trying to determine the effect of t-shirt color {Red, Blue} and hair color {blonde, dark} on weight {0-100}.
First, you observe a red-shirted blonde person who weighs 50 pounds, and then a blue-shirted dark-haired person who weighs 100 pounds.  Note that in this example, hair color and shirt color appear to be perfectly correlated.
Based on the data alone, you would be unable to decide whether a blue shirt has a weight-increasing effect of +50 pounds, or whether dark hair has a weight-increasing effect of +50 pounds.  In terms of the model, the effect of shirt color could have no effect (if hair color was the "cause") or it could be fully responsible for the +50 (if hair color had no true effect).
Note that this example is really oversimplified, but hopefully the essence is clear -- when two variables are correlated, it makes it difficult to tell which of the two had the true effect.  In a model, this translates to an increase in the variance--or wider confidence intervals in both variables.
Both of the previous answers pointed out that fitting a model with just Var1 in it led to the model concluding that Var1 had a significant effect on the outcome.  However, in the full model you have added a second covariate Var2, which is highly correlated with Var1, and the resulting model has a hard time telling which--if any-- of the two variables has a significant effect on the outcome.
One thing that's important to point out is that larger model (i.e., with var1 and var2) appears to explain the outcome better than a model with just var1.  Note that the AIC of the larger model (51.062) is better than the smaller model fit by @Bernhard (55.045).  This is generally true, as adding correlated predictors to a model does not necessarily result in a "poorer" model.  Rather, it simply means that the parameter estimates will be harder to interpret (i.e. can you really attribute the estimated effect to the associated variable when it is so highly correlated with another variable?)
In short:
You've done nothing wrong; you've simply demonstrated that multicollinearity causes the variance of parameter estimates to increase.  I would caution that your interpretation of a p-value ("that in contribute poorly in predicting the 'outcome'") is problematic and may be one reason why this result seems confusing.
Answer: First of all, just to state the fact. The model is bad in the sense that it overfits and actually none of the predictors are good (significant).
Correlation just reflects the amount of linear association between two objects, it does not necessarily translate into the fact that it will be useful in including the variable in logistic regression when it correlates with the output.
If you plot "var1" vs "outcome" and "var2" vs "outcome", you can see that there is no linear association in var2 vs outcome case and there is some "spurious" correlation in "var1" vs "outcome" case.
Given that you are predicting binary data, your model is using "var1" as the best out of the worst parameters to overfit and give the lowest error.
Consider improving your model.
Answer: This is not a complete answer but may give insight that will help finding an answer.
Looking at your data, var1 should easily explain outcome, mostly on its own:
plot(outcome ~ jitter(var1), data=dat)

Yet, glm does not come to a "significant" result, as long as there is only 1 and 2 values in var1. That somehow leads to enormous standard errors. As soon as you add a little jitter to var1, just as I did in the plot above, the standard errors drop drastically and all results are highly significant
> summary(glm(outcome ~ jitter(var1), data=dat, family=binomial))

Call:
glm(formula = outcome ~ jitter(var1), family = binomial, data = dat)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.7033  -0.1286   0.2903   0.4610   0.7332

Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)   -11.405      2.988  -3.818 0.000135 ***
jitter(var1)    6.982      1.586   4.402 1.07e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

Null deviance: 145.993  on 111  degrees of freedom
Residual deviance:  51.045  on 110  degrees of freedom
AIC: 55.045

Number of Fisher Scoring iterations: 7

Adding jitter increases the residual deviance from 47.29 to 51.0 so the model is not better, just the standard errors are smaller.
I have no conclusive answer as to why the "perfect" var1 leads to these enormous standard errors but apparantly that is a huge non-obvious part of the problem here.

R Logistic regression and correlation


How to show quicktime videos in succession

Question: How do I have two or more quicktime videos to play one after the other, with no action taken by the user? I've seen an example of the technique here:
http://untitled.wiredrive.com//l/p/?presentation=7c79bedbb8b02d2b1da45b033cc20345
I can't seem to boil down their code to the good stuff. Thanks!
Answer: it has been a long time since i programmed in QuickTime; but AFAIR, the C API lets you easily create a movie on memory.  What I'd do is just create a long movie with references to those you want to play.


How to prevent entering a time-slot that is already taken when using the Calendar module?

Question: I have installed and enabled the Calendar module. I have noticed that this allows multiple events for the same time slots. It means if event 1 is on Aug 12th from 11-12, I can still enter the same time slot for event 2.
In this case, how can I apply a logic so it complains that if the time-slots already taken?
Answer: I'm not aware of any way to use the Calendar module for this. However, you may want to look at this set of modules (with an official D7 release) that may help to implement the logic you are trying to implement:

Availability Calendars (Reported installs: 2.061 sites).

... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.
An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Rooms (Reported installs: 1.575 sites).

... is a booking and room management solution for hotels, vacation rentals and B&Bs.

Its module page also mentions some related modules you may want to look at, such as:

Rooms Package: Define special offers for bookings.
Rooms Availability Constraints - Allows admins to define availability constraints such as the minimum period of a booking.
Rooms Views- Provides a "Rooms availability" filter and a "Booking form" field to improve the Views integration for Rooms.

MERCI (Reported installs: 441 sites).

... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.

Resource Conflict (Reported installs: 329 sites).

... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

Simple Reservation (Reported installs: 202 sites).

... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.
The module provides the possibility to create reservations for other users (dependent on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.
There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.

Room Reservations (Reported installs: 156 sites).

... for use by academic libraries to manage access to and use of their study rooms.
All academic libraries have rooms set aside for student study and collaboration. These rooms are often available on a first come, first serve basis. Many libraries would like to have a room reservation system that would allow students to better plan their use of these often scarce resources, but setting up and administering such a system without computer support is a very difficult and time consuming undertaking.
The Room Reservation module was created to meet this need. It allows any library to very quickly put together a reservation system customized to its own particular requirements. And once the system has been set up, it performs all the functions necessary to manage the use of group study rooms with practically no involvement from the library staff.
Although this application was written specifically for use by academic libraries, it could also be useful to any facility that provides rooms that can be reserved and used on a short term basis.

Booking Systems Comparison
Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.
This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).
How to pick the module that fits best
I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.
So do your homework to pick the right one for you. E.g. by using criteria such as those I often use for selecting module, as mentioned in the community documentation about Maintenance Scorecards. Here is the intro about it (from that page):

... contains a list of 23 criteria (=28-5) that might help to evaluate
  the maintenance and support of contributed modules. Below is an
  attempt to apply those criteria to each of the native charting modules
  ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.
Disclosure:
I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph).


Unable to reach controller ActionResult from javascript

Question: EDIT 2
I was able to solve the problem. There was nothing wrong with the Javascript or Controller code. The problem came from a .dll file. In the controller method I build a new TextInfo object from the TextModel object. The TextInfo object comes from a .dll that's build from the API. This .dll however had multiple instances with different build dates in the File System. Seems like the old version wasn't removed properly but it was the one the compiler used. This created a 500 Internal Server Error telling me that a Method wasn't available.
EDIT 1
I'm fairly certain my problem stems from a property in my model not being set correctly but I'm not sure why. I had 1 instance where I was able to debug though furhter into the code but I'm clueless as to why or how that happened. Will update later once I find more answers.
I am having trouble accessing the controller action from my ajax call and it honestly makes no sense to me as to why I'm unable to start the code. The issue seems to be with the CurrentPageNumber. When I comment out this variable from both c# and javascript, I am able to hit the breakpoint in the controller. But when I uncomment that variable I can't hit the breakpoint. The error I'm getting is 500 Internal Server Error. To me that sounds like the JSON keys aren't the same as the Controller parameters, but as you can see below that isn't the case (unless if I turned blind). Any idea what the problem could be? Prehaps I'm looking in the wrong direction?
tl;dr Controller ActionResult not started when CurrentPageNumber is in the parameter and key list (uncommented), but it does start when it isn't (commented out).
I am trying to reach the following ActionResult.
public ActionResult SavePageInfo(List<TextModel> TextObjects, string ImageSource, int CurrentPageNumber)

I do this with the help of the following AJAX call
var json = JSON.stringify({ TextObjects: textObjects, ImageSource: imageSource, CurrentPageNumber: pageNumber });

$.ajax({
    url: "/NextprintPhotobook/SavePageInfo",
    type: "POST",
    data: json,
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        console.log(data.message);
        alert(data.message);
    }
})

The JSON that's produced looks like this (as you can see all values are set):

"{"TextObjects":[{"text":"Test","x":50,"y":50,"fillColor":"#77DD44","fontFamily":"arial","fontStyle":"normal","fontSize":"18pt","fontWeight":"normal","textAlignment":"start","angle":0}],
  "ImageSource":"http://localhost:22223/api/file/getfile?name=04.jpg&collectionId=4103&version=1&size=original",
  "CurrentPageNumber":1}"

TextModel is as follows:
public class TextModel
{
    public string text
    {
        get; set;
    }
    public int x
    {
        get; set;
    }
    public int y
    {
        get; set;
    }
    // Same properties as in the JSON.
}

Comment: got a feeling it may have to do with mvc and mapping to your list param... they need to be indexed soda speak.. try looking into this... i could be wrong.... mvc adds prefex names to lists with index's so that it knows how to map to lists..
Comment: are you sure your url is correct?  try with the '/' in the begining NextprintPhotobook/SavePageInfo
Comment: Use `@Html.ActionLink()` instead of text url.
Comment: @Seabizkit The tl;dr says that the code works if the CurrentPageNumber is commented out. Doesn't that tell us that the indexing of the list is done correctly?
Comment: The URL is correct. I've been able to hit the first line in the controller function as explained in the text.
Comment: Use your browser tools (Network tab) to inspect the response - it will give you the details of the error
Comment: @DaBazz totally get you, and agree.. i'm not sure if you are describing it 100% tho....as then it would be hard to understand why it is not working.... what is the 500 error message. like the actual message, which key is it complaining about.
Comment: have you tried just using a different variable name on both sides. I know it doesn't make sense... just ruling out
Comment: @StephenMuecke It seems like it errors on setting a property of TextModel. But I'm not sure why (setWeight not found). I have had a weird interaction while debugging though where I did hit the breakpoint in the controller code that I was looking for (which means the setWeight was found in this instance?). I'll comment again once I found the problem later today.
Comment: Resolved the problem. It came from a malicious .dll file that wasn't deleted after the project was cleaned/(re)build. More info in original post.
Answer: Why are you not using a single object as parameter (a wrapper class for all those params)? (usually this is how it is done, unless you want to add some params in the query string also)
Comment: ill let someone else mark this down. as i want to be neutral, but how does this solve or help his problem
Answer: this is not the answer... well (i just want to put it here so its easier to read)
try this:
var data = {
    TextObjects: JSON.stringify(textObjects),
    ImageSource: imageSource
    CurrentPageNumber: pageNumber
}

$.ajax({
    url: "/NextprintPhotobook/SavePageInfo",
    type: "POST",
    data: data,
    dataType: "json",
    contentType: 'application/json; charset=utf-8',
    success: function (res) {
        console.log(res.message);
        alert(res.message);
    }
});

Comment: my only problem with this is im sure JSON.stringify(textObjects) will not be in the MVC controller auto-mapping format for collections


What is the use of @db_query?

Question: I have used db_query to retrieve table rows from database. Recently I noticed, some people use @db_query instead of db_query.
I dont see any difference with the two. Is it doing any special functionality that normal db_query doesn't?
Comment: `@` is pure PHP, Drupal independent [Error Control Operator](http://php.net/manual/pl/language.operators.errorcontrol.php)
Comment: Yea, either that, or it will cause WSOD preventing you from seeing what exactly failed beyond repair.
Comment: @Mołot: Thanks. So, you saying. if I mistakenly tried to access the field which is not available in the table, this `@` will ignore the sql error and proceed to the next statement anyway?
Answer: @ is the error control operator, what it does is suppress notices/warnings and even script halting errors. You see it most commonly used with variable comparisons where the person coding didn't bother to check if a variable is set first.
if (@$unsetVar != $var) {
  @$unsetVar .= $non_existent_variable';
}

Suppresses the warning that $unsetVar is not initialised.
The proper way of doing this though would be using isset($unsetVar) to check that this variable is in fact initialized first, if not don't do anything with it, or assign it a default of some kind. Then neither the comparison or the concatenate will throw errors. Keeping this in mind can prevent some show stopping bugs later down the line as your applications become more complicated.
I'd personally advise against using @ wherever possible, if there's a notice/warning/error it's usually for a reason, using @ is a lazy fix and can make debugging a pain if something does go wrong.
Tl;dr, I'd avoid using @ where possible.

What is the use of @db_query?


Evidence that Collinearity Causes Predictors to be Insignificant

Question: Question: Is there any evidence that collinearity causes some predictors in this model to be insignificant?
Using R, I calculated the correlations of the predictor variables of a linear model.
<code>         lcavol lweight  age  lbph   svi   lcp gleason pgg45
lcavol    1.00    0.19 0.22  0.03  0.54  0.68    0.43  0.43
lweight   0.19    1.00 0.31  0.43  0.11  0.10    0.00  0.05
age       0.22    0.31 1.00  0.35  0.12  0.13    0.27  0.28
lbph      0.03    0.43 0.35  1.00 -0.09 -0.01    0.08  0.08
svi       0.54    0.11 0.12 -0.09  1.00  0.67    0.32  0.46
lcp       0.68    0.10 0.13 -0.01  0.67  1.00    0.51  0.63
gleason   0.43    0.00 0.27  0.08  0.32  0.51    1.00  0.75
pgg45     0.43    0.05 0.28  0.08  0.46  0.63    0.75  1.00
</code>
I thought that there is a relatively strong correlation between lcp and lcavol, lcp and svi, lcp and gg45, gleason and gg45.
Would a correlation value of >0.5 be considered a strong correlation (ie: one of the variables would do a good job of representing the other)? How do we determine the minimum benchmark for when two variables have a strong correlation?
Comment: Individual correlations tell you little unless they are very close to $1$ in absolute value.  It is possible for all correlations to be relatively low but for one variable to be *perfectly* collinear with the rest of them.  See https://stats.stackexchange.com/a/14528/919 for an analysis of this kind of situation.
Answer: 0.5 would not be considered high correlation in terms of the effect on standard errors. In my experience it only tends to become problematic at correlations quite close to 1.
A little simulation can demonstrate this.
<code>> library(MASS)
> set.seed(1)
> N <- 20
> rho <- 0.5
> Sigma <- matrix(c(1, rho, rho, 1), 2, 2)
> u <- mvrnorm(n = N, c(10, 10), Sigma, empirical = TRUE)
> X1 <- u[, 1]
> X2 <- u[, 2]
> Y <- X1 + X2 + rnorm(N)
> lm( Y ~ X1 + X2 ) %>% summary()

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  -3.3380     2.1116  -1.581    0.132
X1            1.1514     0.2104   5.472 4.13e-05 ***
X2            1.1963     0.2104   5.686 2.68e-05 ***
</code>
Now if we change the correlation to 0.95:
<code>> set.seed(1)
> N <- 20
> rho <- 0.95
> Sigma <- matrix(c(1, rho, rho, 1), 2, 2)
>
> u <- mvrnorm(n = N, c(10, 10), Sigma, empirical = TRUE)
>
> X1 <- u[, 1]
> X2 <- u[, 2]
>
> Y <- X1 + X2 + rnorm(N)
>
> lm( Y ~ X1 + X2 ) %>% summary()

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  -2.9106     1.8540  -1.570   0.1349
X1            1.0814     0.5836   1.853   0.0813 .
X2            1.2235     0.5836   2.097   0.0513 .
</code>
Comment: Removing *any* predictor reduces multicollinearity.  Focusing on individual p-values for model-selection (which, when conducted in a principled way, is called *stepwise selection*) often doesn't work as well as many other methods.
Comment: Thank you! Does that mean there are no insignificant predictors (since none of the variables have a strong correlation, then none of them would do a good of representing the other)? I believe removing insignificant predictors reduces collinearity, correct?
Comment: Unless you have extremely high correlations, you shouldn't have a problem with multicollinearity. Correlations are to be expected with real world, observational data. Only in (well conducted) controlled experiments might you find no correlations between predictors. If you are building a model it is best to do so using knowledge of all the variables, if at all possible. As mentioned by @whuber, stepwise procedures are not very good, generally speaking, especially if you are trying to *understand* the data.


Is there a way to determine the Hostname or IP of a computer given the AD user account logged in?

Question: If I know John Doe is logged into a workstation on my network, is there a way to determine what computer he is on using his account, in Powershell preferably.
Comment: You could do this by enabling Kerberos auditing on your Domain Controllers. Then just look for eventID 4769 containing the target username. This event will provide the IP of the computer being used. If NTLM authentication is being used, then look for eventID 4776. This will provide the hostname and not the IP.
Answer: If you don't have a tool to do this, I'm guessing you don't have a super large inventory. One way you could do this is to inventory all the computers in AD (in this example, Windows 7 or Windows 10). Then check each of those computers for who is logged in.
<code>$TheseComputers = (Get-ADComputer -Filter {OperatingSystem -Like "Windows 7*" -or OperatingSystem -Like "Windows 10*" } -Property *)

foreach ($Computer in $TheseComputers) {
    Get-WmiObject –ComputerName $Computer.name –Class Win32_ComputerSystem | Select-Object UserName
}
</code>
Comment: Thanks! This works. In the future I'll try to create a custom attribute that the host-name or IP is written to when they login. And maybe a logoff script to clear it.


Jaspersoft report plugin for integrating tree view into inputbox control

Question: I am new to jaspersoft reports .Is it possible to have dynamic tree view in the input control dialog box
Comment: Do you talk about JasperServer or about the custom web application?
Comment: Alex ,I am talking about JasperServer
Comment: You can customize this application. Information: http://jasperforge.org/espdocs/espbrowse.php?id=86&type=folder&group_id=112&parent=86 & http://www.jaspersoft.com/download/customizing-and-rebranding-jaspersoft-user-interface
Comment: thanks for replying Alex link u posted are related to customizing the user interface but i want to add a new input control i.e treemap
Answer: JasperReports Server has static lists and dynamic lists (populated by queries). It doesn't have a tree view for input controls.
If you are asking, "Is it possible to write code to implement a tree view input control?", then the answer is, "Yes. Anything is possible with enough customization." But it won't be a trivial customization.
Answer: Tree view is not out of the box.  But it can be done if you are willing to code again the JasperDesign.  Actually, I am writting the code to generate dynamic tree view with columns on the right.


Using JQuery Validate remote method with array

Question: I need to register more users in the same screen, so I use a form like this:
Username*<input name="username[]" />
Password*<input name="password[]" />

Username*<input name="username[]" />
Password*<input name="password[]" />

...
and using jquery.validate to control if the user is still in use:
rules : {
'username[]' : {
    required : true,
    remote: {
            url: "control_user.php"

          }
},

BUT I don't know what to do in control_user.php to return the right 'true' or 'false' for every 'username' in the array.
Any Help??
Thanks
Answer: there are some really useful demos in the validation project files - you can download them as a zip here
you can just return the strings 'true' or 'false' from your php script.  I think your 'control_user.php' will look a lot like this example taken from the 'marketo' demo
<?php
$request = trim(strtolower($_REQUEST['email']));
$emails = array('firstname.lastname@example.com', 'email@example.com', 'firstname.lastname@example.com');
$valid = 'true';
foreach($emails as $email) {
    if( strtolower($email) == $request )
        $valid = 'false';
}
echo $valid;
?>


Is "Little Red Corvette" in a church mode?

Question: I'm trying to make sense of the chord progression in Litte Red Corvette (Gb - Ab - Bb min - Gb).
The Ab maj chord is not in the key of Gb maj, giving the song a somewhat "exotic" sound to it. What is that? What key/mode would that be in?
Answer: The song is actually in Db/C#. So the Gb chord is a IV. The sequence is IV, V I sometimes, and IV, V vi others. Putting it firmly into a major key. To help, try to establish which of the chords the song could finish on. It won't be the Gb, so that can't be the key, or 'I'.
Comment: the song seems to resolve to Gb in the verses, giving it a lydian sound. The chorus resovles to Db, which is a shift in modality.