Programs & Examples On #Inheritance

Inheritance is the system in object oriented programming that allows objects to support operations defined by anterior types without having to provide their own definition. It is the major vector for polymorphism in object-oriented programming.

Calling the base constructor in C#

public class MyException : Exception
{
    public MyException() { }
    public MyException(string msg) : base(msg) { }
    public MyException(string msg, Exception inner) : base(msg, inner) { }
}

How to define custom exception class in Java, the easiest way?

Reason for this is explained in the Inheritance article of the Java Platform which says:

"A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass."

TypeError: module.__init__() takes at most 2 arguments (3 given)

Even after @Mickey Perlstein's answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here's what was going on in my situation.

  • responses is a module
  • Response is a base class within the responses module
  • GeoJsonResponse is a new class derived from Response

Initial GeoJsonResponse class:

from pyexample.responses import Response

class GeoJsonResponse(Response):

    def __init__(self, geo_json_data):

Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:

from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):

E TypeError: module() takes at most 2 arguments (3 given)

=================================== ERRORS ====================================

___________________ ERROR collecting tests/test_geojson.py ____________________

test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)

class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)

ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response

C:\Python37\lib\site-packages\aenum__init__.py:163

(no name 'PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response' in any of [])

The errors were doing their best to point me in the right direction, and @Mickey Perlstein's answer was dead on, it just took me a minute to put it all together in my own context:

I was importing the module:

from pyexample.responses import Response

when I should have been importing the class:

from pyexample.responses.Response import Response

