w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Python : Extending Exception class
ImportError is a built-in exception; an import failure will not look for the exception in the current module globals. In fact, in Python 2, the import machinery doesn't even look in builtins for this; it uses the C equivalent of the exception, PyExc_ImportError. You cannot replace the exception with your own. Just catch the exception at the top level of your python main script: try: main() # or whatever function is your main entrypoint except ImportError: logging.exception('Import oopsie') or raise a custom exception in a exception handler instead. This is far clearer to future maintainers of your code than hacking additional features into standard exceptions. In Python 3.1 and up, the import machinery has been largely reimplemented using a lot more Python code, and there yo

Categories : Python

extending built-in python dict class
You must call the superclass __init__ method. And if you want to be able to use the Masks(one=1, ..) syntax then you have to use **kwargs: In [1]: class Masks(dict): ...: def __init__(self, positive=(), negative=(), **kwargs): ...: super(Masks, self).__init__(**kwargs) ...: self['positive'] = list(positive) ...: self['negative'] = list(negative) ...: In [2]: m = Masks(one=1, two=2) In [3]: m['one'] Out[3]: 1 A general note: do not subclass built-ins!!! It seems an easy way to extend them but it has a lot of pitfalls that will bite you at some point. A safer way to extend a built-in is to use delegation, which gives better control on the subclass behaviour and can avoid many pitfalls of inheriting the built-ins. (Note that impleme

Categories : Python

How do we get an optional class attribute in Python?
You can use hasattr and getattr. For example: hasattr(foo, 'bar') would return True if foo has an attribute named bar, otherwise False and getattr(foo, 'bar', 'quux') would return foo.bar if it exists, otherwise defaults to quux.

Categories : Python

Python class without attribute boilerplate
Here are some recipes you can try: override __setattr__, __dict__, __slots__ and/or init. Let us know what works for you.

Categories : Python

python- Feature class attribute manipulation
Short of writing your code for you, use arcpy.ListFields() to loop over the fields of each featureclass. Be careful not to totally denude the target class of identifying info; use an if/then w/in that loop. You haven't really specified the common key/relate field but you'll want to keep that around, at least, in order to transfer information to relevant features in target. P.S. why 2.6? Time to update both ArcGIS & Python!

Categories : Python

Determine if given class attribute is a property or not, Python object
I once asked a similar question. The trouble you'll run into, of course, is that you can't access the property through the instance to determine its type without calling the getter, which gets you the type of whatever the getter returns. So you have to access the property through its class rather than through the instance. property is already a type, so you can just compare directly to that. (I originally had some superfluous code here that got the property type out of a class that had a property. I thought this was necessary due to a typo when I was testing things.) obj_type = type(obj) for attr in dir(obj): if isinstance(getattr(type(obj), attr, None), property): print attr, "is a property" Don't worry about having an instance attribute with the same name. It's ignored

Categories : Python

Changing object attribute within a custom class (Python)
The lambda default value listbox.val is evaluated at definition-time. So if you use lambda myval=listbox.val: callback(myval) then myval's default value equals 2 forever. Instead, you could use b = Button(top, text="answer", command=lambda mybox=listbox: callback(mybox.val))

Categories : Python

Is this code instantiating or extending an abstract class without creating a new class?
It almost looks like the code extends WindowAdapter or overrides the windowClosing method This is exactly what's happening. but how is that possible without writing a new class? In fact, the code is creating a new (anonymous) class. It's just that the syntax is different to what you've come across so far. Take a look at the tutorial. For a discussion of how anonymous classes are used, see How are Anonymous (inner) classes used in Java?

Categories : Java

Extending class with private constructor in Serializable class
The document says that a non-serializable supertype needs a no-arg constructor. It does not say it should be private. On the contrary it says this constructor should be accessible. What the documentation means about runtime is this class A { A() { <-- accessible only in current package } } public class B extends A implements Serializable { public B() { } } Lets assume both A and B are in the same package. There is no compile error. But if we try to deserialize an instance of B from class C in another package we will get a runtime exception, because ObjectInputStream will try to invoke A's no-arg constructor but it is inaccessible from outside the package

Categories : Java

JPA persistent class extending another class from different JAR
@MappedSuperclass public abstract class CommonObject implements Serializable { private Date createDate; public abstract Long getId() ; public abstract void setId(Long id); public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } } @Entity @Table public class UserDetails extends CommonObject { String name; int age; @GeneratedValue(strategy= GenerationType.AUTO) @Id private Long id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { re

Categories : Java

When to restrict a class from extending a class?
Yes. In Java they call this a final class. In C# they call it a sealed class. It is done because you cannot always predict the many ways a consumer might extend your class, so to prevent you from having to design your class to account for all possible ways someone might extend it, you simply seal it and require the consumer to use composition instead of inheritance. Further Reading Why Are So Many Of The Framework Classes Sealed?

Categories : Misc

vb.net extending a class with generics
is it possible to extend different classes with the same generic class? Generics isn't some kind of "workaround" for a lack of multiple inheritance, no. Your class C doesn't derive from A - it just means that the T in B(Of T) would be A in the context of C. Which instance of A would you expect TestA() to be called on? Creating an instance of C certainly doesn't create an instance of A... The fact that B(Of T) doesn't use T anywhere should be a warning signal - types which are generic but never use their generic type parameters are generally problematic. It's hard to know exactly how to help you solve your real problem without more details, but you can't add a common base class in like this, when you also need to derive from other types which aren't under your control. Perhaps exte

Categories : Vb.Net

Extending a class that may not be in classpath
Frameworks such as Spring which have "optionally used" code depending on other libraries, use a "Strategy pattern" to put that dependency-specific code into an "inner class" or into a separate class. The outer class can be loaded & run fine; it's only when you try & instantiate the inner class that the NoClassDefFoundError will be thrown. So the outer class typically tries (try-catch) instantiating one strategy to use, and then if that fails instantiates a fallback strategy. public class MyService { protected MyStrategy strategy; // constructor; // -- choose our strategy. public MyService() { try { this.strategy = new ExternalLib_Strategy(); } catch (NoClassDefFoundError x) { // external library not available.

Categories : Java

Should I use the same name for a class when extending it with a namespace in PHP?
Using the same class names, or Name collisions is one of the problems that namespaces are specifically designed to solve.. http://www.php.net/manual/en/language.namespaces.rationale.php In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: 1.Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants. 2. Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

Categories : PHP

C++: Extending a template class
You could use a traits style helper class. template<typename T> CVectorTraits {}; template<> CVectorTraits<double> { typedef Point3d PointType; } template<> CVectorTraits<float> { typedef Point3f PointType; } template<typename T> class CVector3 { CVector3<T> &normalize(); // more stuff typename CVectorTraits<T>::PointType toPoint() const; };

Categories : C++

Using .getDeclaredMethod to get a method from a class extending another
It sounds like you just need to use getMethod instead of getDeclaredMethod. The whole point of getDeclaredMethod is that it only finds methods declared in the class you're calling it on: Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object. Whereas getMethod has: C is searched for any matching methods. If no matching method is found, the algorithm of step 1 is invoked recursively on the superclass of C. That will only find public methods though. If the method you're after isn't public, you should recurse up the class hierarchy yourself, using getDeclaredMethod or getDeclaredMethods on each class in the hierarchy. EDIT: Okay, now that we know it's a private method... Class<?> clazz = plugin.getCla

Categories : Java

Extending a class with only one factory constructor
You can't directly extend a class with a factory constructor. However you can implement the class and use delegation to simulate the extension. For instance : class MyExtendedEvent implements CustomEvent { int count; final CustomEvent _delegate; MyExtendedEvent(this.count, String type) : _delegate = new CustomEvent(type); noSuchMethod(Invocation invocation) => reflect(_delegate).delegate(invocation); } NB : I used reflection here to simplify the code snippet. A better implementation (in regard of performances) would have been to define all methods like method1 => _delegate.method1()

Categories : Dart

Pythonic way of extending base class
Use argument expansion in your __init__ method, investigate the arguments provided and if you find one string argument, then perform the Table.constructor1('string') internally. On the other hand, looking at your question more closely, I am wondering what you want to achieve here. So far, your constructor1 classmethod does not make sense. What kind of functionality do you want to implement so that df = pd.read_csv(...) is not enough for you?

Categories : Python

PHP - extend method like extending a class
I would use "hook" and abstraction concepts : class animal{ // Function that has to be implemented in each child abstract public function walkMyWay(); public function walk(){ walk_base; walkMyWay(); } } class human extends animal{ // Just implement the specific part for human public function walkMyWay(){ with2legs; } } class pig extends animal{ // Just implement the specific part for pig public function walkMyWay(){ with4legs; } } This way I just have to call : // Calls parent::walk() which calls both 'parent::walk_base' and human::walkMyWay() $a_human->walk(); // Calls parent::walk() which calls both 'parent::walk_base' and pig::walkMyWay() $a_pig->walk(); to make a child walk his way... See T

Categories : PHP

Extending Custom Validation-Class
Is that function supposed to be static? What if you remove static? public function validateTimezone($attribute, $value, $parameters) { return !empty(Timezones::$timezones[$value]); }

Categories : PHP

Android - Extending Another Class with Fragments
Imageloader needs to be configured in the BaseAdapter class, so what I did since the above codes are quite confusing. I directly use this on my main Activity: BaseActivity.imageLoader.init(ImageLoaderConfiguration.createDefault(getBaseContext())); instead on relying the configuring in AbsListViewBaseActivity class.

Categories : Java

Use ImageIO.read for class extending BufferedImage
You can cast an instance of a subclass to its parent class. But you cannot cast an instance of a superclass to a subclass You can try to use solution something like this: public class NamedImage extends BufferedImage { private String name; public NamedImage(BufferedImage img,String name){ super(img.getWidth(),img.getHeight(),img.getType()); setData(img.getData()); this.name=name; } public NamedImage(int width, int height, int imageType) { super(width, height, imageType); } public void setName(String text) { name = text; } public static void main(String args[]) throws IOException { NamedImage image = new NamedImage(ImageIO.read(new File("/Users/igor/Downloads/cats-coloring.gif")),"A cat"); } }

Categories : Java

Extending google maps Marker class
Can the class be extended? No, as it is marked as final. You cannot create subclasses of the Maps V2 Marker class. One workaround is to overload some data member of Marker, such as the snippet, to use as the key to a collection of model objects (e.g., HashMap) that can contain whatever properties you want.

Categories : Java

Extending core Laravel 4 component class?
It's unnecessary to extend the HTML helper class. Instead, use CSS selectors to pick the elements. As for making your own methods, you can use the HTML::macro() See: http://laravel.com/api/source-class-Illuminate.Html.HtmlBuilder.html#32 And: http://laravel.com/api/source-class-Illuminate.Html.HtmlBuilder.html#390

Categories : PHP

How do I hide the public API methods of my extending class?
In //DataAdapter.m #import <CoreData/CoreData.h> @interface DataAdapter() @property (strong, nonatomic) CoreDataAdapter *adapter; @end @implementation DataAdapter @end

Categories : IOS

creating class extending from predefined Superclass
according to servlet specification it needs to create instance of Servlet so it can't be abstract class You can choose to go for @WebServlet annotation based configuration with servlet 3.0

Categories : Java

I can't use annotation to the extending class when PropertyPlaceholderConfigurer was extended
Since MyClass is a BeanFactoryPostProcessor, it is fully instantiated very early in the bean lifecycle, to be able to act on created bean definitions. The @Autowired annotations on the other hand are processed by AutoWiredAnnotationPostProcessor which is a BeanPostProcessor. Now since MyClass is fully instantiated much earlier, the AutowiredAnnotationPostProcessor cannot act on it and inject in the prop1 dependency and hence the failure. It will better to inject in all properties of a BeanFactoryPostProcessor through explicit configuration itself. EDIT: The javadoc for @Autowired has a good explanation also - http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html

Categories : Java

Using context inside class extending BroadcastReceiver
Hm, you already have your context - it's onReceive()'s parameter. You don't need to use getApplicationContext(). EDIT: You can't use context in switch case, because context is defined in Receiver class and you are trying to use it in onClickListener class. I suggest this: public class %YOUR_RECEIVER_CLASS% { private Context context; public onReceive(Context context, ...) { this.context = context; } } NOW you can use context everywhere

Categories : Android

Extending Types by Subclassing in Python
You mean list.__init__([])? It calls the base initializer from the subclass initializer. Your subclass has replaced the base class initializer with its own. In this case commenting that out happens to work because the unbound initializer was called with an empty list instead of self and is thus a no-op. This is an error on behalf of the authors, most likely. But it is a good idea generally to make sure the base class has run its initialization code when you subclass. That way all internal data structures the base class methods rely on have been set up correctly.

Categories : Python

Python Extending Classes with Same Method Name
Python supports a limited form of multiple inheritance as well. A class definition with multiple base classes looks as follows: class DerivedClassName(Base1, Base2, Base3): . . . The only rule necessary to explain the semantics is the resolution rule used for class attribute references. This is depth-first, left-to-right. Thus, if an attribute is not found in DerivedClassName, it is searched in Base1, then (recursively) in the base classes of Base1, and only if it is not found there, it is searched in Base2, and so on. So in your example if all 3 classes have method save instances of File will use method save from models.Model

Categories : Python

Extending python with a OpenCV C++ module
The C++ header file is #include <opencv2/opencv.hpp>, if you have /usr/local/include on your header path. So what you should be doing is - #include <opencv2/opencv.hpp> using namespace cv; As for including the OpenCV libarries for linking, you should look at the libraries in /usr/local/lib/libopencv*. There are several OpenCV libraries, each corresponding to one package, so you may not need to link all the libraries, if you are not using that package. Personally, I would work by statically linking your module with a libopencv.a and the linking the entire module to Python. If you are bothered about extra code being linked, you can strip the unused symbols.

Categories : C++

Extending a class--how do I avoid having to create multiple classes?
In Java you can't inherit class from more than one superclass. In order to achive your purpose, I would advise you to move all common logic to another class(IOIOHolder, for example), which would take an Activity parameter in constructor. Later you can create two different classes extending Activity and FragmentActivity, each containing an exemplar of IOIOHolder and using it for it's own tasks. By using this approach you can write IOIO code once and use it in any activity you want.

Categories : Java

should we always define interface and abstract classes, even when there will only be only 1 class extending them?
Abstract classes and interfaces are meant if you will use multiple of them. If you are only planning on one class, you don't need either. If at a later point you need two subclasses you could always convert your original class to an interface. One thing to keep in mind is that it is safe to write interfaces and abstract classes. If the functionality is already known and a skeleton has already been made, it is easier to test your classes and it will prevent errors.

Categories : Java

ActionScript 3.0 Document Class not extending to MovieClip or Sprite
Handle an ADDED_TO_STAGE event , then get the stage: Class A: package{ import flash.display.Sprite; public class A extends Sprite // Class A extends Sprite { public function A(){ } } } Class B: package{ import flash.events.Event; public class B extends A // Class B extends only class A { public function B() { addEventListener(Event.ADDED_TO_STAGE, _handleAddedtoStage); } private function _handleAddedtoStage(event:Event):void { trace( stage ); // [object Stage] } } }

Categories : Actionscript

Extending Sentry 2 Models from a Base Eloquent class
You could make your User and Group models extend SentryUserModel and SentryGroupModel respectively then extend Base model using a magic function. Code: class User extends SentryUserModel { private $base; function __construct() { $this->base = new Base(); } // fake "extends Base" using magic function public function __call($method, $args) { $this->base->$method($args[0]); } } class Group extends SentryGroupModel { private $base; function __construct() { $this->base = new Base(); } // fake "extends Base" using magic function public function __call($method, $args) { $this->base->$method($args[0]); } }

Categories : PHP

Rebinding immutable class attribute in the base class from a derived class
Use the __bases__ attribute: In [68]: class Base(object): ...: # class attribute: ...: class_attr = 0 ...: In [69]: class Derived(Base): ...: @classmethod ...: def inc(cls): ...: p, = cls.__bases__ ...: p.class_attr += 1 ...: In [70]: Base.class_attr Out[70]: 0 In [71]: Derived.inc() In [72]: Derived.inc() In [73]: Base.class_attr Out[73]: 2 If you have multiple inheritance: In [88]: class DifferentInherited(object): ...: class2_attr = 0 ...: In [90]: class Der2(Base, DifferentInherited): ...: @classmethod ...: def inc(cls): ...: print cls.__bases__ ...: a, b, = cls.__bases__ ...: print a.class_attr ...: print b.class2_attr

Categories : Python

customization of List view by extending base adapter class
Use this instead public void getSize (Point outSize) Like this getSize() giving me errors

Categories : Android

How can I get a packagemanager object if i am not extending the activity class in Android/ Java?
Usually the best way to do what you're trying to do it pass the Context to the constructor of your new class. That way you can then use that to call methods which belong to the Activity. An example is below, it should help you work out your problem: private Context context; // ... public HelperClass(Context c){ context = c; } // ... context.getPackageManager(); You can then call it by just adding your Context when you initialize the new class: new HelperClass(this); Although in certain situations, such as from a Fragment, you may have to provide getActivity();. new HelperClass(getActivity()); Try edit your class as shown above and let us know if you see any improvements. As mentioned in the comments, unless you're planning on using your context to edits views etc. you'd

Categories : Android

How can I access Middleman template helpers when extending a class in config.rb?
I've found that link_to is an instance method of class Middleman::Application, which I can access through the app variable: helpers do class Middleman::Sitemap::Resource def link(text) app.link_to(text, path) end end end

Categories : Ruby

How to specify the default error message when extending the Validation class in Laravel 4
The Laravel 4 docs specifically state you need to define an error message for your custom rules. You have two options; Option 1: $messages = array( 'foo' => 'The :attribute field is foo.', ); $validator = Validator::make($input, $rules, $messages); Option 2: Specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the app/lang/xx/validation.php language file: 'custom' => array( 'foo' => array( 'required' => 'We need to know your foo!', ), ),

Categories : Validation



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.