Hope this helps someone. (In my defense, it's still pretty early.)

List<Map<String, String>> vs List<? extends Map<String, String>>

The difference is that, for example, a

List<HashMap<String,String>>

is a

List<? extends Map<String,String>>

but not a

List<Map<String,String>>

So:

void withWilds( List<? extends Map<String,String>> foo ){}
void noWilds( List<Map<String,String>> foo ){}

void main( String[] args ){
    List<HashMap<String,String>> myMap;

    withWilds( myMap ); // Works
    noWilds( myMap ); // Compiler error
}

You would think a List of HashMaps should be a List of Maps, but there's a good reason why it isn't:

Suppose you could do:

List<HashMap<String,String>> hashMaps = new ArrayList<HashMap<String,String>>();

List<Map<String,String>> maps = hashMaps; // Won't compile,
                                          // but imagine that it could

Map<String,String> aMap = Collections.singletonMap("foo","bar"); // Not a HashMap

maps.add( aMap ); // Perfectly legal (adding a Map to a List of Maps)

// But maps and hashMaps are the same object, so this should be the same as

hashMaps.add( aMap ); // Should be illegal (aMap is not a HashMap)

So this is why a List of HashMaps shouldn't be a List of Maps.

Can an interface extend multiple interfaces in Java?

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.

for example, take a look here: http://www.tutorialspoint.com/java/java_interfaces.htm

Maven project version inheritance - do I have to specify the parent version?

The easiest way to update versions IMO:

$ mvn versions:set -DgenerateBackupPoms=false

(do that in your root/parent pom folder).

Your POMs are parsed and you're asked which version to set.

Including another class in SCSS

Another option could be using an Attribute Selector:

[class^="your-class-name"]{
  //your style here
}

Whereas every class starting with "your-class-name" uses this style.

So in your case, you could do it like so:

[class^="class"]{
  display: inline-block;
  //some other properties
  &:hover{
   color: darken(#FFFFFF, 10%);
 }  
}

.class-b{
  //specifically for class b
  width: 100px;
  &:hover{
     color: darken(#FFFFFF, 20%);
  }
}

More about Attribute Selectors on w3Schools

Python extending with - using super() Python 3 vs Python 2

In short, they are equivalent. Let's have a history view:

(1) at first, the function looks like this.

    class MySubClass(MySuperClass):
        def __init__(self):
            MySuperClass.__init__(self)

(2) to make code more abstract (and more portable). A common method to get Super-Class is invented like:

    super(<class>, <instance>)

And init function can be:

    class MySubClassBetter(MySuperClass):
        def __init__(self):
            super(MySubClassBetter, self).__init__()

However requiring an explicit passing of both the class and instance break the DRY (Don't Repeat Yourself) rule a bit.

(3) in V3. It is more smart,

    super()

is enough in most case. You can refer to http://www.python.org/dev/peps/pep-3135/

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

The answers given here didn't fully convince me. So instead, I make another example.

public void passOn(Consumer<Animal> consumer, Supplier<Animal> supplier) {
    consumer.accept(supplier.get());
}

sounds fine, doesn't it? But you can only pass Consumers and Suppliers for Animals. If you have a Mammal consumer, but a Duck supplier, they should not fit although both are animals. In order to disallow this, additional restrictions have been added.

Instead of the above, we have to define relationships between the types we use.

E. g.,

public <A extends Animal> void passOn(Consumer<A> consumer, Supplier<? extends A> supplier) {
    consumer.accept(supplier.get());
}

makes sure that we can only use a supplier which provides us the right type of object for the consumer.

OTOH, we could as well do

public <A extends Animal> void passOn(Consumer<? super A> consumer, Supplier<A> supplier) {
    consumer.accept(supplier.get());
}

where we go the other way: we define the type of the Supplier and restrict that it can be put into the Consumer.

We even can do

public <A extends Animal> void passOn(Consumer<? super A> consumer, Supplier<? extends A> supplier) {
    consumer.accept(supplier.get());
}

where, having the intuitive relations Life -> Animal -> Mammal -> Dog, Cat etc., we could even put a Mammal into a Life consumer, but not a String into a Life consumer.

How can I initialize base class member variables in derived class constructor?

While this is usefull in rare cases (if that was not the case, the language would've allowed it directly), take a look at the Base from Member idiom. It's not a code free solution, you'd have to add an extra layer of inheritance, but it gets the job done. To avoid boilerplate code you could use boost's implementation

JSP tricks to make templating easier?

Use tiles. It saved my life.

But if you can't, there's the include tag, making it similar to php.

The body tag might not actually do what you need it to, unless you have super simple content. The body tag is used to define the body of a specified element. Take a look at this example:

<jsp:element name="${content.headerName}"   
   xmlns:jsp="http://java.sun.com/JSP/Page">    
   <jsp:attribute name="lang">${content.lang}</jsp:attribute>   
   <jsp:body>${content.body}</jsp:body> 
</jsp:element>

You specify the element name, any attributes that element might have ("lang" in this case), and then the text that goes in it--the body. So if

  • content.headerName = h1,
  • content.lang = fr, and
  • content.body = Heading in French

Then the output would be

<h1 lang="fr">Heading in French</h1>

What are the differences between type() and isinstance()?

Differences between isinstance() and type() in Python?

Type-checking with

isinstance(obj, Base)

allows for instances of subclasses and multiple possible bases:

isinstance(obj, (Base1, Base2))

whereas type-checking with

type(obj) is Base

only supports the type referenced.


As a sidenote, is is likely more appropriate than

type(obj) == Base

because classes are singletons.

Avoid type-checking - use Polymorphism (duck-typing)

In Python, usually you want to allow any type for your arguments, treat it as expected, and if the object doesn't behave as expected, it will raise an appropriate error. This is known as polymorphism, also known as duck-typing.

def function_of_duck(duck):
    duck.quack()
    duck.swim()

If the code above works, we can presume our argument is a duck. Thus we can pass in other things are actual sub-types of duck:

function_of_duck(mallard)

or that work like a duck:

function_of_duck(object_that_quacks_and_swims_like_a_duck)

and our code still works.

However, there are some cases where it is desirable to explicitly type-check. Perhaps you have sensible things to do with different object types. For example, the Pandas Dataframe object can be constructed from dicts or records. In such a case, your code needs to know what type of argument it is getting so that it can properly handle it.

So, to answer the question:

Differences between isinstance() and type() in Python?

Allow me to demonstrate the difference:

type

Say you need to ensure a certain behavior if your function gets a certain kind of argument (a common use-case for constructors). If you check for type like this:

def foo(data):
    '''accepts a dict to construct something, string support in future'''
    if type(data) is not dict:
        # we're only going to test for dicts for now
        raise ValueError('only dicts are supported for now')

If we try to pass in a dict that is a subclass of dict (as we should be able to, if we're expecting our code to follow the principle of Liskov Substitution, that subtypes can be substituted for types) our code breaks!:

from collections import OrderedDict

foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))

raises an error!

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in foo
ValueError: argument must be a dict

isinstance

But if we use isinstance, we can support Liskov Substitution!:

def foo(a_dict):
    if not isinstance(a_dict, dict):
        raise ValueError('argument must be a dict')
    return a_dict

foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))

returns OrderedDict([('foo', 'bar'), ('fizz', 'buzz')])

Abstract Base Classes

In fact, we can do even better. collections provides Abstract Base Classes that enforce minimal protocols for various types. In our case, if we only expect the Mapping protocol, we can do the following, and our code becomes even more flexible:

from collections import Mapping

def foo(a_dict):
    if not isinstance(a_dict, Mapping):
        raise ValueError('argument must be a dict')
    return a_dict

Response to comment:

It should be noted that type can be used to check against multiple classes using type(obj) in (A, B, C)

Yes, you can test for equality of types, but instead of the above, use the multiple bases for control flow, unless you are specifically only allowing those types:

isinstance(obj, (A, B, C))

The difference, again, is that isinstance supports subclasses that can be substituted for the parent without otherwise breaking the program, a property known as Liskov substitution.

Even better, though, invert your dependencies and don't check for specific types at all.

Conclusion

So since we want to support substituting subclasses, in most cases, we want to avoid type-checking with type and prefer type-checking with isinstance - unless you really need to know the precise class of an instance.

How to call a parent class function from derived class function?

struct a{
 int x;

 struct son{
  a* _parent;
  void test(){
   _parent->x=1; //success
  }
 }_son;

 }_a;

int main(){
 _a._son._parent=&_a;
 _a._son.test();
}

Reference example.

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

When to use an interface instead of an abstract class and vice versa?

This can be a very difficult call to make...

One pointer I can give: An object can implement many interfaces, whilst an object can only inherit one base class( in a modern OO language like c#, I know C++ has multiple inheritance - but isn't that frowned upon?)

Is there a way to override class variables in Java?

Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.

The value will get reflected when using in the blocks of parent class

if the variable is static then change the value during initialization itself with static block,

class Son extends Dad {
    static { 
       me = "son"; 
    }
}

or else change in constructor.

You can also change the value later in any blocks. It will get reflected in super class

Overloading and overriding

I want to share an example which made a lot sense to me when I was learning:

This is just an example which does not include the virtual method or the base class. Just to give a hint regarding the main idea.

Let's say there is a Vehicle washing machine and it has a function called as "Wash" and accepts Car as a type.

Gets the Car input and washes the Car.

public void Wash(Car anyCar){
       //wash the car
}

Let's overload Wash() function

Overloading:

public void Wash(Truck anyTruck){
   //wash the Truck  
}

Wash function was only washing a Car before, but now its overloaded to wash a Truck as well.

  • If the provided input object is a Car, it will execute Wash(Car anyCar)
  • If the provided input object is a Truck, then it will execute Wash(Truck anyTruck)

Let's override Wash() function

Overriding:

public override void Wash(Car anyCar){
   //check if the car has already cleaned
   if(anyCar.Clean){ 
       //wax the car
   }
   else{
       //wash the car
       //dry the car
       //wax the car
   }     
}

Wash function now has a condition to check if the Car is already clean and not need to be washed again.

  • If the Car is clean, then just wax it.

  • If not clean, then first wash the car, then dry it and then wax it

.

So the functionality has been overridden by adding a new functionality or do something totally different.

Struct inheritance in C++

Other than what Alex and Evan have already stated, I would like to add that a C++ struct is not like a C struct.

In C++, a struct can have methods, inheritance, etc. just like a C++ class.

How to access Winform textbox control from another class?

If your other class inherits Form1 and if your textBox1 is declared public, then you can access that text box from your other class by simply calling:

otherClassInstance.textBox1.Text = "hello world";

Why an interface can not implement another interface?

Conceptually there are the two "domains" classes and interfaces. Inside these domains you are always extending, only a class implements an interface, which is kind of "crossing the border". So basically "extends" for interfaces mirrors the behavior for classes. At least I think this is the logic behind. It seems than not everybody agrees with this kind of logic (I find it a little bit contrived myself), and in fact there is no technical reason to have two different keywords at all.

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

What does 'super' do in Python?

Doesn't all of this assume that the base class is a new-style class?

class A:
    def __init__(self):
        print("A.__init__()")

class B(A):
    def __init__(self):
        print("B.__init__()")
        super(B, self).__init__()

Will not work in Python 2. class A must be new-style, i.e: class A(object)

How should I have explained the difference between an Interface and an Abstract class?

When I am trying to share behavior between 2 closely related classes, I create an abstract class that holds the common behavior and serves as a parent to both classes.

When I am trying to define a Type, a list of methods that a user of my object can reliably call upon, then I create an interface.

For example, I would never create an abstract class with 1 concrete subclass because abstract classes are about sharing behavior. But I might very well create an interface with only one implementation. The user of my code won't know that there is only one implementation. Indeed, in a future release there may be several implementations, all of which are subclasses of some new abstract class that didn't even exist when I created the interface.

That might have seemed a bit too bookish too (though I have never seen it put that way anywhere that I recall). If the interviewer (or the OP) really wanted more of my personal experience on that, I would have been ready with anecdotes of an interface has evolved out of necessity and visa versa.

One more thing. Java 8 now allows you to put default code into an interface, further blurring the line between interfaces and abstract classes. But from what I have seen, that feature is overused even by the makers of the Java core libraries. That feature was added, and rightly so, to make it possible to extend an interface without creating binary incompatibility. But if you are making a brand new Type by defining an interface, then the interface should be JUST an interface. If you want to also provide common code, then by all means make a helper class (abstract or concrete). Don't be cluttering your interface from the start with functionality that you may want to change.

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

Difference between private, public, and protected inheritance

Accessors    | Base Class | Derived Class | World
—————————————+————————————+———————————————+———————
public       |      y     |       y       |   y
—————————————+————————————+———————————————+———————
protected    |      y     |       y       |   n
—————————————+————————————+———————————————+———————
private      |            |               |    
  or         |      y     |       n       |   n
no accessor  |            |               |

y: accessible
n: not accessible

Based on this example for java... I think a little table worth a thousand words :)

Inheriting from a template class in c++

Rectangle will have to be a template, otherwise it is just one type. It cannot be a non-template whilst its base magically is. (Its base may be a template instantiation, though you seem to want to maintain the base's functionality as a template.)

How to call Base Class's __init__ method from the child class?

If you are using Python 3, it is recommended to simply call super() without any argument:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super().__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Do not call super with class as it may lead to infinite recursion exceptions as per this answer.

Java error: Implicit super constructor is undefined for default constructor

It is possible but not the way you have it.

You have to add a no-args constructor to the base class and that's it!

public abstract class A {
    private String name;
    public A(){
        this.name = getName();
    }
    public abstract String getName();


    public String toString(){
        return "simple class name: " + this.getClass().getSimpleName() + " name:\"" + this.name + "\"";
    }
}
class B extends A {
    public String getName(){
        return "my name is B";
    }
    public static void main( String [] args ) {
        System.out.println( new C() );
    }
}
class C extends A {
    public String getName() {
        return "Zee";
    }
}

When you don't add a constructor ( any ) to a class the compiler add the default no arg contructor for you.

When the defualt no arg calls to super(); and since you don't have it in the super class you get that error message.

That's about the question it self.

Now, expanding the answer:

Are you aware that creating a subclass ( behavior ) to specify different a different value ( data ) makes no sense??!!! I hope you do.

If the only thing that is changes is the "name" then a single class parametrized is enough!

So you don't need this:

MyClass a = new A("A");
MyClass b = new B("B");
MyClass c = new C("C");
MyClass d = new D("D");

or

MyClass a = new A(); // internally setting "A" "B", "C" etc.
MyClass b = new B();
MyClass c = new C();
MyClass d = new D();

When you can write this:

MyClass a = new MyClass("A");
MyClass b = new MyClass("B");
MyClass c = new MyClass("C");
MyClass d = new MyClass("D");

If I were to change the method signature of the BaseClass constructor, I would have to change all the subclasses.

Well that's why inheritance is the artifact that creates HIGH coupling, which is undesirable in OO systems. It should be avoided and perhaps replaced with composition.

Think if you really really need them as subclass. That's why you see very often interfaces used insted:

 public interface NameAware {
     public String getName();
 }



 class A implements NameAware ...
 class B implements NameAware ...
 class C ... etc. 

Here B and C could have inherited from A which would have created a very HIGH coupling among them, by using interfaces the coupling is reduced, if A decides it will no longer be "NameAware" the other classes won't broke.

Of course, if you want to reuse behavior this won't work.

Why do we assign a parent reference to the child object in Java?

I know this is a very old thread but I came across the same doubt once.

So the concept of Parent parent = new Child(); has something to do with early and late binding in java.

The binding of private, static and final methods happen at the compile as they cannot be overridden and the normal method calls and overloaded methods are example of early binding.

Consider the example:

class Vehicle
{
    int value = 100;
    void start() {
        System.out.println("Vehicle Started");
    }

    static void stop() {
        System.out.println("Vehicle Stopped");
    }
}

class Car extends Vehicle {

    int value = 1000;

    @Override
    void start() {
        System.out.println("Car Started");
    }

    static void stop() {
        System.out.println("Car Stopped");
    }

    public static void main(String args[]) {

        // Car extends Vehicle
        Vehicle vehicle = new Car();
        System.out.println(vehicle.value);
        vehicle.start();
        vehicle.stop();
    }
}

Output: 100

Car Started

Vehicle Stopped

This is happening because stop() is a static method and cannot be overridden. So binding of stop() happens at compile time and start() is non-static is being overridden in child class. So, the information about type of object is available at the run time only(late binding) and hence the start() method of Car class is called.

Also in this code the vehicle.value gives us 100 as the output because variable initialization doesn't come under late binding. Method overriding is one of the ways in which java supports run time polymorphism.

  • When an overridden method is called through a superclass reference, Java determines which version(superclass/subclasses) of that method is to be executed based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time.
  • At run-time, it depends on the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed

I hope this answers where Parent parent = new Child(); is important and also why you weren't able to access the child class variable using the above reference.

Are static methods inherited in Java?

You can experience the difference in following code, which is slightly modification over your code.

class A {
    public static void display() {
        System.out.println("Inside static method of superclass");
    }
}

class B extends A {
    public void show() {
        display();
    }

    public static void display() {
        System.out.println("Inside static method of this class");
    }
}

public class Test {
    public static void main(String[] args) {
        B b = new B();
        // prints: Inside static method of this class
        b.display();

        A a = new B();
        // prints: Inside static method of superclass
        a.display();
    }
}

This is due to static methods are class methods.

A.display() and B.display() will call method of their respective classes.

How can you represent inheritance in a database?

The 3rd option is to create a "Policy" table, then a "SectionsMain" table that stores all of the fields that are in common across the types of sections. Then create other tables for each type of section that only contain the fields that are not in common.

Deciding which is best depends mostly on how many fields you have and how you want to write your SQL. They would all work. If you have just a few fields then I would probably go with #1. With "lots" of fields I would lean towards #2 or #3.

How do you declare an interface in C++?

While it's true that virtual is the de-facto standard to define an interface, let's not forget about the classic C-like pattern, which comes with a constructor in C++:

struct IButton
{
    void (*click)(); // might be std::function(void()) if you prefer

    IButton( void (*click_)() )
    : click(click_)
    {
    }
};

// call as:
// (button.*click)();

This has the advantage that you can re-bind events runtime without having to construct your class again (as C++ does not have a syntax for changing polymorphic types, this is a workaround for chameleon classes).

Tips:

  • You might inherit from this as a base class (both virtual and non-virtual are permitted) and fill click in your descendant's constructor.
  • You might have the function pointer as a protected member and have a public reference and/or getter.
  • As mentioned above, this allows you to switch the implementation in runtime. Thus it's a way to manage state as well. Depending on the number of ifs vs. state changes in your code, this might be faster than switch()es or ifs (turnaround is expected around 3-4 ifs, but always measure first.
  • If you choose std::function<> over function pointers, you might be able to manage all your object data within IBase. From this point, you can have value schematics for IBase (e.g., std::vector<IBase> will work). Note that this might be slower depending on your compiler and STL code; also that current implementations of std::function<> tend to have an overhead when compared to function pointers or even virtual functions (this might change in the future).

Using C++ base class constructors?

Here is a good discussion about superclass constructor calling rules. You always want the base class constructor to be called before the derived class constructor in order to form an object properly. Which is why this form is used

  B( int v) : A( v )
  {
  }

Inheriting constructors

How about using a template function to bind all constructors?

template <class... T> Derived(T... t) : Base(t...) {}

In Java, how do I call a base class's method from the overriding method in a derived class?

Answer is as follows:

super.Mymethod();
super();                // calls base class Superclass constructor.
super(parameter list);          // calls base class parameterized constructor.
super.method();         // calls base class method.

Why not inherit from List<T>?

I just wanted to add that Bertrand Meyer, the inventor of Eiffel and design by contract, would have Team inherit from List<Player> without so much as batting an eyelid.

In his book, Object-Oriented Software Construction, he discusses the implementation of a GUI system where rectangular windows can have child windows. He simply has Window inherit from both Rectangle and Tree<Window> to reuse the implementation.

However, C# is not Eiffel. The latter supports multiple inheritance and renaming of features. In C#, when you subclass, you inherit both the interface and the implemenation. You can override the implementation, but the calling conventions are copied directly from the superclass. In Eiffel, however, you can modify the names of the public methods, so you can rename Add and Remove to Hire and Fire in your Team. If an instance of Team is upcast back to List<Player>, the caller will use Add and Remove to modify it, but your virtual methods Hire and Fire will be called.

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

* This is a simple answer since I'm a beginner in Java *

Consider there are three classes X,Y and Z.

So we are inheriting like X extends Y, Z And both Y and Z is having a method alphabet() with same return type and arguments. This method alphabet() in Y says to display first alphabet and method alphabet in Z says display last alphabet. So here comes ambiguity when alphabet() is called by X. Whether it says to display first or last alphabet??? So java is not supporting multiple inheritance. In case of Interfaces, consider Y and Z as interfaces. So both will contain the declaration of method alphabet() but not the definition. It won't tell whether to display first alphabet or last alphabet or anything but just will declare a method alphabet(). So there is no reason to raise the ambiguity. We can define the method with anything we want inside class X.

So in a word, in Interfaces definition is done after implementation so no confusion.

Convert List<DerivedClass> to List<BaseClass>

If you use IEnumerable instead, it will work (at least in C# 4.0, I have not tried previous versions). This is just a cast, of course, it will still be a list.

Instead of -

List<A> listOfA = new List<C>(); // compiler Error

In the original code of the question, use -

IEnumerable<A> listOfA = new List<C>(); // compiler error - no more! :)

Calling the base class constructor from the derived class constructor

but I can't initialize my derived class, I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ?? so I'm thinking maybe in the PetStore default constructor I can call Farm()... so any Idea ???

Don't panic.

Farm constructor will be called in the constructor of PetStore, automatically.

See the base class inheritance calling rules: What are the rules for calling the superclass constructor?

How to "perfectly" override a dict?

You can write an object that behaves like a dict quite easily with ABCs (Abstract Base Classes) from the collections.abc module. It even tells you if you missed a method, so below is the minimal version that shuts the ABC up.

from collections.abc import MutableMapping


class TransformedDict(MutableMapping):
    """A dictionary that applies an arbitrary key-altering
       function before accessing the keys"""

    def __init__(self, *args, **kwargs):
        self.store = dict()
        self.update(dict(*args, **kwargs))  # use the free update to set keys

    def __getitem__(self, key):
        return self.store[self._keytransform(key)]

    def __setitem__(self, key, value):
        self.store[self._keytransform(key)] = value

    def __delitem__(self, key):
        del self.store[self._keytransform(key)]

    def __iter__(self):
        return iter(self.store)
    
    def __len__(self):
        return len(self.store)

    def _keytransform(self, key):
        return key

You get a few free methods from the ABC:

class MyTransformedDict(TransformedDict):

    def _keytransform(self, key):
        return key.lower()


s = MyTransformedDict([('Test', 'test')])

assert s.get('TEST') is s['test']   # free get
assert 'TeSt' in s                  # free __contains__
                                    # free setdefault, __eq__, and so on

import pickle
# works too since we just use a normal dict
assert pickle.loads(pickle.dumps(s)) == s

I wouldn't subclass dict (or other builtins) directly. It often makes no sense, because what you actually want to do is implement the interface of a dict. And that is exactly what ABCs are for.

C++ cast to derived class

First of all - prerequisite for downcast is that object you are casting is of the type you are casting to. Casting with dynamic_cast will check this condition in runtime (provided that casted object has some virtual functions) and throw bad_cast or return NULL pointer on failure. Compile-time casts will not check anything and will just lead tu undefined behaviour if this prerequisite does not hold.
Now analyzing your code:

DerivedType m_derivedType = m_baseType;

Here there is no casting. You are creating a new object of type DerivedType and try to initialize it with value of m_baseType variable.

Next line is not much better:

DerivedType m_derivedType = (DerivedType)m_baseType;

Here you are creating a temporary of DerivedType type initialized with m_baseType value.

The last line

DerivedType * m_derivedType = (DerivedType*) & m_baseType;

should compile provided that BaseType is a direct or indirect public base class of DerivedType. It has two flaws anyway:

  1. You use deprecated C-style cast. The proper way for such casts is
    static_cast<DerivedType *>(&m_baseType)
  2. The actual type of casted object is not of DerivedType (as it was defined as BaseType m_baseType; so any use of m_derivedType pointer will result in undefined behaviour.

In C#, can a class inherit from another class and an interface?

Unrelated to the question (Mehrdad's answer should get you going), and I hope this isn't taken as nitpicky: classes don't inherit interfaces, they implement them.

.NET does not support multiple-inheritance, so keeping the terms straight can help in communication. A class can inherit from one superclass and can implement as many interfaces as it wishes.


In response to Eric's comment... I had a discussion with another developer about whether or not interfaces "inherit", "implement", "require", or "bring along" interfaces with a declaration like:

public interface ITwo : IOne

The technical answer is that ITwo does inherit IOne for a few reasons:

  • Interfaces never have an implementation, so arguing that ITwo implements IOne is flat wrong
  • ITwo inherits IOne methods, if MethodOne() exists on IOne then it is also accesible from ITwo. i.e: ((ITwo)someObject).MethodOne()) is valid, even though ITwo does not explicitly contain a definition for MethodOne()
  • ...because the runtime says so! typeof(IOne).IsAssignableFrom(typeof(ITwo)) returns true

We finally agreed that interfaces support true/full inheritance. The missing inheritance features (such as overrides, abstract/virtual accessors, etc) are missing from interfaces, not from interface inheritance. It still doesn't make the concept simple or clear, but it helps understand what's really going on under the hood in Eric's world :-)

CSS - make div's inherit a height

The negative margin trick:

http://pastehtml.com/view/1dujbt3.html

Not elegant, I suppose, but it works in some cases.

Understanding Python super() with __init__() methods

It's been noted that in Python 3.0+ you can use

super().__init__()

to make your call, which is concise and does not require you to reference the parent OR class names explicitly, which can be handy. I just want to add that for Python 2.7 or under, some people implement a name-insensitive behaviour by writing self.__class__ instead of the class name, i.e.

super(self.__class__, self).__init__()  # DON'T DO THIS!

HOWEVER, this breaks calls to super for any classes that inherit from your class, where self.__class__ could return a child class. For example:

class Polygon(object):
    def __init__(self, id):
        self.id = id

class Rectangle(Polygon):
    def __init__(self, id, width, height):
        super(self.__class__, self).__init__(id)
        self.shape = (width, height)

class Square(Rectangle):
    pass

Here I have a class Square, which is a sub-class of Rectangle. Say I don't want to write a separate constructor for Square because the constructor for Rectangle is good enough, but for whatever reason I want to implement a Square so I can reimplement some other method.

When I create a Square using mSquare = Square('a', 10,10), Python calls the constructor for Rectangle because I haven't given Square its own constructor. However, in the constructor for Rectangle, the call super(self.__class__,self) is going to return the superclass of mSquare, so it calls the constructor for Rectangle again. This is how the infinite loop happens, as was mentioned by @S_C. In this case, when I run super(...).__init__() I am calling the constructor for Rectangle but since I give it no arguments, I will get an error.

JavaScript OOP in NodeJS: how?

I suggest to use the inherits helper that comes with the standard util module: http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor

There is an example of how to use it on the linked page.

Abstract methods in Python

Before abc was introduced you would see this frequently.

class Base(object):
    def go(self):
        raise NotImplementedError("Please Implement this method")


class Specialized(Base):
    def go(self):
        print "Consider me implemented"

Get all inherited classes of an abstract class

Assuming they are all defined in the same assembly, you can do:

IEnumerable<AbstractDataExport> exporters = typeof(AbstractDataExport)
    .Assembly.GetTypes()
    .Where(t => t.IsSubclassOf(typeof(AbstractDataExport)) && !t.IsAbstract)
    .Select(t => (AbstractDataExport)Activator.CreateInstance(t));

Java Constructor Inheritance

When you inherit from Super this is what in reality happens:

public class Son extends Super{

  // If you dont declare a constructor of any type, adefault one will appear.
  public Son(){
    // If you dont call any other constructor in the first line a call to super() will be placed instead.
    super();
  }

}

So, that is the reason, because you have to call your unique constructor, since"Super" doesn't have a default one.

Now, trying to guess why Java doesn't support constructor inheritance, probably because a constructor only makes sense if it's talking about concrete instances, and you shouldn't be able to create an instance of something when you don't know how it's defined (by polymorphism).

Is it possible to make abstract classes in Python?

also this works and is simple:

class A_abstract(object):

    def __init__(self):
        # quite simple, old-school way.
        if self.__class__.__name__ == "A_abstract": 
            raise NotImplementedError("You can't instantiate this abstract class. Derive it, please.")

class B(A_abstract):

        pass

b = B()

# here an exception is raised:
a = A_abstract()

How do I get a PHP class constructor to call its parent's parent's constructor?

I ended up coming up with an alternative solution that solved the problem.

  • I created an intermediate class that extended Grandpa.
  • Then both Papa and Kiddo extended that class.
  • Kiddo required some intermediate functionality of Papa but didn't like it's constructor so the class has that additional functionality and both extend it.

I've upvoted the other two answers that provided valid yet ugly solutions for an uglier question:)

Defining an abstract class without any abstract methods

Yes we can have an abstract class without Abstract Methods as both are independent concepts. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass.

What is the main difference between Inheritance and Polymorphism?

Inheritance is a concept related to code reuse. For example if I have a parent class say Animal and it contains certain attributes and methods (for this example say makeNoise() and sleep()) and I create two child classes called Dog and Cat. Since both dogs and cats go to sleep in the same fashion( I would assume) there is no need to add more functionality to the sleep() method in the Dog and Cat subclasses provided by the parent class Animal. However, a Dog barks and a Cat meows so although the Animal class might have a method for making a noise, a dog and a cat make different noises relative to each other and other animals. Thus, there is a need to redefine that behavior for their specific types. Thus the definition of polymorphism. Hope this helps.

Inheritance and init method in Python

When you override the init you have also to call the init of the parent class

super(Num2, self).__init__(num)

Understanding Python super() with __init__() methods

Convert base class to derived class

That's not possible. but you can use an Object Mapper like AutoMapper

Example:

class A
{
    public int IntProp { get; set; }
}
class B
{
    public int IntProp { get; set; }
    public string StrProp { get; set; }
}

In global.asax or application startup:

AutoMapper.Mapper.CreateMap<A, B>();

Usage:

var b = AutoMapper.Mapper.Map<B>(a);

It's easily configurable via a fluent API.

Difference between Inheritance and Composition

In Simple Word Aggregation means Has A Relationship ..

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Why Use Aggregation

Code Reusability

When Use Aggregation

Code reuse is also best achieved by aggregation when there is no is a Relation ship

Inheritance

Inheritance is a Parent Child Relationship Inheritance Means Is A RelationShip

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Using inheritance in Java 1 Code Reusability. 2 Add Extra Feature in Child Class as well as Method Overriding (so runtime polymorphism can be achieved).

how to inherit Constructor from super class to sub class

Constructors are not inherited, you must create a new, identically prototyped constructor in the subclass that maps to its matching constructor in the superclass.

Here is an example of how this works:

class Foo {
    Foo(String str) { }
}

class Bar extends Foo {
    Bar(String str) {
        // Here I am explicitly calling the superclass 
        // constructor - since constructors are not inherited
        // you must chain them like this.
        super(str);
    }
}

Java: Calling a super method which calls an overridden method

I don't believe you can do it directly. One workaround would be to have a private internal implementation of method2 in the superclass, and call that. For example:

public class SuperClass
{
    public void method1()
    {
        System.out.println("superclass method1");
        this.internalMethod2();
    }

    public void method2()
    {
        this.internalMethod2(); 
    }
    private void internalMethod2()
    {
        System.out.println("superclass method2");
    }

}

Interfaces vs. abstract classes

The advantages of an abstract class are:

  • Ability to specify default implementations of methods
  • Added invariant checking to functions
  • Have slightly more control in how the "interface" methods are called
  • Ability to provide behavior related or unrelated to the interface for "free"

Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.

C++ calling base class constructors

The default class constructor is called unless you explicitly call another constructor in the derived class. the language specifies this.

Rectangle(int h,int w):
   Shape(h,w)
  {...}

Will call the other base class constructor.

Why can't I inherit static classes?

What you want to achieve by using class hierarchy can be achieved merely through namespacing. So languages that support namespapces ( like C#) will have no use of implementing class hierarchy of static classes. Since you can not instantiate any of the classes, all you need is a hierarchical organization of class definitions which you can obtain through the use of namespaces

C++ inheritance - inaccessible base?

You have to do this:

class Bar : public Foo
{
    // ...
}

The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.

C# Error: Parent does not contain a constructor that takes 0 arguments

You need to change the constructor of the child class to this:

public child(int i) : base(i)
{
    Console.WriteLine("child");
}

The part : base(i) means that the constructor of the base class with one int parameter should be used. If this is missing, you are implicitly telling the compiler to use the default constructor without parameters. Because no such constructor exists in the base class it is giving you this error.

What is object slicing?

1. THE DEFINITION OF SLICING PROBLEM

If D is a derived class of the base class B, then you can assign an object of type Derived to a variable (or parameter) of type Base.

EXAMPLE

class Pet
{
 public:
    string name;
};
class Dog : public Pet
{
public:
    string breed;
};

int main()
{   
    Dog dog;
    Pet pet;

    dog.name = "Tommy";
    dog.breed = "Kangal Dog";
    pet = dog;
    cout << pet.breed; //ERROR

Although the above assignment is allowed, the value that is assigned to the variable pet loses its breed field. This is called the slicing problem.

2. HOW TO FIX THE SLICING PROBLEM

To defeat the problem, we use pointers to dynamic variables.

EXAMPLE

Pet *ptrP;
Dog *ptrD;
ptrD = new Dog;         
ptrD->name = "Tommy";
ptrD->breed = "Kangal Dog";
ptrP = ptrD;
cout << ((Dog *)ptrP)->breed; 

In this case, none of the data members or member functions of the dynamic variable being pointed to by ptrD (descendant class object) will be lost. In addition, if you need to use functions, the function must be a virtual function.

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

What's wrong with overridable method calls in constructors?

Here is an example that reveals the logical problems that can occur when calling an overridable method in the super constructor.

class A {

    protected int minWeeklySalary;
    protected int maxWeeklySalary;

    protected static final int MIN = 1000;
    protected static final int MAX = 2000;

    public A() {
        setSalaryRange();
    }

    protected void setSalaryRange() {
        throw new RuntimeException("not implemented");
    }

    public void pr() {
        System.out.println("minWeeklySalary: " + minWeeklySalary);
        System.out.println("maxWeeklySalary: " + maxWeeklySalary);
    }
}

class B extends A {

    private int factor = 1;

    public B(int _factor) {
        this.factor = _factor;
    }

    @Override
    protected void setSalaryRange() {
        this.minWeeklySalary = MIN * this.factor;
        this.maxWeeklySalary = MAX * this.factor;
    }
}

public static void main(String[] args) {
    B b = new B(2);
    b.pr();
}

The result would actually be:

minWeeklySalary: 0

maxWeeklySalary: 0

This is because the constructor of class B first calls the constructor of class A, where the overridable method inside B gets executed. But inside the method we are using the instance variable factor which has not yet been initialized (because the constructor of A has not yet finished), thus factor is 0 and not 1 and definitely not 2 (the thing that the programmer might think it will be). Imagine how hard would be to track an error if the calculation logic was ten times more twisted.

I hope that would help someone.

At runtime, find all classes in a Java application that extend a base class

One way is to make the classes use a static initializers... I don't think these are inherited (it won't work if they are):

public class Dog extends Animal{

static
{
   Animal a = new Dog();
   //add a to the List
}

It requires you to add this code to all of the classes involved. But it avoids having a big ugly loop somewhere, testing every class searching for children of Animal.

How to extend / inherit components?

As far as I know component inheritance has not been implemented yet in Angular 2 and I'm not sure if they have plans to, however since Angular 2 is using typescript (if you've decided to go that route) you can use class inheritance by doing class MyClass extends OtherClass { ... }. For component inheritance I'd suggest getting involved with the Angular 2 project by going to https://github.com/angular/angular/issues and submitting a feature request!

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes. So when you set

myObject.prop = '123';

It doesn't look up the chain, but when you set

myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

I was also faced by the posted issue when I used python 2.7. It is working very fine with python 3.4

To make it work in python 2.7 I have added the __metaclass__ = type attribute at the top of my program and it worked.

__metaclass__ : It eases the transition from old-style classes and new-style classes.

JavaScript Extending Class

For Autodidacts:

function BaseClass(toBePrivate){
    var morePrivates;
    this.isNotPrivate = 'I know';
    // add your stuff
}
var o = BaseClass.prototype;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';


// MiddleClass extends BaseClass
function MiddleClass(toBePrivate){
    BaseClass.call(this);
    // add your stuff
    var morePrivates;
    this.isNotPrivate = 'I know';
}
var o = MiddleClass.prototype = Object.create(BaseClass.prototype);
MiddleClass.prototype.constructor = MiddleClass;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';



// TopClass extends MiddleClass
function TopClass(toBePrivate){
    MiddleClass.call(this);
    // add your stuff
    var morePrivates;
    this.isNotPrivate = 'I know';
}
var o = TopClass.prototype = Object.create(MiddleClass.prototype);
TopClass.prototype.constructor = TopClass;
// add your prototype stuff
o.stuff_is_never_private = 'whatever_except_getter_and_setter';


// to be continued...

Create "instance" with getter and setter:

function doNotExtendMe(toBePrivate){
    var morePrivates;
    return {
        // add getters, setters and any stuff you want
    }
}

Python class inherits object

History from Learn Python the Hard Way:

Python's original rendition of a class was broken in many serious ways. By the time this fault was recognized it was already too late, and they had to support it. In order to fix the problem, they needed some "new class" style so that the "old classes" would keep working but you can use the new more correct version.

They decided that they would use a word "object", lowercased, to be the "class" that you inherit from to make a class. It is confusing, but a class inherits from the class named "object" to make a class but it's not an object really its a class, but don't forget to inherit from object.

Also just to let you know what the difference between new-style classes and old-style classes is, it's that new-style classes always inherit from object class or from another class that inherited from object:

class NewStyle(object):
    pass

Another example is:

class AnotherExampleOfNewStyle(NewStyle):
    pass

While an old-style base class looks like this:

class OldStyle():
    pass

And an old-style child class looks like this:

class OldStyleSubclass(OldStyle):
    pass

You can see that an Old Style base class doesn't inherit from any other class, however, Old Style classes can, of course, inherit from one another. Inheriting from object guarantees that certain functionality is available in every Python class. New style classes were introduced in Python 2.2

Implements vs extends: When to use? What's the difference?

Implements is used for Interfaces and extends is used to extend a class.

To make it more clearer in easier terms,an interface is like it sound - an interface - a model, that you need to apply,follow, along with your ideas to it.

Extend is used for classes,here,you are extending something that already exists by adding more functionality to it.

A few more notes:

an interface can extend another interface.

And when you need to choose between implementing an interface or extending a class for a particular scenario, go for implementing an interface. Because a class can implement multiple interfaces but extend only one class.

What are the rules for calling the superclass constructor?

If you have default parameters in your base constructor the base class will be called automatically.

using namespace std;

class Base
{
    public:
    Base(int a=1) : _a(a) {}

    protected:
    int _a;
};

class Derived : public Base
{
  public:
  Derived() {}

  void printit() { cout << _a << endl; }
};

int main()
{
   Derived d;
   d.printit();
   return 0;
}

Output is: 1

When do I have to use interfaces instead of abstract classes?

Interfaces and abstracted classes seem very similar, however, there are important differences between them.

Abstraction is based on a good "is-a" relationship. Meaning that you would say that a car is a Honda, and a Honda is a car. Using abstraction on a class means you can also have abstract methods. This would require any subclass extended from it to obtain the abstract methods and override them. Using the example below, we can create an abstract howToStart(); method that will require each class to implement it.

Through abstraction, we can provide similarities between code so we would still have a base class. Using an example of the Car class idea we could create:

public abstract class Car{
    private String make;
    private String model

    protected Car() { }  // Default constructor

    protect Car(String make, String model){
        //Assign values to 
    }

    public abstract void howToStart();
}

Then with the Honda class we would have:

public class Honda extends implements Engine {

    public Honda() { }  // Default constructor

    public Honda(String make, String model){
        //Assign values
    }

    @Override
    public static void howToStart(){
        // Code on how to start
    }

}

Interfaces are based on the "has-a" relationship. This would mean you could say a car has-a engine, but an engine is not a car. In the above example, Honda has implements Engine.

For the engine interface we could create:

public interface Engine {
    public void startup();
}

The interface will provide a many-to-one instance. So we could apply the Engine interface to any type of car. We can also extend it to other object. Like if we were to make a boat class, and have sub classes of boat types, we could extend Engine and have the sub classes of boat require the startup(); method. Interfaces are good for creating framework to various classes that have some similarities. We can also implement multiple instances in one class, such as:

public class Honda extends implements Engine, Transmission, List<Parts>

Hopefully this helps.

Do subclasses inherit private fields?

I would have to answer that private fields in Java are inherited. Allow me to demonstrate:

public class Foo {

    private int x; // This is the private field.

    public Foo() {
        x = 0; // Sets int x to 0.
    }

    //The following methods are declared "final" so that they can't be overridden.
    public final void update() { x++; } // Increments x by 1.
    public final int getX() { return x; } // Returns the x value.

}


public class Bar extends Foo {

    public Bar() {

        super(); // Because this extends a class with a constructor, it is required to run before anything else.

        update(); //Runs the inherited update() method twice
        update();
        System.out.println(getX()); // Prints the inherited "x" int.

    }

}

If you run in a program Bar bar = new Bar();, then you will always see the number "2" in the output box. Because the integer "x" is encapsulated with the methods update() and getX(), then it can be proven that the integer is inherited.

The confusion is that because you can't directly access the integer "x", then people argue that it isn't inherited. However, every non-static thing in a class, be it field or method, is inherited.

Class extending more than one class Java?

Most of the answers given seem to assume that all the classes we are looking to inherit from are defined by us.

But what if one of the classes is not defined by us, i.e. we cannot change what one of those classes inherits from and therefore cannot make use of the accepted answer, what happens then?

Well the answer depends on if we have at least one of the classes having been defined by us. i.e. there exists a class A among the list of classes we would like to inherit from, where A is created by us.

In addition to the already accepted answer, I propose 3 more instances of this multiple inheritance problem and possible solutions to each.

Inheritance type 1

Ok say you want a class C to extend classes, A and B, where B is a class defined somewhere else, but A is defined by us. What we can do with this is to turn A into an interface then, class C can implement A while extending B.

class A {}
class B {} // Some external class
class C {}

Turns into

interface A {}
class AImpl implements A {}
class B {} // Some external class
class C extends B implements A

Inheritance type 2

Now say you have more than two classes to inherit from, well the same idea still holds - all but one of the classes has to be defined by us. So say we want class A to inherit from the following classes, B, C, ... X where X is a class which is external to us, i.e. defined somewhere else. We apply the same idea of turning all the other classes but the last into an interface then we can have:

interface B {}
class BImpl implements B {}
interface C {}
class CImpl implements C {}
...
class X {}
class A extends X implements B, C, ...

Inheritance type 3

Finally, there is also the case where you have just a bunch of classes to inherit from, but none of them are defined by you. This is a bit trickier, but it is doable by making use of delegation. Delegation allows a class A to pretend to be some other class B but any calls on A to some public method defined in B, actually delegates that call to an object of type B and the result is returned. This makes class A what I would call a Fat class

How does this help?

Well it's simple. You create an interface which specifies the public methods within the external classes which you would like to make use of, as well as methods within the new class you are creating, then you have your new class implement that interface. That may have sounded confusing, so let me explain better.

Initially we have the following external classes B, C, D, ..., X, and we want our new class A to inherit from all those classes.

class B {
    public void foo() {}
}

class C {
    public void bar() {}
}

class D {
    public void fooFoo() {}
}

...

class X {
    public String fooBar() {}
}

Next we create an interface A which exposes the public methods that were previously in class A as well as the public methods from the above classes

interface A {
    void doSomething(); // previously defined in A
    String fooBar(); // from class X
    void fooFoo(); // from class D
    void bar(); // from class C
    void foo(); // from class B
}

Finally, we create a class AImpl which implements the interface A.

class AImpl implements A {
    // It needs instances of the other classes, so those should be
    // part of the constructor
    public AImpl(B b, C c, D d, X x) {}
    ... // define the methods within the interface
}

And there you have it! This is sort of pseudo-inheritance because an object of type A is not a strict descendant of any of the external classes we started with but rather exposes an interface which defines the same methods as in those classes.

You might ask, why we didn't just create a class that defines the methods we would like to make use of, rather than defining an interface. i.e. why didn't we just have a class A which contains the public methods from the classes we would like to inherit from? This is done in order to reduce coupling. We don't want to have classes that use A to have to depend too much on class A (because classes tend to change a lot), but rather to rely on the promise given within the interface A.

How to inherit constructors?

Too many constructors is a sign of a broken design. Better a class with few constructors and the ability to set properties. If you really need control over the properties, consider a factory in the same namespace and make the property setters internal. Let the factory decide how to instantiate the class and set its properties. The factory can have methods that take as many parameters as necessary to configure the object properly.

Prefer composition over inheritance?

If you understand the difference, it's easier to explain.

Procedural Code

An example of this is PHP without the use of classes (particularly before PHP5). All logic is encoded in a set of functions. You may include other files containing helper functions and so on and conduct your business logic by passing data around in functions. This can be very hard to manage as the application grows. PHP5 tries to remedy this by offering more object oriented design.

Inheritance

This encourages the use of classes. Inheritance is one of the three tenets of OO design (inheritance, polymorphism, encapsulation).

class Person {
   String Title;
   String Name;
   Int Age
}

class Employee : Person {
   Int Salary;
   String Title;
}

This is inheritance at work. The Employee "is a" Person or inherits from Person. All inheritance relationships are "is-a" relationships. Employee also shadows the Title property from Person, meaning Employee.Title will return the Title for the Employee not the Person.

Composition

Composition is favoured over inheritance. To put it very simply you would have:

class Person {
   String Title;
   String Name;
   Int Age;

   public Person(String title, String name, String age) {
      this.Title = title;
      this.Name = name;
      this.Age = age;
   }

}

class Employee {
   Int Salary;
   private Person person;

   public Employee(Person p, Int salary) {
       this.person = p;
       this.Salary = salary;
   }
}

Person johnny = new Person ("Mr.", "John", 25);
Employee john = new Employee (johnny, 50000);

Composition is typically "has a" or "uses a" relationship. Here the Employee class has a Person. It does not inherit from Person but instead gets the Person object passed to it, which is why it "has a" Person.

Composition over Inheritance

Now say you want to create a Manager type so you end up with:

class Manager : Person, Employee {
   ...
}

This example will work fine, however, what if Person and Employee both declared Title? Should Manager.Title return "Manager of Operations" or "Mr."? Under composition this ambiguity is better handled:

Class Manager {
   public string Title;
   public Manager(Person p, Employee e)
   {
      this.Title = e.Title;
   }
}

The Manager object is composed as an Employee and a Person. The Title behaviour is taken from employee. This explicit composition removes ambiguity among other things and you'll encounter fewer bugs.

How to invoke the super constructor in Python?

Short Answer

super(DerivedClass, self).__init__()

Long Answer

What does super() do?

It takes specified class name, finds its base classes (Python allows multiple inheritance) and looks for the method (__init__ in this case) in each of them from left to right. As soon as it finds method available, it will call it and end the search.

How do I call init of all base classes?

Above works if you have only one base class. But Python does allow multiple inheritance and you might want to make sure all base classes are initialized properly. To do that, you should have each base class call init:

class Base1:
  def __init__():
    super(Base1, self).__init__()

class Base2:
  def __init__():
    super(Base2, self).__init__()

class Derived(Base1, Base2):
  def __init__():
    super(Derived, self).__init__()

What if I forget to call init for super?

The constructor (__new__) gets invoked in a chain (like in C++ and Java). Once the instance is created, only that instance's initialiser (__init__) is called, without any implicit chain to its superclass.

How to call a Parent Class's method from Child Class in Python?

Use the super() function:

class Foo(Bar):
    def baz(self, arg):
        return super().baz(arg)

For Python < 3, you must explicitly opt in to using new-style classes and use:

class Foo(Bar):
    def baz(self, arg):
        return super(Foo, self).baz(arg)

Java Inheritance - calling superclass method

Whenever you create child class object then that object has all the features of parent class. Here Super() is the facilty for accession parent.

If you write super() at that time parents's default constructor is called. same if you write super.

this keyword refers the current object same as super key word facilty for accessing parents.

Ruby: kind_of? vs. instance_of? vs. is_a?

kind_of? and is_a? are synonymous.

instance_of? is different from the other two in that it only returns true if the object is an instance of that exact class, not a subclass.

Example:

  • "hello".is_a? Object and "hello".kind_of? Object return true because "hello" is a String and String is a subclass of Object.
  • However "hello".instance_of? Object returns false.

How to determine an object's class?

Multiple right answers were presented, but there are still more methods: Class.isAssignableFrom() and simply attempting to cast the object (which might throw a ClassCastException).

Possible ways summarized

Let's summarize the possible ways to test if an object obj is an instance of type C:

// Method #1
if (obj instanceof C)
    ;

// Method #2
if (C.class.isInstance(obj))
    ;

// Method #3
if (C.class.isAssignableFrom(obj.getClass()))
    ;

// Method #4
try {
    C c = (C) obj;
    // No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}

// Method #5
try {
    C c = C.class.cast(obj);
    // No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}

Differences in null handling

There is a difference in null handling though:

  • In the first 2 methods expressions evaluate to false if obj is null (null is not instance of anything).
  • The 3rd method would throw a NullPointerException obviously.
  • The 4th and 5th methods on the contrary accept null because null can be cast to any type!

To remember: null is not an instance of any type but it can be cast to any type.

Notes

  • Class.getName() should not be used to perform an "is-instance-of" test becase if the object is not of type C but a subclass of it, it may have a completely different name and package (therefore class names will obviously not match) but it is still of type C.
  • For the same inheritance reason Class.isAssignableFrom() is not symmetric:
    obj.getClass().isAssignableFrom(C.class) would return false if the type of obj is a subclass of C.

Call a child class method from a parent class object

A parent class should not have knowledge of child classes. You can implement a method calculate() and override it in every subclass:

class Person {
    String name;
    void getName(){...}
    void calculate();
}

and then

class Student extends Person{
    String class;
    void getClass(){...}

    @Override
    void calculate() {
        // do something with a Student
    }
}

and

class Teacher extends Person{
    String experience;
    void getExperience(){...}

    @Override
    void calculate() {
        // do something with a Student
    }

}

By the way. Your statement about abstract classes is confusing. You can call methods defined in an abstract class, but of course only of instances of subclasses.

In your example you can make Person abstract and the use getName() on instanced of Student and Teacher.

Nesting await in Parallel.ForEach

svick's answer is (as usual) excellent.

However, I find Dataflow to be more useful when you actually have large amounts of data to transfer. Or when you need an async-compatible queue.

In your case, a simpler solution is to just use the async-style parallelism:

var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };

var customerTasks = ids.Select(i =>
  {
    ICustomerRepo repo = new CustomerRepo();
    return repo.GetCustomer(i);
  });
var customers = await Task.WhenAll(customerTasks);

foreach (var customer in customers)
{
  Console.WriteLine(customer.ID);
}

Console.ReadKey();

Change background color of iframe issue

An <iframe> background can be changed like this:

<iframe allowtransparency="true" style="background: #FFFFFF;" 
    src="http://zingaya.com/widget/9d043c064dc241068881f045f9d8c151" 
    frameborder="0" height="184" width="100%">
</iframe>

I don't think it's possible to change the background of the page that you have loaded in the iframe.

Save a list to a .txt file

If you have more then 1 dimension array

with open("file.txt", 'w') as output:
    for row in values:
        output.write(str(row) + '\n')

Code to write without '[' and ']'

with open("file.txt", 'w') as file:
        for row in values:
            s = " ".join(map(str, row))
            file.write(s+'\n')

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.

@{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    string cLayout = "";

    if (controller == "Webmaster")
        cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
    else
        cLayout = "~/Views/Shared/_Layout.cshtml";

    Layout = cLayout;
}

Read Complete Article here "How to Render different Layout in ASP.NET MVC"

Neither BindingResult nor plain target object for bean name available as request attr

I have encountered this problem as well. Here is my solution:

Below is the error while running a small Spring Application:-

*HTTP Status 500 - 
--------------------------------------------------------------------------------
type Exception report
message 
description The server encountered an internal error () that prevented it from fulfilling this request.
exception 
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/employe.jsp at line 12
9: <form:form method="POST" commandName="command"  action="/SpringWeb/addEmploye">
10:    <table>
11:     <tr>
12:         <td><form:label path="name">Name</form:label></td>
13:         <td><form:input path="name" /></td>
14:     </tr>
15:     <tr>
Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause 
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
    org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
    org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
    org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:89)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005flabel_005f0(employe_jsp.java:185)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspx_meth_form_005fform_005f0(employe_jsp.java:120)
    org.apache.jsp.WEB_002dINF.jsp.employe_jsp._jspService(employe_jsp.java:80)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.26 logs.*

In order to resolve this issue you need to do the following in the controller class:-

  1. Change the import package from "import org.springframework.web.portlet.ModelAndView;" to "import org.springframework.web.servlet.ModelAndView;"...
  2. Recompile and run the code... the problem should get resolved.

Showing the stack trace from a running Python application

I am in the GDB camp with the python extensions. Follow https://wiki.python.org/moin/DebuggingWithGdb, which means

  1. dnf install gdb python-debuginfo or sudo apt-get install gdb python2.7-dbg
  2. gdb python <pid of running process>
  3. py-bt

Also consider info threads and thread apply all py-bt.

From Arraylist to Array

This is the best way (IMHO).

List<String> myArrayList = new ArrayList<String>();
//.....
String[] myArray = myArrayList.toArray(new String[myArrayList.size()]);

This code works also:

String[] myArray = myArrayList.toArray(new String[0]);

But it less effective: the string array is created twice: first time zero-length array is created, then the real-size array is created, filled and returned. So, if since you know the needed size (from list.size()) you should create array that is big enough to put all elements. In this case it is not re-allocated.

Best practice to call ConfigureAwait for all server-side code

Update: ASP.NET Core does not have a SynchronizationContext. If you are on ASP.NET Core, it does not matter whether you use ConfigureAwait(false) or not.

For ASP.NET "Full" or "Classic" or whatever, the rest of this answer still applies.

Original post (for non-Core ASP.NET):

This video by the ASP.NET team has the best information on using async on ASP.NET.

I had read that it is more performant since it doesn't have to switch thread contexts back to the original thread context.

This is true with UI applications, where there is only one UI thread that you have to "sync" back to.

In ASP.NET, the situation is a bit more complex. When an async method resumes execution, it grabs a thread from the ASP.NET thread pool. If you disable the context capture using ConfigureAwait(false), then the thread just continues executing the method directly. If you do not disable the context capture, then the thread will re-enter the request context and then continue to execute the method.

So ConfigureAwait(false) does not save you a thread jump in ASP.NET; it does save you the re-entering of the request context, but this is normally very fast. ConfigureAwait(false) could be useful if you're trying to do a small amount of parallel processing of a request, but really TPL is a better fit for most of those scenarios.

However, with ASP.NET Web Api, if your request is coming in on one thread, and you await some function and call ConfigureAwait(false) that could potentially put you on a different thread when you are returning the final result of your ApiController function.

Actually, just doing an await can do that. Once your async method hits an await, the method is blocked but the thread returns to the thread pool. When the method is ready to continue, any thread is snatched from the thread pool and used to resume the method.

The only difference ConfigureAwait makes in ASP.NET is whether that thread enters the request context when resuming the method.

I have more background information in my MSDN article on SynchronizationContext and my async intro blog post.

How to set a primary key in MongoDB?

If you're using Mongo on Meteor, you can use _ensureIndex:

CollectionName._ensureIndex({field:1 }, {unique: true});

PHP - Getting the index of a element from a array

function Index($index) {
    $Count = count($YOUR_ARRAY);
    if ($index <= $Count) {
        $Keys = array_keys($YOUR_ARRAY);
        $Value = array_values($YOUR_ARRAY);
        return $Keys[$index] . ' = ' . $Value[$index];
    } else {
        return "Out of the ring";
    }
}

echo 'Index : ' . Index(0);

Replace the ( $YOUR_ARRAY )

How do I disable log messages from the Requests library?

import logging
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.CRITICAL)

In this way all the messages of level=INFO from urllib3 won't be present in the logfile.

So you can continue to use the level=INFO for your log messages...just modify this for the library you are using.

How to verify CuDNN installation?

On Ubuntu 20.04LTS:

cat /usr/local/cuda/include/cudnn_version.h | grep CUDNN_MAJOR

returned the expected results

Difference between ApiController and Controller in ASP.NET MVC

The main difference is: Web API is a service for any client, any devices, and MVC Controller only serve its client. The same because it is MVC platform.

How to add an item to a drop down list in ASP.NET?

Try this, it will insert the list item at index 0;

DropDownList1.Items.Insert(0, new ListItem("Add New", ""));

TreeMap sort by value

A lot of people hear adviced to use List and i prefer to use it as well

here are two methods you need to sort the entries of the Map according to their values.

    static final Comparator<Entry<?, Double>> DOUBLE_VALUE_COMPARATOR = 
        new Comparator<Entry<?, Double>>() {
            @Override
            public int compare(Entry<?, Double> o1, Entry<?, Double> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        };

        static final List<Entry<?, Double>> sortHashMapByDoubleValue(HashMap temp)
        {
            Set<Entry<?, Double>> entryOfMap = temp.entrySet();

            List<Entry<?, Double>> entries = new ArrayList<Entry<?, Double>>(entryOfMap);
            Collections.sort(entries, DOUBLE_VALUE_COMPARATOR);
            return entries;
        }

Updating version numbers of modules in a multi-module Maven project

I encourage you to read the Maven Book about multi-module (reactor) builds.

I meant in particular the following:

<parent>
    <artifactId>xyz-application</artifactId>
    <groupId>com.xyz</groupId>
    <version>2.50.0.g</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.xyz</groupId>
<artifactId>xyz-Library</artifactId>
<version>2.50.0.g</version>

should be changed into. Here take care about the not defined version only in parent part it is defined.

<modelVersion>4.0.0</modelVersion>

<parent>
    <artifactId>xyz-application</artifactId>
    <groupId>com.xyz</groupId>
    <version>2.50.0.g</version>
</parent>
<groupId>com.xyz</groupId>
<artifactId>xyz-Library</artifactId>

This is a better link.

How to lookup JNDI resources on WebLogic?

I just had to update legacy Weblogic 8 app to use a data-source instead of hard-coded JDBC string. Datasource JNDI name on the configuration tab in the Weblogic admin showed: "weblogic.jdbc.ESdatasource", below are two ways that worked:

      Context ctx = new InitialContext();
      DataSource dataSource;

      try {
        dataSource = (DataSource) ctx.lookup("weblogic.jdbc.ESdatasource");
        response.getWriter().println("A " +dataSource);
      }catch(Exception e) {
        response.getWriter().println("A " + e.getMessage() + e.getCause());
      }

      //or

      try {
        dataSource = (DataSource) ctx.lookup("weblogic/jdbc/ESdatasource");
        response.getWriter().println("F "+dataSource);
      }catch(Exception e) {
        response.getWriter().println("F " + e.getMessage() + e.getCause());
      }

      //use your datasource
      conn = datasource.getConnection();

That's all folks. No passwords and initial context factory needed from the inside of Weblogic app.

How do I call ::CreateProcess in c++ to launch a Windows executable?

On a semi-related note, if you want to start a process that has more privileges than your current process (say, launching an admin app, which requires Administrator rights, from the main app running as a normal user), you can't do so using CreateProcess() on Vista since it won't trigger the UAC dialog (assuming it is enabled). The UAC dialog is triggered when using ShellExecute(), though.

Java: int[] array vs int array[]

There is no difference between these two declarations, and both have the same performance.

Importing class/java files in Eclipse

First, you don't need the .class files if they are compiled from your .java classes.

To import your files, you need to create an empty Java project. They you either import them one by one (New -> File -> Advanced -> Link file) or directly copy them into their corresponding folder/package and refresh the project.

Create code first, many to many, with additional fields in association table

I want to propose a solution where both flavors of a many-to-many configuration can be achieved.

The "catch" is we need to create a view that targets the Join Table, since EF validates that a schema's table may be mapped at most once per EntitySet.

This answer adds to what's already been said in previous answers and doesn't override any of those approaches, it builds upon them.

The model:

public class Member
{
    public int MemberID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
    public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Message { get; set; }

    public virtual ICollection<Member> Members { get; set; }
    public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}

public class MemberCommentView
{
    public int MemberID { get; set; }
    public int CommentID { get; set; }
    public int Something { get; set; }
    public string SomethingElse { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }
}

The configuration:

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

public class MemberConfiguration : EntityTypeConfiguration<Member>
{
    public MemberConfiguration()
    {
        HasKey(x => x.MemberID);

        Property(x => x.MemberID).HasColumnType("int").IsRequired();
        Property(x => x.FirstName).HasColumnType("varchar(512)");
        Property(x => x.LastName).HasColumnType("varchar(512)")

        // configure many-to-many through internal EF EntitySet
        HasMany(s => s.Comments)
            .WithMany(c => c.Members)
            .Map(cs =>
            {
                cs.ToTable("MemberComment");
                cs.MapLeftKey("MemberID");
                cs.MapRightKey("CommentID");
            });
    }
}

public class CommentConfiguration : EntityTypeConfiguration<Comment>
{
    public CommentConfiguration()
    {
        HasKey(x => x.CommentID);

        Property(x => x.CommentID).HasColumnType("int").IsRequired();
        Property(x => x.Message).HasColumnType("varchar(max)");
    }
}

public class MemberCommentViewConfiguration : EntityTypeConfiguration<MemberCommentView>
{
    public MemberCommentViewConfiguration()
    {
        ToTable("MemberCommentView");
        HasKey(x => new { x.MemberID, x.CommentID });

        Property(x => x.MemberID).HasColumnType("int").IsRequired();
        Property(x => x.CommentID).HasColumnType("int").IsRequired();
        Property(x => x.Something).HasColumnType("int");
        Property(x => x.SomethingElse).HasColumnType("varchar(max)");

        // configure one-to-many targeting the Join Table view
        // making all of its properties available
        HasRequired(a => a.Member).WithMany(b => b.MemberComments);
        HasRequired(a => a.Comment).WithMany(b => b.MemberComments);
    }
}

The context:

using System.Data.Entity;

public class MyContext : DbContext
{
    public DbSet<Member> Members { get; set; }
    public DbSet<Comment> Comments { get; set; }
    public DbSet<MemberCommentView> MemberComments { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Configurations.Add(new MemberConfiguration());
        modelBuilder.Configurations.Add(new CommentConfiguration());
        modelBuilder.Configurations.Add(new MemberCommentViewConfiguration());

        OnModelCreatingPartial(modelBuilder);
     }
}

From Saluma's (@Saluma) answer

If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:

This still works...

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
    .ToList();

...but could now also be...

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.Comments)
    .ToList();

Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:

This still works...

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        Comments = m.MemberComments.Select(mc => mc.Comment)
    })
    .ToList();

...but could now also be...

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        m.Comments
    })
        .ToList();

If you want to remove a comment from a member

var comment = ... // assume comment from member John Smith
var member = ... // assume member John Smith

member.Comments.Remove(comment);

If you want to Include() a member's comments

var member = context.Members
    .Where(m => m.FirstName == "John", m.LastName == "Smith")
    .Include(m => m.Comments);

This all feels like syntactic sugar, however it does get you a few perks if you're willing to go through the additional configuration. Either way you seem to be able to get the best of both approaches.

MySQL: How to add one day to datetime field in query

It`s possible to use MySQL specific syntax sugar:

SELECT ... date_field + INTERVAL 1 DAY

Looks much more pretty instead of DATE_ADD function

Add borders to cells in POI generated Excel File

a Helper function:

private void setRegionBorderWithMedium(CellRangeAddress region, Sheet sheet) {
        Workbook wb = sheet.getWorkbook();
        RegionUtil.setBorderBottom(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, region, sheet, wb);
    }

When you want to add Border in Excel, then

String cellAddr="$A$11:$A$17";

setRegionBorderWithMedium(CellRangeAddress.valueOf(cellAddr1), sheet);

python mpl_toolkits installation issue

I can't comment due to the lack of reputation, but if you are on arch linux, you should be able to find the corresponding libraries on the arch repositories directly. For example for mpl_toolkits.basemap:

pacman -S python-basemap

How to update a value, given a key in a hashmap?

One line solution:

map.put(key, map.containsKey(key) ? map.get(key) + 1 : 1);

How to create a new component in Angular 4 using CLI

ng generate component componentName.

It will automatically import the component in module.ts

Windows command prompt log to a file

In cmd when you use > or >> the output will be only written on the file. Is it possible to see the output in the cmd windows and also save it in a file. Something similar if you use teraterm, when you can start saving all the log in a file meanwhile you use the console and view it (only for ssh, telnet and serial).

How do I round to the nearest 0.5?

decimal d = // your number..

decimal t = d - Math.Floor(d);
if(t >= 0.3d && t <= 0.7d)
{
    return Math.Floor(d) + 0.5d;
}
else if(t>0.7d)
    return Math.Ceil(d);
return Math.Floor(d);

How to connect to Mysql Server inside VirtualBox Vagrant?

For anyone trying to do this using mysql workbench or sequel pro these are the inputs:

Mysql Host: 192.168.56.101 (or ip that you choose for it)
username: root (or mysql username u created)
password: **** (your mysql password)
database: optional
port: optional (unless you chose another port, defaults to 3306)

ssh host: 192.168.56.101 (or ip that you choose for this vm, like above)
ssh user: vagrant (vagrants default username)
ssh password: vagrant (vagrants default password)
ssh port: optional (unless you chose another)

source: https://coderwall.com/p/yzwqvg

Grant all on a specific schema in the db to a group role in PostgreSQL

You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies:

(but note that ALL TABLES is considered to include views and foreign tables).

Bold emphasis mine. serial columns are implemented with nextval() on a sequence as column default and, quoting the manual:

For sequences, this privilege allows the use of the currval and nextval functions.

So if there are serial columns, you'll also want to grant USAGE (or ALL PRIVILEGES) on sequences

GRANT USAGE ON ALL SEQUENCES IN SCHEMA foo TO mygrp;

Note: identity columns in Postgres 10 or later use implicit sequences that don't require additional privileges. (Consider upgrading serial columns.)

What about new objects?

You'll also be interested in DEFAULT PRIVILEGES for users or schemas:

ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT ALL PRIVILEGES ON TABLES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT USAGE          ON SEQUENCES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo REVOKE ...;

This sets privileges for objects created in the future automatically - but not for pre-existing objects.

Default privileges are only applied to objects created by the targeted user (FOR ROLE my_creating_role). If that clause is omitted, it defaults to the current user executing ALTER DEFAULT PRIVILEGES. To be explicit:

ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo GRANT ...;
ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo REVOKE ...;

Note also that all versions of pgAdmin III have a subtle bug and display default privileges in the SQL pane, even if they do not apply to the current role. Be sure to adjust the FOR ROLE clause manually when copying the SQL script.

ImportError: No module named sqlalchemy

This code works perfectly:

import sqlalchemy

Maybe you installed the package in another version of the interpreter?

Also, like Shawley pointed out, you need to have the flask extension installed in order for it to be accessible.

Reference — What does this symbol mean in PHP?

?-> NullSafe Operator

Added in PHP 8.0

It's the NullSafe Operator, it returns null in case you try to invoke functions or get values from null. Nullsafe operator can be chained and can be used both on the methods and properties.

$objDrive = null;
$drive = $objDrive?->func?->getDriver()?->value; //return null
$drive = $objDrive->func->getDriver()->value; // Error: Trying to get property 'func' of non-object

Nullsafe operator doesn't work with array keys:

$drive['admin']?->getDriver()?->value //Warning: Trying to access array offset on value of type null

$drive = [];
$drive['admin']?->getAddress()?->value //Warning: Undefined array key "admin"

round() for float in C++

It may be worth noting that if you wanted an integer result from the rounding you don't need to pass it through either ceil or floor. I.e.,

int round_int( double r ) {
    return (r > 0.0) ? (r + 0.5) : (r - 0.5); 
}

Login to website, via C#

You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.

There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").


POSTing to the login form

Form posts are easy to simulate, it's just a case of formatting your post data as follows:

field1=value1&field2=value2

Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:

string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];

Here's an example of what you should see in the Set-cookie header for your login form:

PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-

GETting the page behind the login form

Now you can perform your GET request to a page that you need to be logged in for.

string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

EDIT:

If you need to view the results of the first POST, you can recover the HTML it returned with:

using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

Place this directly below cookieHeader = resp.Headers["Set-cookie"]; and then inspect the string held in pageSource.

How to get a value inside an ArrayList java

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

class hari
{
public static void main (String[] args) throws Exception
{  Scanner s=new Scanner(System.in);
    int i=0;
    int b=0;
    HashSet<Integer> h=new HashSet<Integer>();
    try{
        for(i=0;i<1000;i++)
    {   b=s.nextInt();
        h.add(b);
    }
    }
    catch(Exception e){
        System.out.println(h+","+h.size());
    }
}}

How can I catch all the exceptions that will be thrown through reading and writing a file?

If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions later (perhaps at the same time as other exceptions).

The code looks like:

public void someMethode() throws SomeCheckedException {

    //  code

}

Then later you can deal with the exceptions if you don't wanna deal with them in that method.

To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)

try {

    // exceptional block of code ...

    // ...

} catch (Exception e){

    // Deal with e as you please.
    //e may be any type of exception at all.

}

The reason that works is because Exception is the base class for all exceptions. Thus any exception that may get thrown is an Exception (Uppercase 'E').

If you want to handle your own exceptions first simply add a catch block before the generic Exception one.

try{    
}catch(MyOwnException me){
}catch(Exception e){
}

WhatsApp API (java/python)

Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.

How to use group by with union in t-sql

You need to alias the subquery. Thus, your statement should be:

Select Z.id
From    (
        Select id, time
        From dbo.tablea
        Union All
        Select id, time
        From dbo.tableb
        ) As Z
Group By Z.id

How to select multiple rows filled with constants?

Try the connect by clause in oracle, something like this

select level,level+1,level+2 from dual connect by level <=3;

For more information on connect by clause follow this link : removed URL because oraclebin site is now malicious.

Fatal error: Class 'PHPMailer' not found

Just from reading what you have written, you will need to add the file class.phpmailer.php to your directory as well.

Firing events on CSS class changes in jQuery

var timeout_check_change_class;

function check_change_class( selector )
{
    $(selector).each(function(index, el) {
        var data_old_class = $(el).attr('data-old-class');
        if (typeof data_old_class !== typeof undefined && data_old_class !== false) 
        {

            if( data_old_class != $(el).attr('class') )
            {
                $(el).trigger('change_class');
            }
        }

        $(el).attr('data-old-class', $(el).attr('class') );

    });

    clearTimeout( timeout_check_change_class );
    timeout_check_change_class = setTimeout(check_change_class, 10, selector);
}
check_change_class( '.breakpoint' );


$('.breakpoint').on('change_class', function(event) {
    console.log('haschange');
});

How to disable Home and other system buttons in Android?

Post ICS i.e. Android 4+, the overriding of the HomeButton has been removed for security reasons, to enable the user exit in case the application turns out to be a malware.

Plus, it is not a really good practice to not let the user navigate away from the application. But, since you are making a lock screen application, what you can do is declare the activity as a Launcher , so that when the HomeButton is pressed it will simply restart your application and remain there itself (the users would notice nothing but a slight flicker in the screen).

You can go through the following link:

http://dharmendra4android.blogspot.in/2012/05/override-home-button-in-android.html

HTTP requests and JSON parsing in Python

Try this:

import requests
import json

# Goole Maps API.
link = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'

# Request data from link as 'str'
data = requests.get(link).text

# convert 'str' to Json
data = json.loads(data)

# Now you can access Json 
for i in data['routes'][0]['legs'][0]['steps']:
    lattitude = i['start_location']['lat']
    longitude = i['start_location']['lng']
    print('{}, {}'.format(lattitude, longitude))

"Prevent saving changes that require the table to be re-created" negative effects

Tools --> Options --> Designers node --> Uncheck " Prevent saving changes that require table recreation ".

Best way to test if a row exists in a MySQL table

At times it is quite handy to get the auto increment primary key (id) of the row if it exists and 0 if it doesn't.

Here's how this can be done in a single query:

SELECT IFNULL(`id`, COUNT(*)) FROM WHERE ...

CSS3 equivalent to jQuery slideUp and slideDown?

So I've gone ahead and answered my own question :)

@True's answer regarded transforming an element to a specific height. The problem with this is I don't know the height of the element (it can fluctuate).

I found other solutions around which used max-height as the transition but this produced a very jerky animation for me.

My solution below works only in WebKit browsers.

Although not purely CSS, it involves transitioning the height, which is determined by some JS.

_x000D_
_x000D_
$('#click-me').click(function() {_x000D_
  var height = $("#this").height();_x000D_
  if (height > 0) {_x000D_
    $('#this').css('height', '0');_x000D_
  } else {_x000D_
    $("#this").css({_x000D_
      'position': 'absolute',_x000D_
      'visibility': 'hidden',_x000D_
      'height': 'auto'_x000D_
    });_x000D_
    var newHeight = $("#this").height();_x000D_
    $("#this").css({_x000D_
      'position': 'static',_x000D_
      'visibility': 'visible',_x000D_
      'height': '0'_x000D_
    });_x000D_
    $('#this').css('height', newHeight + 'px');_x000D_
  }_x000D_
});
_x000D_
#this {_x000D_
  width: 500px;_x000D_
  height: 0;_x000D_
  max-height: 9999px;_x000D_
  overflow: hidden;_x000D_
  background: #BBBBBB;_x000D_
  -webkit-transition: height 1s ease-in-out;_x000D_
}_x000D_
_x000D_
#click-me {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>_x000D_
_x000D_
<p id="click-me">click me</p>_x000D_
<div id="this">here<br />is<br />a<br />bunch<br />of<br />content<br />sdf</div>_x000D_
<div>always shows</div>
_x000D_
_x000D_
_x000D_

View on JSFiddle

Capturing a single image from my webcam in Java or Python

On windows it is easy to interact with your webcam with pygame:

from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')

I haven't tried using pygame on linux (all my linux boxen are servers without X), but this link might be helpful http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-on-linux

Output of git branch in tree like fashion

For those who use Github, they have a branch network viewer that seems easier to read

How to access Anaconda command prompt in Windows 10 (64-bit)

To run Anaconda Prompt using icon, I made an icon and put

%windir%\System32\cmd.exe "/K" C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3 The file location would be different in each computer.

at icon -> right click -> Property -> Shortcut -> Target

I see %HOMEPATH% at icon -> right click -> Property -> Start in

OS: Windows 10, Library: Anaconda 10 (64 bit)

Intel's HAXM equivalent for AMD on Windows OS

From the Android docs (March 2016):

Before attempting to use this type of acceleration, you should first determine if your development system’s CPU supports one of the following virtualization extensions technologies:

  • Intel Virtualization Technology (VT, VT-x, vmx) extensions
  • AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)

The specifications from the manufacturer of your CPU should indicate if it supports virtualization extensions. If your CPU does not support one of these virtualization technologies, then you cannot use virtual machine acceleration.

Note: Virtualization extensions are typically enabled through your computer's BIOS and are frequently turned off by default. Check the documentation for your system's motherboard to find out how to enable virtualization extensions.

Most people talk about Genymotion being faster, and I have never heard anyone say it's slower. I definitely think it's faster, and it will be worth the ~20 minutes it will take to set up just to try it.

How to show particular image as thumbnail while implementing share on Facebook?

I also had an issue on a site I was working on last week. I implemented a like box and tested the like box. Then I went ahead to add an image to my header (the ob:image meta). Still the correct image did not show up on my facebook notification.

I tried everything, and came to the conclusion that every single implementation of a like button is cached. So let's say you clock the Like button on url A, then you specify an image in the header and you test it by clicking the Luke button again on url A. You won't see the image as the page is cached. The image will show up when you click on the Like button on page B.

To reset the cache, you have to use the lint debugger tool that's mentioned above, and validate all the Urls for those that are cached... That's the only thing that worked for me.

Centering FontAwesome icons vertically and horizontally

If you are using twitter Bootstrap add the class text-center to your code.

<div class='login-icon'><i class="icon-lock text-center"></i></div>

Get individual query parameters from Uri

You can use:

var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)

MSDN

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

How do I create a folder in a GitHub repository?

You just create the required folders in your local repository. For example, you created the app and config directories.

You may create new files under these folders.

For Git rules:

  1. First we need to add files to the directory.
  2. Then commit those added files.

Git command to do commit:

  1. git add app/ config/
  2. git commit

Then give the commit message and save the commit.

Then push to your remote repository,

git push origin remote

Hadoop "Unable to load native-hadoop library for your platform" warning

In my case , after I build hadoop on my 64 bit Linux mint OS, I replaced the native library in hadoop/lib. Still the problem persist. Then I figured out the hadoop pointing to hadoop/lib not to the hadoop/lib/native. So I just moved all content from native library to its parent. And the warning just gone.

How to Create an excel dropdown list that displays text with a numeric hidden value

There are two types of drop down lists available (I am not sure since which version).

ActiveX Drop Down
You can set the column widths, so your hidden column can be set to 0.

Form Drop Down
You could set the drop down range to a hidden sheet and reference the cell adjacent to the selected item. This would also work with the ActiveX type control.

Custom Cell Row Height setting in storyboard is not responding

Added as a comment, but posting as an answer for visibility:

There seems to also be an issue if you initially setup a table view as "static cells" and then change it to "dynamic prototypes." I had an issue where even the delegate method for heightForRowAtIndexPath was being ignored. I first resolved it by directly editing the storyboard XML, then finally just rebuilt the storyboard scene from scratch, using dynamic prototypes from the start.

How can I convert a string to an int in Python?

def addition(a, b): return a + b

def subtraction(a, b): return a - b

def multiplication(a, b): return a * b

def division(a, b): return a / b

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
print "Please choose what you'd like to do:"

print "0: Addition"
print "1: Subtraction"
print "2: Multiplication"
print "3: Division"
print "4: Quit Application"



#Capture the menu choice.
choice = raw_input()    

if choice == "0":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(addition(numberA, numberB)) + "\n"
elif choice == "1":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(subtraction(numberA, numberB)) + "\n"
elif choice == "2":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(multiplication(numberA, numberB)) + "\n"
elif choice == "3":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(division(numberA, numberB)) + "\n"
elif choice == "4":
    print "Bye!"
    keepProgramRunning = False
else:
    print "Please choose a valid option."
    print "\n"

Remove 'b' character do in front of a string literal in Python 3

Here u Go

f = open('test.txt','rb+')
ch=f.read(1)
ch=str(ch,'utf-8')
print(ch)

receiver type *** for instance message is a forward declaration

I was trying to use @class "Myclass.h".

When I changed it to #import "Myclass.h", it worked fine.

How to launch PowerShell (not a script) from the command line

If you go to C:\Windows\system32\Windowspowershell\v1.0 (and C:\Windows\syswow64\Windowspowershell\v1.0 on x64 machines) in Windows Explorer and double-click powershell.exe you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe can be set independently from the default properties.

To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.

Running start powershell from cmd.exe should start a new console with your default settings.

What is the --save option for npm install?

You can also use -S, -D or -P which are equivalent of saving the package to an app dependency, a dev dependency or prod dependency. See more NPM shortcuts below:

-v: --version
-h, -?, --help, -H: --usage
-s, --silent: --loglevel silent
-q, --quiet: --loglevel warn
-d: --loglevel info
-dd, --verbose: --loglevel verbose
-ddd: --loglevel silly
-g: --global
-C: --prefix
-l: --long
-m: --message
-p, --porcelain: --parseable
-reg: --registry
-f: --force
-desc: --description
-S: --save
-P: --save-prod
-D: --save-dev
-O: --save-optional
-B: --save-bundle
-E: --save-exact
-y: --yes
-n: --yes false
ll and la commands: ls --long

This list of shortcuts can be obtained by running the following command:

$ npm help 7 config

Chrome Extension: Make it run every page load

From a background script you can listen to the chrome.tabs.onUpdated event and check the property changeInfo.status on the callback. It can be loading or complete. If it is complete, do the action.

Example:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {

    // do your things

  }
})

Because this will probably trigger on every tab completion, you can also check if the tab is active on its homonymous attribute, like this:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete' && tab.active) {

    // do your things

  }
})

TypeError: 'int' object is not subscriptable

If you want to sum the digit of a number, one way to do it is using sum() + a generator expression:

sum(int(i) for i in str(155))

I modified a little your code using sum(), maybe you want to take a look at it:

birthday = raw_input("When is your birthday(mm/dd/yyyy)? ")
summ = sum(int(i) for i in birthday[0:2])
sumd = sum(int(i) for i in birthday[3:5])
sumy = sum(int(i) for i in birthday[6:10])
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumln = sum(int(c) for c in str(sumall)))
print "Your lucky number is", sumln

Prevent redirect after form is submitted

Instead of return false, you could try event.preventDefault(); like this:

$(function() {
$('#registerform').submit(function(event) {
    event.preventDefault();
    $(this).submit();
    }); 
});

jQuery validation plugin: accept only alphabetical characters?

 $('.AlphabetsOnly').keypress(function (e) {
        var regex = new RegExp(/^[a-zA-Z\s]+$/);
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else {
            e.preventDefault();
            return false;
        }
    });

django - get() returned more than one topic

get() returned more than one topic -- it returned 2!

The above error indicatess that you have more than one record in the DB related to the specific parameter you passed while querying using get() such as

Model.objects.get(field_name=some_param)

To avoid this kind of error in the future, you always need to do query as per your schema design. In your case you designed a table with a many-to-many relationship so obviously there will be multiple records for that field and that is the reason you are getting the above error.

So instead of using get() you should use filter() which will return multiple records. Such as

Model.objects.filter(field_name=some_param)

Please read about how to make queries in django here.

Run function in script from command line (Node JS)

This one is dirty but works :)

I will be calling main() function from my script. Previously I just put calls to main at the end of script. However I did add some other functions and exported them from script (to use functions in some other parts of code) - but I dont want to execute main() function every time I import other functions in other scripts.

So I did this, in my script i removed call to main(), and instead at the end of script I put this check:

if (process.argv.includes('main')) {
   main();
}

So when I want to call that function in CLI: node src/myScript.js main

How to set <iframe src="..."> without causing `unsafe value` exception?

This one works for me.

import { Component,Input,OnInit} from '@angular/core';
import {DomSanitizer,SafeResourceUrl,} from '@angular/platform-browser';

@Component({
    moduleId: module.id,
    selector: 'player',
    templateUrl: './player.component.html',
    styleUrls:['./player.component.scss'],
    
})
export class PlayerComponent implements OnInit{
    @Input()
    id:string; 
    url: SafeResourceUrl;
    constructor (public sanitizer:DomSanitizer) {
    }
    ngOnInit() {
        this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.id);      
    }
}

SVN "Already Locked Error"

Its even good to use tortoise svn cleanup, no need to use Ankh one in my case

Why does JPA have a @Transient annotation?

Purpose is different:

The transient keyword and @Transient annotation have two different purposes: one deals with serialization and one deals with persistence. As programmers, we often marry these two concepts into one, but this is not accurate in general. Persistence refers to the characteristic of state that outlives the process that created it. Serialization in Java refers to the process of encoding/decoding an object's state as a byte stream.

The transient keyword is a stronger condition than @Transient:

If a field uses the transient keyword, that field will not be serialized when the object is converted to a byte stream. Furthermore, since JPA treats fields marked with the transient keyword as having the @Transient annotation, the field will not be persisted by JPA either.

On the other hand, fields annotated @Transient alone will be converted to a byte stream when the object is serialized, but it will not be persisted by JPA. Therefore, the transient keyword is a stronger condition than the @Transient annotation.

Example

This begs the question: Why would anyone want to serialize a field that is not persisted to the application's database? The reality is that serialization is used for more than just persistence. In an Enterprise Java application there needs to be a mechanism to exchange objects between distributed components; serialization provides a common communication protocol to handle this. Thus, a field may hold critical information for the purpose of inter-component communication; but that same field may have no value from a persistence perspective.

For example, suppose an optimization algorithm is run on a server, and suppose this algorithm takes several hours to complete. To a client, having the most up-to-date set of solutions is important. So, a client can subscribe to the server and receive periodic updates during the algorithm's execution phase. These updates are provided using the ProgressReport object:

@Entity
public class ProgressReport implements Serializable{

    private static final long serialVersionUID = 1L;

    @Transient
    long estimatedMinutesRemaining;
    String statusMessage;
    Solution currentBestSolution;

}

The Solution class might look like this:

@Entity
public class Solution implements Serializable{

    private static final long serialVersionUID = 1L;

    double[][] dataArray;
    Properties properties;
}

The server persists each ProgressReport to its database. The server does not care to persist estimatedMinutesRemaining, but the client certainly cares about this information. Therefore, the estimatedMinutesRemaining is annotated using @Transient. When the final Solution is located by the algorithm, it is persisted by JPA directly without using a ProgressReport.

Change keystore password from no password to a non blank password

this way worked better for me:

echo y | keytool -storepasswd -storepass 123456 -keystore /tmp/IT-Root-CA.keystore -import -alias IT-Root-CA -file /etc/pki/ca-trust/source/anchors/IT-Root-CA.crt

machine running:

[root@rhel80-68]# cat /etc/redhat-release 
Red Hat Enterprise Linux release 8.1 (Ootpa)

How to create a trie in Python

Unwind is essentially correct that there are many different ways to implement a trie; and for a large, scalable trie, nested dictionaries might become cumbersome -- or at least space inefficient. But since you're just getting started, I think that's the easiest approach; you could code up a simple trie in just a few lines. First, a function to construct the trie:

>>> _end = '_end_'
>>> 
>>> def make_trie(*words):
...     root = dict()
...     for word in words:
...         current_dict = root
...         for letter in word:
...             current_dict = current_dict.setdefault(letter, {})
...         current_dict[_end] = _end
...     return root
... 
>>> make_trie('foo', 'bar', 'baz', 'barz')
{'b': {'a': {'r': {'_end_': '_end_', 'z': {'_end_': '_end_'}}, 
             'z': {'_end_': '_end_'}}}, 
 'f': {'o': {'o': {'_end_': '_end_'}}}}

If you're not familiar with setdefault, it simply looks up a key in the dictionary (here, letter or _end). If the key is present, it returns the associated value; if not, it assigns a default value to that key and returns the value ({} or _end). (It's like a version of get that also updates the dictionary.)

Next, a function to test whether the word is in the trie:

>>> def in_trie(trie, word):
...     current_dict = trie
...     for letter in word:
...         if letter not in current_dict:
...             return False
...         current_dict = current_dict[letter]
...     return _end in current_dict
... 
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'baz')
True
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'barz')
True
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'barzz')
False
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'bart')
False
>>> in_trie(make_trie('foo', 'bar', 'baz', 'barz'), 'ba')
False

I'll leave insertion and removal to you as an exercise.

Of course, Unwind's suggestion wouldn't be much harder. There might be a slight speed disadvantage in that finding the correct sub-node would require a linear search. But the search would be limited to the number of possible characters -- 27 if we include _end. Also, there's nothing to be gained by creating a massive list of nodes and accessing them by index as he suggests; you might as well just nest the lists.

Finally, I'll add that creating a directed acyclic word graph (DAWG) would be a bit more complex, because you have to detect situations in which your current word shares a suffix with another word in the structure. In fact, this can get rather complex, depending on how you want to structure the DAWG! You may have to learn some stuff about Levenshtein distance to get it right.

I can't access http://localhost/phpmyadmin/

I am using Linux Mint : After installing LAMP along with PhpMyAdmin, I linked both the configuration files of Apache and PhpMyAdmin. It did the trick. Following are the commands.

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin.conf

sudo /etc/init.d/apache2 reload

Abstract variables in Java?

Change the code to:

public abstract class clsAbstractTable {
  protected String TAG;
  public abstract void init();
}

public class clsContactGroups extends clsAbstractTable {
  public String doSomething() {
    return TAG + "<something else>";
  }
}

That way, all of the classes who inherit this class will have this variable. You can do 200 subclasses and still each one of them will have this variable.

Side note: do not use CAPS as variable name; common wisdom is that all caps identifiers refer to constants, i.e. non-changeable pieces of data.

How can I determine if a variable is 'undefined' or 'null'?

I've just had this problem i.e. checking if an object is null.
I simply use this:

if (object) {
    // Your code
}

For example:

if (document.getElementById("enterJob")) {
    document.getElementById("enterJob").className += ' current';
}

How to enable GZIP compression in IIS 7.5

This is more an add-on to the best answer above (GZip Compression can be enabled directly through IIS) which is correct if your running IIS on Windows desktop however...

If your running IIS on Windows Server, this content compression feature is found in a different place to desktop Windows (not in programs and features in Control Panel). First open "Server Manager" then click Manage -> "Add Roles & Features" then keep clicking NEXT (make sure you select the correct server when you see the list of servers if your managing multiple servers from this instance) until you get to SERVER ROLES, scroll down to and open "Web Server (IIS)..." then "Web Server" then "Performance" then tick "Dynamic Content Compression" then click INSTALL. I tested this on Server 2016 Standard so there may be slight differences if your on an earlier version of Server.

Then follow the instructions from Testing - Check if GZIP Compression is Enabled

how to get request path with express req object

In some cases you should use:

req.path

This gives you the path, instead of the complete requested URL. For example, if you are only interested in which page the user requested and not all kinds of parameters the url:

/myurl.htm?allkinds&ofparameters=true

req.path will give you:

/myurl.html

how to destroy bootstrap modal window completely?

This completely removes the modal from the DOM , is working for the "appended" modals as well .

#pickoptionmodal is the id of my modal window.

$(document).on('hidden.bs.modal','#pickoptionmodal',function(e){

e.preventDefault();

$("#pickoptionmodal").remove();

});

Remove first Item of the array (like popping from stack)

There is a function called shift(). It will remove the first element of your array.

There is some good documentation and examples.

Locate current file in IntelliJ

In Intellij Idea Community edition 2020.1 :

  1. Right click on project header
  2. Select 'Always Select Opened File'

enter image description here

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

I have a maths degree from Oxford too! It took me a while to 'get' the new collections stuff. But I like it a lot now that I do. In fact, the typing of 'map' was one of the first big things that bugged me in 2.7 (perhaps since the first thing I did was subclass one of the collection classes).

Reading Martin's paper on the new 2.8 collections really helped explain the use of implicits, but yes the documentation itself definitely needs to do a better job of explaining the role of different kind of implicits within method signatures of core APIs.

My main concern is more this: when is 2.8 going to be released? When will the bug reports stop coming in for it? have scala team bitten off more than they can chew with 2.8 / tried to change too much at once?

I'd really like to see 2.8 stabilised for release as a priority before adding anything else new at all, and wonder (while watching from the sidelines) if some improvements could be made to the way the development roadmap for the scala compiler is managed.

Can you delete multiple branches in one command with Git?

If you really need clean all of your branches, try

git branch -d $(git branch)

It will delete all your local merged branches except the one you're currently checking in.

It's a good way to make your local clean

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

Eclipse DDMS error "Can't bind to local 8600 for debugger"

Running two instances of adb (eg eclipse debugger and android studio) at same time causes conflicts as this too

How to compare two floating point numbers in Bash?

I used the answers from here and put them in a function, you can use it like this:

is_first_floating_number_bigger 1.5 1.2
result="${__FUNCTION_RETURN}"

Once called, echo $result will be 1 in this case, otherwise 0.

The function:

is_first_floating_number_bigger () {
    number1="$1"
    number2="$2"

    [ ${number1%.*} -eq ${number2%.*} ] && [ ${number1#*.} \> ${number2#*.} ] || [ ${number1%.*} -gt ${number2%.*} ];
    result=$?
    if [ "$result" -eq 0 ]; then result=1; else result=0; fi

    __FUNCTION_RETURN="${result}"
}

Or a version with debug output:

is_first_floating_number_bigger () {
    number1="$1"
    number2="$2"

    echo "... is_first_floating_number_bigger: comparing ${number1} with ${number2} (to check if the first one is bigger)"

    [ ${number1%.*} -eq ${number2%.*} ] && [ ${number1#*.} \> ${number2#*.} ] || [ ${number1%.*} -gt ${number2%.*} ];
    result=$?
    if [ "$result" -eq 0 ]; then result=1; else result=0; fi

    echo "... is_first_floating_number_bigger: result is: ${result}"

    if [ "$result" -eq 0 ]; then
        echo "... is_first_floating_number_bigger: ${number1} is not bigger than ${number2}"
    else
        echo "... is_first_floating_number_bigger: ${number1} is bigger than ${number2}"
    fi

    __FUNCTION_RETURN="${result}"
}

Just save the function in a separated .sh file and include it like this:

. /path/to/the/new-file.sh

How to return multiple objects from a Java method?

As I see it there are really three choices here and the solution depends on the context. You can choose to implement the construction of the name in the method that produces the list. This is the choice you've chosen, but I don't think it is the best one. You are creating a coupling in the producer method to the consuming method that doesn't need to exist. Other callers may not need the extra information and you would be calculating extra information for these callers.

Alternatively, you could have the calling method calculate the name. If there is only one caller that needs this information, you can stop there. You have no extra dependencies and while there is a little extra calculation involved, you've avoided making your construction method too specific. This is a good trade-off.

Lastly, you could have the list itself be responsible for creating the name. This is the route I would go if the calculation needs to be done by more than one caller. I think this puts the responsibility for the creation of the names with the class that is most closely related to the objects themselves.

In the latter case, my solution would be to create a specialized List class that returns a comma-separated string of the names of objects that it contains. Make the class smart enough that it constructs the name string on the fly as objects are added and removed from it. Then return an instance of this list and call the name generation method as needed. Although it may be almost as efficient (and simpler) to simply delay calculation of the names until the first time the method is called and store it then (lazy loading). If you add/remove an object, you need only remove the calculated value and have it get recalculated on the next call.

Remove CSS class from element with JavaScript (no jQuery)

Edit

Okay, complete re-write. It's been a while, I've learned a bit and the comments have helped.

Node.prototype.hasClass = function (className) {
    if (this.classList) {
        return this.classList.contains(className);
    } else {
        return (-1 < this.className.indexOf(className));
    }
};

Node.prototype.addClass = function (className) {
    if (this.classList) {
        this.classList.add(className);
    } else if (!this.hasClass(className)) {
        var classes = this.className.split(" ");
        classes.push(className);
        this.className = classes.join(" ");
    }
    return this;
};

Node.prototype.removeClass = function (className) {
    if (this.classList) {
        this.classList.remove(className);
    } else {
        var classes = this.className.split(" ");
        classes.splice(classes.indexOf(className), 1);
        this.className = classes.join(" ");
    }
    return this;
};


Old Post
I was just working with something like this. Here's a solution I came up with...

// Some browsers don't have a native trim() function
if(!String.prototype.trim) {
    Object.defineProperty(String.prototype,'trim', {
        value: function() {
            return this.replace(/^\s+|\s+$/g,'');
        },
        writable:false,
        enumerable:false,
        configurable:false
    });
}
// addClass()
// first checks if the class name already exists, if not, it adds the class.
Object.defineProperty(Node.prototype,'addClass', {
    value: function(c) {
        if(this.className.indexOf(c)<0) {
            this.className=this.className+=' '+c;
        }
        return this;
    },
    writable:false,
    enumerable:false,
    configurable:false
});
// removeClass()
// removes the class and cleans up the className value by changing double 
// spacing to single spacing and trimming any leading or trailing spaces
Object.defineProperty(Node.prototype,'removeClass', {
    value: function(c) {
        this.className=this.className.replace(c,'').replace('  ',' ').trim();
        return this;
    },
    writable:false,
    enumerable:false,
    configurable:false
});

Now you can call myElement.removeClass('myClass')

or chain it: myElement.removeClass("oldClass").addClass("newClass");

python's re: return True if string contains regex pattern

Match objects are always true, and None is returned if there is no match. Just test for trueness.

Code:

>>> st = 'bar'
>>> m = re.match(r"ba[r|z|d]",st)
>>> if m:
...     m.group(0)
...
'bar'

Output = bar

If you want search functionality

>>> st = "bar"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m is not None:
...     m.group(0)
...
'bar'

and if regexp not found than

>>> st = "hello"
>>> m = re.search(r"ba[r|z|d]",st)
>>> if m:
...     m.group(0)
... else:
...   print "no match"
...
no match

As @bukzor mentioned if st = foo bar than match will not work. So, its more appropriate to use re.search.

Can you force Vue.js to reload/re-render?

Please read this http://michaelnthiessen.com/force-re-render/

The horrible way: reloading the entire page
The terrible way: using the v-if hack
The better way: using Vue’s built-in forceUpdate method
The best way: key-changing on your component

<template>
   <component-to-re-render :key="componentKey" />
</template>

<script>
 export default {
  data() {
    return {
      componentKey: 0,
    };
  },
  methods: {
    forceRerender() {
      this.componentKey += 1;  
    }
  }
 }
</script>

I also use watch: in some situations.

How do I specify new lines on Python, when writing on files?

As mentioned in other answers: "The new line character is \n. It is used inside a string".

I found the most simple and readable way is to use the "format" function, using nl as the name for a new line, and break the string you want to print to the exact format you going to print it:

python2:

print("line1{nl}"
      "line2{nl}"
      "line3".format(nl="\n"))

python3:

nl = "\n"
print(f"line1{nl}"
      f"line2{nl}"
      f"line3")

That will output:

line1
line2
line3

This way it performs the task, and also gives high readability of the code :)

Catching an exception while using a Python 'with' statement

from __future__ import with_statement

try:
    with open( "a.txt" ) as f :
        print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
    print 'oops'

If you want different handling for errors from the open call vs the working code you could do:

try:
    f = open('foo.txt')
except IOError:
    print('error')
else:
    with f:
        print f.readlines()

What is the best way to seed a database in Rails?

Using seeds.rb file or FactoryBot is great, but these are respectively great for fixed data structures and testing.

The seedbank gem might give you more control and modularity to your seeds. It inserts rake tasks and you can also define dependencies between your seeds. Your rake task list will have these additions (e.g.):

rake db:seed                    # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/ENVIRONMENT/*.seeds.rb. ENVIRONMENT is the current environment in Rails.env.
rake db:seed:bar                # Load the seed data from db/seeds/bar.seeds.rb
rake db:seed:common             # Load the seed data from db/seeds.rb and db/seeds/*.seeds.rb.
rake db:seed:development        # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/development/*.seeds.rb.
rake db:seed:development:users  # Load the seed data from db/seeds/development/users.seeds.rb
rake db:seed:foo                # Load the seed data from db/seeds/foo.seeds.rb
rake db:seed:original           # Load the seed data from db/seeds.rb

Properly Handling Errors in VBA (Excel)

You've got one truly marvelous answer from ray023, but your comment that it's probably overkill is apt. For a "lighter" version....

Block 1 is, IMHO, bad practice. As already pointed out by osknows, mixing error-handling with normal-path code is Not Good. For one thing, if a new error is thrown while there's an Error condition in effect you will not get an opportunity to handle it (unless you're calling from a routine that also has an error handler, where the execution will "bubble up").

Block 2 looks like an imitation of a Try/Catch block. It should be okay, but it's not The VBA Way. Block 3 is a variation on Block 2.

Block 4 is a bare-bones version of The VBA Way. I would strongly advise using it, or something like it, because it's what any other VBA programmer inherting the code will expect. Let me present a small expansion, though:

Private Sub DoSomething()
On Error GoTo ErrHandler

'Dim as required

'functional code that might throw errors

ExitSub:
    'any always-execute (cleanup?) code goes here -- analagous to a Finally block.
    'don't forget to do this -- you don't want to fall into error handling when there's no error
    Exit Sub

ErrHandler:
    'can Select Case on Err.Number if there are any you want to handle specially

    'display to user
    MsgBox "Something's wrong: " & vbCrLf & Err.Description

    'or use a central DisplayErr routine, written Public in a Module
    DisplayErr Err.Number, Err.Description

    Resume ExitSub
    Resume
End Sub

Note that second Resume. This is a trick I learned recently: It will never execute in normal processing, since the Resume <label> statement will send the execution elsewhere. It can be a godsend for debugging, though. When you get an error notification, choose Debug (or press Ctl-Break, then choose Debug when you get the "Execution was interrupted" message). The next (highlighted) statement will be either the MsgBox or the following statement. Use "Set Next Statement" (Ctl-F9) to highlight the bare Resume, then press F8. This will show you exactly where the error was thrown.

As to your objection to this format "jumping around", A) it's what VBA programmers expect, as stated previously, & B) your routines should be short enough that it's not far to jump.

MySQL Daemon Failed to Start - centos 6

Try restarting apache sudo service httpd restart. Worked for me.

how to get domain name from URL

For a certain purpose I did this quick Python function yesterday. It returns domain from URL. It's quick and doesn't need any input file listing stuff. However, I don't pretend it works in all cases, but it really does the job I needed for a simple text mining script.

Output looks like this :

http://www.google.co.uk => google.co.uk
http://24.media.tumblr.com/tumblr_m04s34rqh567ij78k_250.gif => tumblr.com

def getDomain(url):    
        parts = re.split("\/", url)
        match = re.match("([\w\-]+\.)*([\w\-]+\.\w{2,6}$)", parts[2]) 
        if match != None:
            if re.search("\.uk", parts[2]): 
                match = re.match("([\w\-]+\.)*([\w\-]+\.[\w\-]+\.\w{2,6}$)", parts[2])
            return match.group(2)
        else: return ''  

Seems to work pretty well.
However, it has to be modified to remove domain extensions on output as you wished.

Accessing the web page's HTTP Headers in JavaScript

Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been repeatedly asked, too, because some people would like to get the actual response headers of the original page request without issuing another one.


For AJAX Requests:

If an HTTP request is made over AJAX, it is possible to get the response headers with the getAllResponseHeaders() method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the fetchSimilarHeaders() function below. Note that this is a work-around to the problem that won't be reliable for some applications.

myXMLHttpRequest.getAllResponseHeaders();

This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.


Getting header values from the Initial Page Request:

This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the current page (i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.

The following are a few suggestions for getting around that problem.


1. Requests on Resources which are largely static

If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.

function fetchSimilarHeaders (callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE) {
            //
            // The following headers may often be similar
            // to those of the original page request...
            //
            if (callback && typeof callback === 'function') {
                callback(request.getAllResponseHeaders());
            }
        }
    };

    //
    // Re-request the same page (document.location)
    // We hope to get the same or similar response headers to those which 
    // came with the current page, but we have no guarantee.
    // Since we are only after the headers, a HEAD request may be sufficient.
    //
    request.open('HEAD', document.location, true);
    request.send(null);
}

This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.


2. Make Inferences

There are some BOM properties (Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g. navigator.userAgent is set to the value of the HTTP User-Agent header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.


3. Stash them

If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.

Remove all newlines from inside a string

strip() returns the string with leading and trailing whitespaces(by default) removed.

So it would turn " Hello World " to "Hello World", but it won't remove the \n character as it is present in between the string.

Try replace().

str = "Hello \n World"
str2 = str.replace('\n', '')
print str2

How to load a resource from WEB-INF directory of a web archive

Use the getResourceAsStream() method on the ServletContext object, e.g.

servletContext.getResourceAsStream("/WEB-INF/myfile");

How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?

EDITED: If you're inside a Servlet object, then call getServletContext(). If you're in JSP, use the predefined variable application.

How can I make text appear on next line instead of overflowing?

Just add

white-space: initial;

to the text, a line text will come automatically in the next line.

How to change the floating label color of TextInputLayout

I tried using android:textColorHint in the android.support.design.widget.TextInputLayout it works fine.

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColorHint="@color/colorAccent">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Hello"
                android:imeActionLabel="Hello"
                android:imeOptions="actionUnspecified"
                android:maxLines="1"
                android:singleLine="true"/>

        </android.support.design.widget.TextInputLayout>

How to check edittext's text is email address or not?

In your case you can use the android.util.Patterns package.

EditText email = (EditText)findViewById(R.id.user_email);

if(Patterns.EMAIL_ADDRESS.matcher(email.getText().toString()).matches())
    Toast.makeText(this, "Email is VALID.", Toast.LENGTH_SHORT).show();
else
    Toast.makeText(this, "Email is INVALID.", Toast.LENGTH_SHORT).show();

How to read a value from the Windows registry

Here is some pseudo-code to retrieve the following:

  1. If a registry key exists
  2. What the default value is for that registry key
  3. What a string value is
  4. What a DWORD value is

Example code:

Include the library dependency: Advapi32.lib

HKEY hKey;
LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey);
bool bExistsAndSuccess (lRes == ERROR_SUCCESS);
bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND);
std::wstring strValueOfBinDir;
std::wstring strKeyDefaultValue;
GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad");
GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad");

LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue)
{
    nValue = nDefaultValue;
    DWORD dwBufferSize(sizeof(DWORD));
    DWORD nResult(0);
    LONG nError = ::RegQueryValueExW(hKey,
        strValueName.c_str(),
        0,
        NULL,
        reinterpret_cast<LPBYTE>(&nResult),
        &dwBufferSize);
    if (ERROR_SUCCESS == nError)
    {
        nValue = nResult;
    }
    return nError;
}


LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue)
{
    DWORD nDefValue((bDefaultValue) ? 1 : 0);
    DWORD nResult(nDefValue);
    LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue);
    if (ERROR_SUCCESS == nError)
    {
        bValue = (nResult != 0) ? true : false;
    }
    return nError;
}


LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue)
{
    strValue = strDefaultValue;
    WCHAR szBuffer[512];
    DWORD dwBufferSize = sizeof(szBuffer);
    ULONG nError;
    nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
    if (ERROR_SUCCESS == nError)
    {
        strValue = szBuffer;
    }
    return nError;
}

How to undo "git commit --amend" done instead of "git commit"

You can do below to undo your git commit —amend

  1. git reset --soft HEAD^
  2. git checkout files_from_old_commit_on_branch
  3. git pull origin your_branch_name

====================================

Now your changes are as per previous. So you are done with the undo for git commit —amend

Now you can do git push origin <your_branch_name>, to push to the branch.

Is it correct to use DIV inside FORM?

It is totally fine .

The form will submit only its input type controls ( *also Textarea , Select , etc...).

You have nothing to worry about a div within a form.

Winforms TableLayoutPanel adding rows programmatically

I just did this last week. Set the GrowStyle on the TableLayoutPanel to AddRows or AddColumns, then your code should work:

// Adds "myControl" to the first column of each row
myTableLayoutPanel.Controls.Add(myControl1, 0 /* Column Index */, 0 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl2, 0 /* Column Index */, 1 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl3, 0 /* Column Index */, 2 /* Row index */);

Here is some working code that seems similar to what you are doing:

    private Int32 tlpRowCount = 0;

    private void BindAddress()
    {
        Addlabel(Addresses.Street);
        if (!String.IsNullOrEmpty(Addresses.Street2))
        {
            Addlabel(Addresses.Street2);
        }
        Addlabel(Addresses.CityStateZip);
        if (!String.IsNullOrEmpty(Account.Country))
        {
            Addlabel(Address.Country);
        }
        Addlabel(String.Empty); // Notice the empty label...
    }

    private void Addlabel(String text)
    {            
        label = new Label();
        label.Dock = DockStyle.Fill;
        label.Text = text;
        label.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        tlpAddress.Controls.Add(label, 1, tlpRowCount);
        tlpRowCount++;
    }

The TableLayoutPanel always gives me fits with size. In my example above, I'm filing an address card that might grow or shrink depending on the account having an address line two, or a country. Because the last row, or column, of the table layout panel will stretch, I throw the empty label in there to force a new empty row, then everything lines up nicely.

Here is the designer code so you can see the table I start with:

        //
        // tlpAddress
        // 
        this.tlpAddress.AutoSize = true;
        this.tlpAddress.BackColor = System.Drawing.Color.Transparent;
        this.tlpAddress.ColumnCount = 2;
        this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 25F));
        this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
        this.tlpAddress.Controls.Add(this.pictureBox1, 0, 0);
        this.tlpAddress.Dock = System.Windows.Forms.DockStyle.Fill;
        this.tlpAddress.Location = new System.Drawing.Point(0, 0);
        this.tlpAddress.Name = "tlpAddress";
        this.tlpAddress.Padding = new System.Windows.Forms.Padding(3);
        this.tlpAddress.RowCount = 2;
        this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
        this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
        this.tlpAddress.Size = new System.Drawing.Size(220, 95);
        this.tlpAddress.TabIndex = 0;

Update my gradle dependencies in eclipse

You have to select "Refresh Dependencies" in the "Gradle" context menu that appears when you right-click the project in the Package Explorer.

How to pass optional parameters while omitting some other optional parameters?

You can do this without an interface.

class myClass{
  public error(message: string, title?: string, autoHideAfter? : number){
    //....
  }
}

use the ? operator as an optional parameter.

SameSite warning Chrome 77

Fixed by adding crossorigin to the script tag.

From: https://code.jquery.com/

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org

Insert text into textarea with jQuery

Here is a quick solution that works in jQuery 1.9+:

a) Get caret position:

function getCaret(el) {
        if (el.prop("selectionStart")) {
            return el.prop("selectionStart");
        } else if (document.selection) {
            el.focus();

            var r = document.selection.createRange();
            if (r == null) {
                return 0;
            }

            var re = el.createTextRange(),
                    rc = re.duplicate();
            re.moveToBookmark(r.getBookmark());
            rc.setEndPoint('EndToStart', re);

            return rc.text.length;
        }
        return 0;
    };

b) Append text at caret position:

function appendAtCaret($target, caret, $value) {
        var value = $target.val();
        if (caret != value.length) {
            var startPos = $target.prop("selectionStart");
            var scrollTop = $target.scrollTop;
            $target.val(value.substring(0, caret) + ' ' + $value + ' ' + value.substring(caret, value.length));
            $target.prop("selectionStart", startPos + $value.length);
            $target.prop("selectionEnd", startPos + $value.length);
            $target.scrollTop = scrollTop;
        } else if (caret == 0)
        {
            $target.val($value + ' ' + value);
        } else {
            $target.val(value + ' ' + $value);
        }
    };

c) Example

$('textarea').each(function() {
  var $this = $(this);
  $this.click(function() {
    //get caret position
    var caret = getCaret($this);

    //append some text
    appendAtCaret($this, caret, 'Some text');
  });
});

Android: No Activity found to handle Intent error? How it will resolve

in my case, i was sure that the action is correct, but i was passing wrong URL, i passed the website link without the http:// in it's beginning, so it caused the same issue, here is my manifest (part of it)

<activity
        android:name=".MyBrowser"
        android:label="MyBrowser Activity" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <action android:name="com.dsociety.activities.MyBrowser" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:scheme="http" />
        </intent-filter>
    </activity>

when i code the following, the same Exception is thrown at run time :

Intent intent = new Intent();
intent.setAction("com.dsociety.activities.MyBrowser");
intent.setData(Uri.parse("www.google.com"));    // should be http://www.google.com
startActivity(intent);

Installing R with Homebrew

If you run

xcode-select --install

you do you not need to install gcc through brew, and you will not have to waste time compiling gcc. See https://stackoverflow.com/a/24967219/2668545 for more details.

After that, you can simply do

brew tap homebrew/science
brew install Caskroom/cask/xquartz
brew install r

How can you check for a #hash in a URL using JavaScript?

Throwing this in here as a method for abstracting location properties from arbitrary URI-like strings. Although window.location instanceof Location is true, any attempt to invoke Location will tell you that it's an illegal constructor. You can still get to things like hash, query, protocol etc by setting your string as the href property of a DOM anchor element, which will then share all the address properties with window.location.

Simplest way of doing this is:

var a = document.createElement('a');
a.href = string;

string.hash;

For convenience, I wrote a little library that utilises this to replace the native Location constructor with one that will take strings and produce window.location-like objects: Location.js

Get viewport/window height in ReactJS

Using Hooks (React 16.8.0+)

Create a useWindowDimensions hook.

import { useState, useEffect } from 'react';

function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height
  };
}

export default function useWindowDimensions() {
  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return windowDimensions;
}

And after that you'll be able to use it in your components like this

const Component = () => {
  const { height, width } = useWindowDimensions();

  return (
    <div>
      width: {width} ~ height: {height}
    </div>
  );
}

Working example

Original answer

It's the same in React, you can use window.innerHeight to get the current viewport's height.

As you can see here

Format ints into string of hex

Just for completeness, using the modern .format() syntax:

>>> numbers = [1, 15, 255]
>>> ''.join('{:02X}'.format(a) for a in numbers)
'010FFF'

Calling stored procedure with return value

The version of EnterpriseLibrary on my machine had other parameters. This was working:

        SqlParameter retval = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
        retval.Direction = System.Data.ParameterDirection.ReturnValue;
        cmd.Parameters.Add(retval);
        db.ExecuteNonQuery(cmd);
        object o = cmd.Parameters["@ReturnValue"].Value;

How to fix: Error device not found with ADB.exe

How about:

Settings -> System -> Developer options -> Debugging -> turn on toggle for Wireless ADB debugging

or:

Revoke USB debugging authorizations

and try from the scratch.

Is it ok to use `any?` to check if an array is not empty?

Avoid any? for large arrays.

  • any? is O(n)
  • empty? is O(1)

any? does not check the length but actually scans the whole array for truthy elements.

static VALUE
rb_ary_any_p(VALUE ary)
{
  long i, len = RARRAY_LEN(ary);
  const VALUE *ptr = RARRAY_CONST_PTR(ary);

  if (!len) return Qfalse;
  if (!rb_block_given_p()) {
    for (i = 0; i < len; ++i) if (RTEST(ptr[i])) return Qtrue;
  }
  else {
    for (i = 0; i < RARRAY_LEN(ary); ++i) {
        if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qtrue;
    }
  }
  return Qfalse;
}

empty? on the other hand checks the length of the array only.

static VALUE
rb_ary_empty_p(VALUE ary)
{
  if (RARRAY_LEN(ary) == 0)
    return Qtrue;
  return Qfalse;
}

The difference is relevant if you have "sparse" arrays that start with lots of nil values, like for example an array that was just created.

How to specify a min but no max decimal using the range data annotation attribute?

How about something like this:

[Range(0.0, Double.MaxValue, ErrorMessage = "The field {0} must be greater than {1}.")]

That should do what you are looking for and you can avoid using strings.

PHP foreach loop through multidimensional array

$last = count($arr_nav) - 1;

foreach ($arr_nav as $i => $row)
{
    $isFirst = ($i == 0);
    $isLast = ($i == $last);

    echo ... $row['name'] ... $row['url'] ...;
}

Can you split a stream into two streams?

not exactly, but you may be able to accomplish what you need by invoking Collectors.groupingBy(). you create a new Collection, and can then instantiate streams on that new collection.

Javascript-Setting background image of a DIV via a function and function parameter

You need to concatenate your string.

document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';

The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.

I would even suggest creating the string separate:

function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
    var urlString = 'url(buttons/' + imagePrefix + '.png)';
    document.getElementById(tabName).style.backgroundImage =  urlString;
}

As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html

Stop embedded youtube iframe?

Unfortunately these API's evolve very fast. As of May 2015, the proposed solutions don't work anymore, as the player object has no stopVideo method.

A reliable solution is to be found in this page (1) and it works with an:

<iframe id="youtube_player" class="yt_player_iframe" width="640" height="360" src="http://www.youtube.com/embed/aHUBlv5_K8Y?enablejsapi=1&version=3&playerapiid=ytplayer"  allowfullscreen="true" allowscriptaccess="always" frameborder="0"></iframe>

and the following JS/jQuery code:

$('.yt_player_iframe').each(function(){
  this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
});

What is the best way to get all the divisors of a number?

I like Greg solution, but I wish it was more python like. I feel it would be faster and more readable; so after some time of coding I came out with this.

The first two functions are needed to make the cartesian product of lists. And can be reused whnever this problem arises. By the way, I had to program this myself, if anyone knows of a standard solution for this problem, please feel free to contact me.

"Factorgenerator" now returns a dictionary. And then the dictionary is fed into "divisors", who uses it to generate first a list of lists, where each list is the list of the factors of the form p^n with p prime. Then we make the cartesian product of those lists, and we finally use Greg' solution to generate the divisor. We sort them, and return them.

I tested it and it seem to be a bit faster than the previous version. I tested it as part of a bigger program, so I can't really say how much is it faster though.

Pietro Speroni (pietrosperoni dot it)

from math import sqrt


##############################################################
### cartesian product of lists ##################################
##############################################################

def appendEs2Sequences(sequences,es):
    result=[]
    if not sequences:
        for e in es:
            result.append([e])
    else:
        for e in es:
            result+=[seq+[e] for seq in sequences]
    return result


def cartesianproduct(lists):
    """
    given a list of lists,
    returns all the possible combinations taking one element from each list
    The list does not have to be of equal length
    """
    return reduce(appendEs2Sequences,lists,[])

##############################################################
### prime factors of a natural ##################################
##############################################################

def primefactors(n):
    '''lists prime factors, from greatest to smallest'''  
    i = 2
    while i<=sqrt(n):
        if n%i==0:
            l = primefactors(n/i)
            l.append(i)
            return l
        i+=1
    return [n]      # n is prime


##############################################################
### factorization of a natural ##################################
##############################################################

def factorGenerator(n):
    p = primefactors(n)
    factors={}
    for p1 in p:
        try:
            factors[p1]+=1
        except KeyError:
            factors[p1]=1
    return factors

def divisors(n):
    factors = factorGenerator(n)
    divisors=[]
    listexponents=[map(lambda x:k**x,range(0,factors[k]+1)) for k in factors.keys()]
    listfactors=cartesianproduct(listexponents)
    for f in listfactors:
        divisors.append(reduce(lambda x, y: x*y, f, 1))
    divisors.sort()
    return divisors



print divisors(60668796879)

P.S. it is the first time I am posting to stackoverflow. I am looking forward for any feedback.

git add remote branch

I am not sure if you are trying to create a remote branch from a local branch or vice versa, so I've outlined both scenarios as well as provided information on merging the remote and local branches.

Creating a remote called "github":

git remote add github git://github.com/jdoe/coolapp.git
git fetch github

List all remote branches:

git branch -r
  github/gh-pages
  github/master
  github/next
  github/pu

Create a new local branch (test) from a github's remote branch (pu):

git branch test github/pu
git checkout test

Merge changes from github's remote branch (pu) with local branch (test):

git fetch github
git checkout test
git merge github/pu

Update github's remote branch (pu) from a local branch (test):

git push github test:pu

Creating a new branch on a remote uses the same syntax as updating a remote branch. For example, create new remote branch (beta) on github from local branch (test):

git push github test:beta

Delete remote branch (pu) from github:

git push github :pu

Flex-box: Align last row to grid

Without any extra markup, just adding ::after worked for me specifying the width of the column.

.grid {
  display:flex;
  justify-content:space-between;
  flex-wrap:wrap;
}
.grid::after{
  content: '';
  width: 10em // Same width of .grid__element
}
.grid__element{
  width:10em;
}

With the HTML like this:

<div class=grid">
   <div class="grid__element"></div>
   <div class="grid__element"></div>
   <div class="grid__element"></div>
</div>

How do I show the changes which have been staged?

Think about the gitk tool also , provided with git and very useful to see the changes

Can I mask an input text in a bat file?

make a batch file that calls the one needed for invisible characters then make a shortcut for the batch file being called.

right click

properties

colors

text==black

background == black

apply

ok

hope thus helps you!!!!!!!!

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

I had the exact same problem in a project. The issue is that even though the fetch size might be small enough, the JDBCTemplate reads all the result of your query and maps it out in a huge list which might blow your memory. I ended up extending NamedParameterJdbcTemplate to create a function which returns a Stream of Object. That Stream is based on the ResultSet normally returned by JDBC but will pull data from the ResultSet only as the Stream requires it. This will work if you don't keep a reference of all the Object this Stream spits. I did inspire myself a lot on the implementation of org.springframework.jdbc.core.JdbcTemplate#execute(org.springframework.jdbc.core.ConnectionCallback). The only real difference has to do with what to do with the ResultSet. I ended up writing this function to wrap up the ResultSet:

private <T> Stream<T> wrapIntoStream(ResultSet rs, RowMapper<T> mapper) {
    CustomSpliterator<T> spliterator = new CustomSpliterator<T>(rs, mapper, Long.MAX_VALUE, NON-NULL | IMMUTABLE | ORDERED);
    Stream<T> stream = StreamSupport.stream(spliterator, false);
    return stream;
}
private static class CustomSpliterator<T> extends Spliterators.AbstractSpliterator<T> {
    // won't put code for constructor or properties here
    // the idea is to pull for the ResultSet and set into the Stream
    @Override
    public boolean tryAdvance(Consumer<? super T> action) {
        try {
            // you can add some logic to close the stream/Resultset automatically
            if(rs.next()) {
                T mapped = mapper.mapRow(rs, rowNumber++);
                action.accept(mapped);
                return true;
            } else {
                return false;
            }
        } catch (SQLException) {
            // do something with this Exception
        }
    }
}

you can add some logic to make that Stream "auto closable", otherwise don't forget to close it when you are done.

Using HTML5/Canvas/JavaScript to take in-browser screenshots

Your web app can now take a 'native' screenshot of the client's entire desktop using getUserMedia():

Have a look at this example:

https://www.webrtc-experiment.com/Pluginfree-Screen-Sharing/

The client will have to be using chrome (for now) and will need to enable screen capture support under chrome://flags.

android asynctask sending callbacks to ui

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

For example:

Your interface:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

Your Activity:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

EDIT

Since this answer got quite popular, I want to add some things.

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

How do I install opencv using pip?

Simply use this for the so far latest version 4.1.0.

pip install opencv-contrib-python==4.1.0.25

For default version use this:

pip install opencv-contrib-python

Excel: Use a cell value as a parameter for a SQL query

queryString = "SELECT name FROM user WHERE id=" & Worksheets("Sheet1").Range("D4").Value

How to get current html page title with javascript

Like this :

jQuery(document).ready(function () {
    var title = jQuery(this).attr('title');
});

works for IE, Firefox and Chrome.

Is it necessary to assign a string to a variable before comparing it to another?

Do I really have to create an NSString for "Wrong"?

No, why not just do:

if([statusString isEqualToString:@"Wrong"]){
    //doSomething;
}

Using @"" simply creates a string literal, which is a valid NSString.

Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?

Yes, you can do something like:

UILabel *label = ...;
if([someString isEqualToString:label.text]) {
    // Do stuff here 
}

jQuery get text as number

If anyone came here trying to do this with a decimal like me:

myFloat = parseFloat(myString);

If you just need an Int, that's well covered in the other answers.

Nth word in a string variable

A file containing some statements :

cat test.txt

Result :

This is the 1st Statement
This is the 2nd Statement
This is the 3rd Statement
This is the 4th Statement
This is the 5th Statement

So, to print the 4th word of this statement type :

cat test.txt |awk '{print $4}'

Output :

1st
2nd
3rd
4th
5th

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

Difference between java HH:mm and hh:mm on SimpleDateFormat

Actually the last one is not weird. Code is setting the timezone for working instead of working2.

SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss"); working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

kk goes from 1 to 24, HH from 0 to 23 and hh from 1 to 12 (AM/PM).

Fixing this error gives:

24:00:00
00:00:00
01:00:00

Regex for numbers only

Perhaps my method will help you.

    public static bool IsNumber(string s)
    {
        return s.All(char.IsDigit);
    }

Evaluate a string with a switch in C++

what about just have the option number:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s;
    int op;

    cin >> s >> op;
    switch (op) {
    case 1: break;
    case 2: break;
    default:
    }

    return 0;
}  

Dead simple example of using Multiprocessing Queue, Pool and Locking

The best solution for your problem is to utilize a Pool. Using Queues and having a separate "queue feeding" functionality is probably overkill.

Here's a slightly rearranged version of your program, this time with only 2 processes coralled in a Pool. I believe it's the easiest way to go, with minimal changes to original code:

import multiprocessing
import time

data = (
    ['a', '2'], ['b', '4'], ['c', '6'], ['d', '8'],
    ['e', '1'], ['f', '3'], ['g', '5'], ['h', '7']
)

def mp_worker((inputs, the_time)):
    print " Processs %s\tWaiting %s seconds" % (inputs, the_time)
    time.sleep(int(the_time))
    print " Process %s\tDONE" % inputs

def mp_handler():
    p = multiprocessing.Pool(2)
    p.map(mp_worker, data)

if __name__ == '__main__':
    mp_handler()

Note that mp_worker() function now accepts a single argument (a tuple of the two previous arguments) because the map() function chunks up your input data into sublists, each sublist given as a single argument to your worker function.

Output:

Processs a  Waiting 2 seconds
Processs b  Waiting 4 seconds
Process a   DONE
Processs c  Waiting 6 seconds
Process b   DONE
Processs d  Waiting 8 seconds
Process c   DONE
Processs e  Waiting 1 seconds
Process e   DONE
Processs f  Waiting 3 seconds
Process d   DONE
Processs g  Waiting 5 seconds
Process f   DONE
Processs h  Waiting 7 seconds
Process g   DONE
Process h   DONE

Edit as per @Thales comment below:

If you want "a lock for each pool limit" so that your processes run in tandem pairs, ala:

A waiting B waiting | A done , B done | C waiting , D waiting | C done, D done | ...

then change the handler function to launch pools (of 2 processes) for each pair of data:

def mp_handler():
    subdata = zip(data[0::2], data[1::2])
    for task1, task2 in subdata:
        p = multiprocessing.Pool(2)
        p.map(mp_worker, (task1, task2))

Now your output is:

 Processs a Waiting 2 seconds
 Processs b Waiting 4 seconds
 Process a  DONE
 Process b  DONE
 Processs c Waiting 6 seconds
 Processs d Waiting 8 seconds
 Process c  DONE
 Process d  DONE
 Processs e Waiting 1 seconds
 Processs f Waiting 3 seconds
 Process e  DONE
 Process f  DONE
 Processs g Waiting 5 seconds
 Processs h Waiting 7 seconds
 Process g  DONE
 Process h  DONE

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Android Studio AVD - Emulator: Process finished with exit code 1

Android make the default avd files in the C:\Users\[USERNAME]\.android directory. Just make sure you copy the avd folder from this directory C:\Users\[USERNAME]\.android to C:\Android\.android. My problem was resolved after doing this.

Invoking a jQuery function after .each() has completed

If you're willing to make it a couple of steps, this might work. It's dependent on the animations finishing in order, though. I don't think that should be a problem.

var elems = $(parentSelect).nextAll();
var lastID = elems.length - 1;

elems.each( function(i) {
    $(this).fadeOut(200, function() { 
        $(this).remove(); 
        if (i == lastID) {
           doMyThing();
        }
    });
});

How to write a comment in a Razor view?

This comment syntax should work for you:

@* enter comments here *@

Dictionary with list of strings as value

Just create a new array in your dictionary

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));

Plotting with C#

FWIW, you probably want to look at F# instead of C# in the context of technical computing because F# is specifically designed for that purpose. However, I developed my own commercial plotting library because I was not satisfied with anything freely available on .NET.

Best way to get the max value in a Spark dataframe column

In case some wonders how to do it using Scala (using Spark 2.0.+), here you go:

scala> df.createOrReplaceTempView("TEMP_DF")
scala> val myMax = spark.sql("SELECT MAX(x) as maxval FROM TEMP_DF").
    collect()(0).getInt(0)
scala> print(myMax)
117

List of enum values in java

This is a more generic solution, that can be use for any Enum object, so be free of used.

static public List<Object> constFromEnumToList(Class enumType) {
    List<Object> nueva = new ArrayList<Object>();
    if (enumType.isEnum()) {
        try {
            Class<?> cls = Class.forName(enumType.getCanonicalName());
            Object[] consts = cls.getEnumConstants();
            nueva.addAll(Arrays.asList(consts));
        } catch (ClassNotFoundException e) {
            System.out.println("No se localizo la clase");
        }
    }
    return nueva;
}

Now you must call this way:

constFromEnumToList(MiEnum.class);

pop/remove items out of a python tuple

ok I figured out a crude way of doing it.

I store the "n" value in the for loop when condition is satisfied in a list (lets call it delList) then do the following:

    for ii in sorted(delList, reverse=True):
    tupleX.pop(ii)

Any other suggestions are welcome too.

Round double in two decimal places in C#?

you can try one from below.there are many way for this.

1. 
 value=Math.Round(123.4567, 2, MidpointRounding.AwayFromZero) //"123.46"
2.
 inputvalue=Math.Round(123.4567, 2)  //"123.46"
3. 
 String.Format("{0:0.00}", 123.4567);      // "123.46"
4. 
string.Format("{0:F2}", 123.456789);     //123.46
string.Format("{0:F3}", 123.456789);     //123.457
string.Format("{0:F4}", 123.456789);     //123.4568

ResultSet exception - before start of result set

You need to move the pointer to the first row, before asking for data:

result.beforeFirst();
result.next();
String foundType = result.getString(1);

How do I set the background color of Excel cells using VBA?

or alternatively you could not bother coding for it and use the 'conditional formatting' function in Excel which will set the background colour and font colour based on cell value.

There are only two variables here so set the default to yellow and then overwrite when the value is greater than or less than your threshold values.

Array length in angularjs returns undefined

Make it like this:

$scope.users.data.length;

CMake does not find Visual C++ compiler

In my case there was an environment variable set which was the reason for this error. The problem was solved after deleting cxx_flags from the environment variables.

Why is php not running?

When installing Apache and PHP under Ubuntu 14.04, I needed to specifically enable php configs by issuing a2enmod php5-cgi

"SDK Platform Tools component is missing!"

Before update SDK components, check in Android SDK Manager ? Tools ? Options and set HTTP proxy and port if it is set in local LAN.

Is it possible to use Java 8 for Android development?

Follow this link for new updates. Use Java 8 language features

Old Answer

As of Android N preview release Android support limited features of Java 8 see Java 8 Language Features

To start using these features, you need to download and set up Android Studio 2.1 and the Android N Preview SDK, which includes the required Jack toolchain and updated Android Plugin for Gradle. If you haven't yet installed the Android N Preview SDK, see Set Up to Develop for Android N.

Supported Java 8 Language Features and APIs

Android does not currently support all Java 8 language features. However, the following features are now available when developing apps targeting the Android N Preview:

Default and static interface methods

Lambda expressions (also available on API level 23 and lower)

Repeatable annotations

Method References (also available on API level 23 and lower)

There are some additional Java 8 features which Android support, you can see complete detail from Java 8 Language Features

Update

Note: The Android N bases its implementation of lambda expressions on anonymous classes. This approach allows them to be backwards compatible and executable on earlier versions of Android. To test lambda expressions on earlier versions, remember to go to your build.gradle file, and set compileSdkVersion and targetSdkVersion to 23 or lower.

Update 2

Now Android studio 3.0 stable release support Java 8 libraries and Java 8 language features (without the Jack compiler).

Android Studio: Module won't show up in "Edit Configuration"

Make sure your build.gradle is

apply plugin: 'com.android.application'

not

apply plugin: 'com.android.library'

After you have changed, please sync your gradle again.

enter image description here

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

How to show soft-keyboard when edittext is focused

For fragment, sure its working:

 displayName = (EditText) view.findViewById(R.id.displayName);
    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

DB2 Query to retrieve all table names for a given schema

Using the DB2 commands (no SQL) there is the possibility of executing

db2 LIST TABLES FOR ALL

This shows all the tables in all the schemas in the database.

ref: show all tables in DB2 using the LIST command

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

SQL Server SELECT into existing table

It would work as given below :

insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration 
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""

Difference between List, List<?>, List<T>, List<E>, and List<Object>

Let us talk about them in the context of Java history ;

  1. List:

List means it can include any Object. List was in the release before Java 5.0; Java 5.0 introduced List, for backward compatibility.

List list=new  ArrayList();
list.add(anyObject);
  1. List<?>:

? means unknown Object not any Object; the wildcard ? introduction is for solving the problem built by Generic Type; see wildcards; but this also causes another problem:

Collection<?> c = new ArrayList<String>();
c.add(new Object()); // Compile time error
  1. List< T> List< E>

Means generic Declaration at the premise of none T or E type in your project Lib.

  1. List< Object> means generic parameterization.

Best way to replace multiple characters in a string?

Are you always going to prepend a backslash? If so, try

import re
rx = re.compile('([&#])')
#                  ^^ fill in the characters here.
strs = rx.sub('\\\\\\1', strs)

It may not be the most efficient method but I think it is the easiest.

Change the background color of CardView programmatically

The way it's set in the initialize method uses the protected RoundRectDrawable class, like so:

RoundRectDrawable backgroundDrawable = new RoundRectDrawable(backgroundColor, cardView.getRadius());
cardView.setBackgroundDrawable(backgroundDrawable);

It's not pretty, but you can extend that class. Something like:

package android.support.v7.widget;

public class MyRoundRectDrawable extends RoundRectDrawable {

    public MyRoundRectDrawable(int backgroundColor, float radius) {
        super(backgroundColor, radius);
    }

}

then:

final MyRoundRectDrawable backgroundDrawable = new MyRoundRectDrawable(bgColor,
            mCardView.getRadius());
mCardView.setBackgroundDrawable(backgroundDrawable);

EDIT

This won't give you the shadow on < API 21, so you'd have to do the same with RoundRectDrawableWithShadow.

There doesn't appear to be a better way to do this.

Change WPF window background image in C# code

img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);

Copy files to network computers on windows command line

Why for? What do you want to iterate? Try this.

call :cpy pc-name-1
call :cpy pc-name-2
...

:cpy
net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

Here is the content of the file MessageBoxManager.cs

#pragma warning disable 0618

using System;

using System.Text;

using System.Runtime.InteropServices;

using System.Security.Permissions;

[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)]

namespace System.Windows.Forms

{

    public class MessageBoxManager
    {
        private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
        private delegate bool EnumChildProc(IntPtr hWnd, IntPtr lParam);

        private const int WH_CALLWNDPROCRET = 12;
        private const int WM_DESTROY = 0x0002;
        private const int WM_INITDIALOG = 0x0110;
        private const int WM_TIMER = 0x0113;
        private const int WM_USER = 0x400;
        private const int DM_GETDEFID = WM_USER + 0;

        private const int MBOK = 1;
        private const int MBCancel = 2;
        private const int MBAbort = 3;
        private const int MBRetry = 4;
        private const int MBIgnore = 5;
        private const int MBYes = 6;
        private const int MBNo = 7;


        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

        [DllImport("user32.dll")]
        private static extern int UnhookWindowsHookEx(IntPtr idHook);

        [DllImport("user32.dll")]
        private static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", EntryPoint = "GetWindowTextLengthW", CharSet = CharSet.Unicode)]
        private static extern int GetWindowTextLength(IntPtr hWnd);

        [DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);

        [DllImport("user32.dll")]
        private static extern int EndDialog(IntPtr hDlg, IntPtr nResult);

        [DllImport("user32.dll")]
        private static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildProc lpEnumFunc, IntPtr lParam);

        [DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)]
        private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        [DllImport("user32.dll")]
        private static extern int GetDlgCtrlID(IntPtr hwndCtl);

        [DllImport("user32.dll")]
        private static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);

        [DllImport("user32.dll", EntryPoint = "SetWindowTextW", CharSet = CharSet.Unicode)]
        private static extern bool SetWindowText(IntPtr hWnd, string lpString);


        [StructLayout(LayoutKind.Sequential)]
        public struct CWPRETSTRUCT
        {
            public IntPtr lResult;
            public IntPtr lParam;
            public IntPtr wParam;
            public uint   message;
            public IntPtr hwnd;
        };

        private static HookProc hookProc;
        private static EnumChildProc enumProc;
        [ThreadStatic]
        private static IntPtr hHook;
        [ThreadStatic]
        private static int nButton;

        /// <summary>
        /// OK text
        /// </summary>
        public static string OK = "&OK";
        /// <summary>
        /// Cancel text
        /// </summary>
        public static string Cancel = "&Cancel";
        /// <summary>
        /// Abort text
        /// </summary>
        public static string Abort = "&Abort";
        /// <summary>
        /// Retry text
        /// </summary>
        public static string Retry = "&Retry";
        /// <summary>
        /// Ignore text
        /// </summary>
        public static string Ignore = "&Ignore";
        /// <summary>
        /// Yes text
        /// </summary>
        public static string Yes = "&Yes";
        /// <summary>
        /// No text
        /// </summary>
        public static string No = "&No";

        static MessageBoxManager()
        {
            hookProc = new HookProc(MessageBoxHookProc);
            enumProc = new EnumChildProc(MessageBoxEnumProc);
            hHook = IntPtr.Zero;
        }

        /// <summary>
        /// Enables MessageBoxManager functionality
        /// </summary>
        /// <remarks>
        /// MessageBoxManager functionality is enabled on current thread only.
        /// Each thread that needs MessageBoxManager functionality has to call this method.
        /// </remarks>
        public static void Register()
        {
            if (hHook != IntPtr.Zero)
                throw new NotSupportedException("One hook per thread allowed.");
            hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
        }

        /// <summary>
        /// Disables MessageBoxManager functionality
        /// </summary>
        /// <remarks>
        /// Disables MessageBoxManager functionality on current thread only.
        /// </remarks>
        public static void Unregister()
        {
            if (hHook != IntPtr.Zero)
            {
                UnhookWindowsHookEx(hHook);
                hHook = IntPtr.Zero;
            }
        }

        private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode < 0)
                return CallNextHookEx(hHook, nCode, wParam, lParam);

            CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
            IntPtr hook = hHook;

            if (msg.message == WM_INITDIALOG)
            {
                int nLength = GetWindowTextLength(msg.hwnd);
                StringBuilder className = new StringBuilder(10);
                GetClassName(msg.hwnd, className, className.Capacity);
                if (className.ToString() == "#32770")
                {
                    nButton = 0;
                    EnumChildWindows(msg.hwnd, enumProc, IntPtr.Zero);
                    if (nButton == 1)
                    {
                        IntPtr hButton = GetDlgItem(msg.hwnd, MBCancel);
                        if (hButton != IntPtr.Zero)
                            SetWindowText(hButton, OK);
                    }
                }
            }

            return CallNextHookEx(hook, nCode, wParam, lParam);
        }

        private static bool MessageBoxEnumProc(IntPtr hWnd, IntPtr lParam)
        {
            StringBuilder className = new StringBuilder(10);
            GetClassName(hWnd, className, className.Capacity);
            if (className.ToString() == "Button")
            {
                int ctlId = GetDlgCtrlID(hWnd);
                switch (ctlId)
                {
                    case MBOK:
                        SetWindowText(hWnd, OK);
                        break;
                    case MBCancel:
                        SetWindowText(hWnd, Cancel);
                        break;
                    case MBAbort:
                        SetWindowText(hWnd, Abort);
                        break;
                    case MBRetry:
                        SetWindowText(hWnd, Retry);
                        break;
                    case MBIgnore:
                        SetWindowText(hWnd, Ignore);
                        break;
                    case MBYes:
                        SetWindowText(hWnd, Yes);
                        break;
                    case MBNo:
                        SetWindowText(hWnd, No);
                        break;

                }
                nButton++;
            }

            return true;
        }


    }
}

Why are interface variables static and final by default?

Think of a web application where you have interface defined and other classes implement it. As you cannot create an instance of interface to access the variables you need to have a static keyword. Since its static any change in the value will reflect to other instances which has implemented it. So in order to prevent it we define them as final.

Can attributes be added dynamically in C#?

This really depends on what exactly you're trying to accomplish.

The System.ComponentModel.TypeDescriptor stuff can be used to add attributes to types, properties and object instances, and it has the limitation that you have to use it to retrieve those properties as well. If you're writing the code that consumes those attributes, and you can live within those limitations, then I'd definitely suggest it.

As far as I know, the PropertyGrid control and the visual studio design surface are the only things in the BCL that consume the TypeDescriptor stuff. In fact, that's how they do about half the things they really need to do.

What does '--set-upstream' do?

git branch --set-upstream <remote-branch>

sets the default remote branch for the current local branch.

Any future git pull command (with the current local branch checked-out),
will attempt to bring in commits from the <remote-branch> into the current local branch.


One way to avoid having to explicitly type --set-upstream is to use its shorthand flag -u as follows:

git push -u origin local-branch

This sets the upstream association for any future push/pull attempts automatically.
For more details, checkout this detailed explanation about upstream branches and tracking.


To avoid confusion, recent versions of git deprecate this somewhat ambiguous --set-upstream option in favour of a more verbose --set-upstream-to option with identical syntax and behaviour

git branch --set-upstream-to <origin/remote-branch>

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Powershell script to locate specific file/file name?

To search the whole computer:

gdr -PSProvider 'FileSystem' | %{ ls -r $_.root} 2>$null | where { $_.name -eq "httpd.exe" }

Volley - POST/GET parameters

For the GET parameters there are two alternatives:

First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:

String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s",
                           num1,
                           num2);

StringRequest myReq = new StringRequest(Method.GET,
                                        uri,
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener());
queue.add(myReq);

where num1 and num2 are String variables that contain your values.

Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.

For the POST parameters probably sometimes will be easier than the accepted answer to do it like:

StringRequest myReq = new StringRequest(Method.POST,
                                        "http://somesite.com/some_endpoint.php",
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener()) {

    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("param1", num1);
        params.put("param2", num2);
        return params;
    };
};
queue.add(myReq);

e.g. to just override the getParams() method.

You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.

Find and replace with a newline in Visual Studio Code

In the local searchbox (ctrl + f) you can insert newlines by pressing ctrl + enter.

Image of multiline search in local search

If you use the global search (ctrl + shift + f) you can insert newlines by pressing shift + enter.

Image of multiline search in global search

If you want to search for multilines by the character literal, remember to check the rightmost regex icon.

Image of regex mode in search replace


In previous versions of Visual Studio code this was difficult or impossible. Older versions require you to use the regex mode, older versions yet did not support newline search whatsoever.

What's the point of the X-Requested-With header?

Make sure you read SilverlightFox's answer. It highlights a more important reason.

The reason is mostly that if you know the source of a request you may want to customize it a little bit.

For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click. The link may be www.example.com/recipe/apple_pie

Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.

Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie but that's harder to maintain and share to other people.

But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.

The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.

It's actually kind of similar to the Accept-Language header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.

SQL Server: IF EXISTS ; ELSE

EDIT

I want to add the reason that your IF statement seems to not work. When you do an EXISTS on an aggregate, it's always going to be true. It returns a value even if the ID doesn't exist. Sure, it's NULL, but its returning it. Instead, do this:

if exists(select 1 from table where id = 4)

and you'll get to the ELSE portion of your IF statement.


Now, here's a better, set-based solution:

update b
  set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
  on b.id = a.id
where
  b.id = yourid

This has the benefit of being able to run on the entire table rather than individual ids.

What is the difference between null and undefined in JavaScript?

You might consider undefined to represent a system-level, unexpected, or error-like absence of value and null to represent program-level, normal, or expected absence of value.

via JavaScript:The Definitive Guide

ant build.xml file doesn't exist

If I understand correctly, you assumed that -v is the "print version" command. Check the documentation, that is not the case -- instead ant -v is running ant build in verbose mode. So ant is trying to perform your build, based on the build.xml file, which is obviously not there.

To answer your question explicitly: there is probably nothing wrong with both the system nor ant installation.

Forking vs. Branching in GitHub

It has to do with the general workflow of Git. You're unlikely to be able to push directly to the main project's repository. I'm not sure if GitHub project's repository support branch-based access control, as you wouldn't want to grant anyone the permission to push to the master branch for example.

The general pattern is as follows:

  • Fork the original project's repository to have your own GitHub copy, to which you'll then be allowed to push changes.
  • Clone your GitHub repository onto your local machine
  • Optionally, add the original repository as an additional remote repository on your local repository. You'll then be able to fetch changes published in that repository directly.
  • Make your modifications and your own commits locally.
  • Push your changes to your GitHub repository (as you generally won't have the write permissions on the project's repository directly).
  • Contact the project's maintainers and ask them to fetch your changes and review/merge, and let them push back to the project's repository (if you and them want to).

Without this, it's quite unusual for public projects to let anyone push their own commits directly.

How to output numbers with leading zeros in JavaScript?

NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.

You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:

function pad(num, size) {
    num = num.toString();
    while (num.length < size) num = "0" + num;
    return num;
}

Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.

function pad(num, size) {
    var s = "000000000" + num;
    return s.substr(s.length-size);
}

If you care about negative numbers you'll have to strip the - and read it.

Find all CSV files in a directory using Python

While solution given by thclpr works it scans only immediate files in the directory and not files in the sub directories if any. Although this is not the requirement but just in case someone wishes to scan sub directories too below is the code that uses os.walk

import os
from glob import glob
PATH = "/home/someuser/projects/someproject"
EXT = "*.csv"
all_csv_files = [file
                 for path, subdir, files in os.walk(PATH)
                 for file in glob(os.path.join(path, EXT))]
print(all_csv_files)

Copied from this blog.

Why do access tokens expire?

It is essentially a security measure. If your app is compromised, the attacker will only have access to the short-lived access token and no way to generate a new one.

Refresh tokens also expire but they are supposed to live much longer than the access token.

C++ float array initialization

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

How to align content of a div to the bottom

Seems to be working:

HTML: I'm at the bottom

css:

h1.alignBtm {
  line-height: 3em;
}
h1.alignBtm span {
  line-height: 1.2em;
  vertical-align: bottom;
}

Cause of a process being a deadlock victim

Here is how this particular deadlock problem actually occurred and how it was actually resolved. This is a fairly active database with 130K transactions occurring daily. The indexes in the tables in this database were originally clustered. The client requested us to make the indexes nonclustered. As soon as we did, the deadlocking began. When we reestablished the indexes as clustered, the deadlocking stopped.

django import error - No module named core.management

I was getting the same problem while I trying to create a new app. If you write python manage.py startapp myapp, then it looks for usr/bin/python. But you need this "python" which is located in /bin directory of your virtual env path. I solved this by mentioning the virtualenv's python path just like this:

<env path>/bin/python manage.py startapp myapp

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I want to mention here a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr for concatenate things.

Both of this projects are entirely developed with requirejs modules (you can see that in their github repos) and then they use the requirejs optimizer as a very smart concatenator. The interesting thing is that, as you can see, nor jQuery neither Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code. So they end up with a standalone library that was developed with requirejs modules! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.

For all those interested in concatenation with the requirejs optimizer, check out this post

Also there is a small tool that abstracts all the boilerplate of the process: AlbanilJS

How do I select child elements of any depth using XPath?

//form/descendant::input[@type='submit']

No space left on device

Such difference between the output of du -sh and df -h may happen if some large file has been deleted, but is still opened by some process. Check with the command lsof | grep deleted to see which processes have opened descriptors to deleted files. You can restart the process and the space will be freed.

Transparent background in JPEG image

How can I set a transparent background on JPEG image?

If you intend to keep the image as a JPEG then you can't. As others have suggested, convert it to PNG and add an alpha channel.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Running a simple shell script as a cronjob

The easiest way would be to use a GUI:

For Gnome use gnome-schedule (universe)

sudo apt-get install gnome-schedule 

For KDE use kde-config-cron

It should be pre installed on Kubuntu

But if you use a headless linux or don´t want GUI´s you may use:

crontab -e

If you type it into Terminal you´ll get a table.
You have to insert your cronjobs now.
Format a job like this:

*     *     *     *     *  YOURCOMMAND
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- Day in Week (0 to 7) (Sunday is 0 and 7)
|     |     |     +------- Month (1 to 12)
|     |     +--------- Day in Month (1 to 31)
|     +----------- Hour (0 to 23)
+------------- Minute (0 to 59)

There are some shorts, too (if you don´t want the *):

@reboot --> only once at startup
@daily ---> once a day
@midnight --> once a day at midnight
@hourly --> once a hour
@weekly --> once a week
@monthly --> once a month
@annually --> once a year
@yearly --> once a year

If you want to use the shorts as cron (because they don´t work or so):

@daily --> 0 0 * * *
@midnight --> 0 0 * * *
@hourly --> 0 * * * *
@weekly --> 0 0 * * 0
@monthly --> 0 0 1 * *
@annually --> 0 0 1 1 *
@yearly --> 0 0 1 1 *

read subprocess stdout line by line

Bit late to the party, but was surprised not to see what I think is the simplest solution here:

import io
import subprocess

proc = subprocess.Popen(["prog", "arg"], stdout=subprocess.PIPE)
for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"):  # or another encoding
    # do something with line

(This requires Python 3.)

How can I change Eclipse theme?

Eclipse... To just get everything done goto Window>Preferences>General and goto theme menu and change it... Then re-start to apply...

Can't compare naive and aware datetime.now() <= challenge.datetime_end

Just:

dt = datetimeObject.strftime(format) # format = your datetime format ex) '%Y %d %m'
dt = datetime.datetime.strptime(dt,format)

So do this:

start_time = challenge.datetime_start.strftime('%Y %d %m %H %M %S')
start_time = datetime.datetime.strptime(start_time,'%Y %d %m %H %M %S')

end_time = challenge.datetime_end.strftime('%Y %d %m %H %M %S')
end_time = datetime.datetime.strptime(end_time,'%Y %d %m %H %M %S')

and then use start_time and end_time