Do not have multiple speed variables, just have one, and call for it every time you need to get it SpeedHolder speedHolder; public void Update() { transform.position += speedHolder.Speed * Time.deltaTime; } If you REALLY want this done another way... you can use events and delegates. public class SpeedHolder {...
First you're using non-ascii characters in your pathname. I've never tried to do it so I can't help you there but maybe you can try the answer here Open File with Non ASCII Characters You're doing it wrong, the way you go about writing to the file. I assume that...
python,class,share,instance,global
* Main module ***************** import matplotlib as plt import plotter import shapes def main(): global thePlot thePlot = plotter.plotter() cyl = shapes.cylinder(r, c, n, color) cyl.draw() plt.show() And this: global thePlot * This line causes the error thePlot.plot(self.x, self.y, self.z, self.color) Should become: main.thePlot.plot(self.x, self.y, self.z, self.color) With the condition...
You seem to be a bit confused about classes. They are for creating a new, custom type of variable. I'd also read up on constructors (initializing method for a class). Ok, as for your code, you don't need all those classes. You just need the methods. I would also recommend...
How about using a decorator? You will have to decorate each function that requires the pet to be alive, but you will avoid having to write the if-logic over and over: >>> def require_alive(func): ... def wrapper(self, *args, **kwargs): ... if not self.alive: ... raise Exception("Not alive") ... return func(self,...
c++,class,operator-overloading,operators,element
Simply call the base class member functions as required: double& operator[](size_type index) { #ifdef DEBUG_ENABLED return std::vector<double>::at(index); #else return std::vector<double>::operator[](index); #endif } You should provide a const version of this too. Also note you probably don't want to make this operator virtual....
Not sure if this is what you're asking but you could do this function Card(obj) { // The attributes of "obj" to map to this class var keys = ["cardTypes", "rarity", ...]; for (var key in obj) { if (obj.hasOwnProperty(key) && keys.indexOf(key) !== -1) { this[key] = obj[key]; } }...
javascript,html,class,eventlistener
Instead of referring the checkboxes with their id's you can refer to them using the class you are giving them class="texts" HTML: <input class="texts" type="checkbox" value="a"/>A <input class="texts" type="checkbox" value="b"/>B <input class="texts" type="checkbox" value="c"/>C Using only JavaScript: JavaScript demo If you want a pure JavaScript solution then you need to...
Method 1: use statics in the class. This is not a very good method since it only knows about itself and not about anything else. The problem is if you have a second window which uses Example, it starts from the position where the last one stopped, so you need...
c++,class,operator-overloading,ambiguous
The issue is that you have implicit conversions going in both directions. Disregarding const, your two candidates are: T & buffer::operator [] ( size_t ); int& operator[] (int*, int); For the call buf[pos] where pos is an int (such as a literal), the call is ambiguous. The first candidate could...
c++,class,templates,template-templates
The issue is that std::vector takes two template arguments: the type and the allocator. Many other container types will takes additional policy arguments which have defaults to allow you to instantiate like T<U>. In order to support this, you can say that your template template parameter should take at least...
javascript,html,class,getelementsbyclassname
function searchItem(itemname) { if($('a.item-name:contains("' + itemname + '")').length) { //console.log("true"); return true; } } jsfiddle...
Go with the second. Your first snippet has a redundant new List<T> call which allocates a new list, while the next line overrides that reference with a newly created list from your repo. Absolutely no need for that....
javascript,class,properties,public,ecmascript-6
You'd need to put it inside your constructor: class myClass{ constructor(){ this.someObject = { myvalue:value }; } } var obj = new myClass(); console.log(obj.someObject.myvalue); // value If required, you can add the object onto the prototype chain the same as you would in ES5: class myClass{ constructor(){ } } myClass.prototype.someObject...
First, module Tree2 ( Tree ) where only exports the Tree data type, not its constructors; you should use module Tree2 ( Tree(..) ) where instead. Second, as you're doing a qualified import, you need to use Tree2.EmptyTree instead of just EmptyTree....
If I add methods to this struct, probably the internal structure will be changed. That's wrong; to satisfy your needs what you want is to keep your structure a POD, for which essentially you don't want: non-trivial constructors/destructors/assignment operators; virtual functions or virtual base classes; different access specifiers for...
classes in HTML are very useful, particularly in CSS. If you want to create a design for your web page which you can use more than once, you can use the same CSS stylesheet for multiple pages, and each page will contain the same classes referenced by the CSS stylesheet....
python,class,inheritance,printing,instances
If Family is supposed to contain Agent objects, why does it inherit from Agent? Regardless, you never initialized the parent Agent object in the Family class's __init__, and according to your edit the get_money method is contained in the Agent class, so Family objects don't have a get_money method. To...
I think what you're trying to do is look up an object by name. You can't do it literally the way you have, but it's common and you don't have to add to much code. Let's say you have an RPG game and you have team members, which each little...
It's because you have a non-optional property that doesn't have a default value. var hero: JTHero Is non-optional but it also has no value. So, you can either make it optional by doing var hero: JTHero? Or you can create an init method and set the value in there. Or...
Yes, and it is implemented as this, like in Java or C++. You don't have to pass it explicitly at the method call, like in python. Then what you're creating in your example are instance variables, also called members. They belong to instances of the class, i.e. they are not...
In Symfony you use namespaces. imagine that you want to make an instance of COM into a controller, lets say MyController. Your controller PHP file will begin with this rule: namespace AppBundle\Controller; Now if you make an instance of the PHP COM class PHP will search this class into the...
You are doing it wrongly , either you need to give module.ClassName to access the Class or import it using from <module> import <Class> Examples - >>> import classy >>> rectangle = classy.Shape(10,10) Or >>> from classy import Shape >>> rectangle = Shape(10,10) ...
java,class,oop,methods,casting
When using inheritance within classes, overriding a method will ALWAYS call the child method regardless of casting. You can never change the type of an object, so a RockMusician - although it is an extension of Musician - is still a RockMusician and will be called by its type, not...
php,class,namespaces,autoload,silex
I believe your problem is caused by the way you named your directory controllers. According to the documentation about PSR-4 standard: 5) Alphabetic characters in the fully qualified class name MAY be any combination of lower case and upper case. 6) All class names MUST be referenced in a case-sensitive...
It's somewhat vague what you're asking, but if valueToUseHere is not used outside of doStuff, then don't make it a property! class someClass { public function doStuff() { $valueToUseHere = 60; // Do more stuff here... } } If there's no reason to share that value with other methods of...
You didn't say is it a method but if it is then you could make static method (no need to create new class then) and then use it like Message.method(message, error code);. Or even add import static what gives you ability to do something like this: method(message, error code);.
Firstly, you just need to write check::TStatus check::getStatus() ^^^^^^^ because otherwise the compiler does not know where does TStatus come from. See full compilable code here: http://ideone.com/l5qxbK But note also another problem. Your getStatus() is a public function, so you will probably want to call it from outside of a...
You can not implement __rmul__ for both sides, because __rmul__ is, by definition, for right multiplication. When you want to change the behaviour of x * y you have to look at either x.__class__.__mul__ or y.__class__.__rmul__. a * b uses R3.__mul__ (OK) b * a also uses R3.__mul__ (OK) 2...
javascript,function,class,inheritance,prototype
after constructorFunction.prototype there is no propertie or method name That's not true. The prototype of the constructor is set using triangle object. The prototype has 3 properties. prototype is an object. Consider these examples: var obj = { 'baz': 'bar' }; obj = { 'foo': 'bash' } // obj...
java,android,class,android-intent,android-activity
You are doing mistake in your onPostExecute(String result) method. Replace Intent intent3 = new Intent(SigninActivity.this, MainActivity.class); startActivity(intent3); By context.startActivity(new Intent(context, MainActivity.class)); ...
c++,class,c++11,smart-pointers
Since std::unique_ptr is not copyable, class Foo does not have a valid copy constructor. You could either deep copy or use a move constructor: #include <memory> #include <vector> class FooImpl {}; class Foo { std::unique_ptr<FooImpl> myImpl; public: Foo( Foo&& f ) : myImpl( std::move( f.myImpl ) ) {} Foo(){} ~Foo(){}...
javascript,jquery,class,object,callback
EDIT Actually, my first solution does not work because the context of the callback is the element, not the object. Here is the working code and a jsfiddle: function Waves(selector){ this.selector = selector; this.animateWaves = function(forward,backward,speed){ var self = this; $(selector).velocity({translateX: forward},speed); $(selector).velocity({translateX: backward}, speed, function () { self.animateWaves(forward,backward,speed); });...
java,class,design-patterns,design,immutability
A final variable can be assigned a value only once. The compiler doesn't check whether a method is called only once; hence, final variables cannot be assigned in methods. (In case of the deserialize method the compiler couldn't determine if the method is called only once, even if it would...
c++,class,inheritance,comparison
Your design has the potential to produce unexpected results. If your main is: int main(int argc, char** argv) { Foo a(1); Bar d(1, 2); coutResult(a, d); return 0; } you'll end up comparing a Foo object with a Bar object and output will be: l.m_a == 1, r.m_a == 1,...
I would say that in object oriented programming the use of statics should me minimized, but they do have a place. It takes a bit of time to develop a good sense for when static methods/variable are appropriate, so I would start out only using them in a small set...
Check if this has property and then assign from foo for(var property in foo) { if(this.hasOwnProperty(property)) { this[property] = foo[property]; } } or a better way is to loop all keys in this and you do not need if statement....
As the documentation states, classes and structs are by default internal and their members are private. The code won't compile because, as the error message will state, you cannot inherit from a less accessible class. In this case the child class would be public and the parent internal....
The 000000b0 is not part of the data. It's the memory address where the following 16 bytes are located. The two-digit hex numbers are the actual data. Read them from left to right. Each row is in two groups of eight, purely to asist in working out memory addresses etc....
You can't use type hints with scalar values ( in you case string - check the docs) Change your constructor in this way: public function __construct($scheme, $hostname, $www) { $this->scheme = $scheme; $this->hostname = $hostname; $this->www = $www; } and it should work...
ruby,class,inheritance,keyword,superclass
They're keywords, not classes. If anything, they would be methods in Kernel, as opposed to classes with superclass BasicObject, but they're just keywords, and as such have neither class nor superclass. They're a special case and treated specially by the interpreter. Note that not everything that looks like a keyword...
The override keyword allows you to replace or extend the definition of a method in the base class that is marked with virtual. Since you haven't specified your base class explicitly, your object extends System.Object which does not define a ToInt32() method. Simply remove the override keyword and your class...
c++,class,object,inheritance,vector
Option 1 cannot work because obs is a vector<observable*>^. You cannot push a object of type observable because you can only store pointers (observable*) in it. You could store such objects in a vector<observable> but you cannot store Energy objects in such vector. Option 2 cannot work because ecause obs...
You forgot to return the value of $this->getUserId($username); in your constructor but that doesn't matter anyway as in PHP constructors do not return values. You will have to make a second call to get that value after you initiate your object. $test = new Test(); $userId = $test->getUserId($username); class Test...
You are using the concrete type Fighter in the parameter-list of your method instead of the abstract type IFighter. Change the following line public void Utok(Fighter warrior) To public void Utok(IFighter warrior) You need to use the exact type defined in the interface if you implement it in a class....
I found out what was the problem. I used a different package name. in the beginning of the project I chose <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.thenewboston" android:versionCode="1" android:versionName="1.0" > until this point non of the Intent caused no error, but I guess when I was using Class ourClass = Class.forName("com.thenewboston.travis." + cheese);...
python,multithreading,class,python-2.7
Assuming you want to create a new instance of the TlsListener class each time you accept a socket, you can simply leave your code as is, and create a new class inside of tls_listener function: while True: newsock, fromaddr = s.accept() ssl_sock = context.wrap_socket(newsock, server_side=True) threading.Thread(target=tls_listener, args=(ssl_sock,)).start() def tls_listener(ssl_sock): t...
You have declared the constructor in Calculator.h but have not defined it in Calculator.cpp (or anywhere else). Adding Calculator::Calculator() { } to Calculator.cpp will fix the issue....
python,class,tkinter,attributes
I think what you want is def input_check(which_box): getattr(my_window,which_box).delete(0, "end") return 0 input_check("get_info_box") but its hard to tell for sure...
You can do that but you need to add Gson library for that. Your two classes are as follows in which i have add constructor to add few items: public class Customer{ public String Name; public String Surname; public Customer(String Name, String Surname){ this.Name = Name; this.Surname = Surname; }...
In order to deny direct access to your class attribute, you can define it as private. By doing that, construction like $allen->userName will throw an error. This is also known as encapsulation. First make sure that you initialize your class object properly. In PHP you should define your constructor using...
php,class,oop,laravel,laravel-5
That's simple php stuff. Set the attribute as static and access it with ::. class LanguageMiddleware { public static $languages = ['en','es','fr','de','pt','pl','zh','ja']; } @foreach (App\Http\Middleware\LanguageMiddleware::$languages as $lang) ... @endforeach You should not have that in a middleware though. You'd better add a configuration (i.e in /config/app.php) with that array, and...
javascript,jquery,class,if-statement,jquery-selectors
You can traverse and find the $matches's 'header' element and exclude while sliding up. var $header = $matches.prevAll('li.header'); //hiding non matching lists excluding matches heare $('li', list).not($matches).not($header).slideUp(); ...
c++,class,inheritance,polymorphism
You create a vector of Parent objects. There's no polymorphism here. Vectors contain values. If you want a polymorphic container, you have to use something else. It's just as if you did Parent myObject; No matter what you do to myObject later, it will still be a Parent. Even if...
Without really knowing the particulars of your situation, the classic answer is this: if your class initializer requires a whole bunch of arguments, then it is probably doing too much, and it should be factored into several classes. Take a Car class defined as such: class Car: def __init__(self, tire_size,...
c++,performance,class,loops,struct
This is easy-peasy work for a modern optimizer to handle. As a programmer you might look at that constructor and struct and think it has to cost something. "The constructor code involves branching, passing arguments through registers/stack, popping from the stack, etc. The struct is a user-defined type, it must...
I've successfully and effortlessly being able to do what you ask using JD plugin for eclipse: http://jd.benow.ca/ It gets installed in less than 5 minutes and it's really smooth and flawless....
class,haskell,opengl,types,uniform
Try adding -XFlexibleContexts and the constraint, literally, to your existing answer: {-# LANGUAGE FlexibleContexts #-} mvpUnif :: ( GL.UniformComponent a , Num a , Epsilon a , Floating a , AsUniform a , AsUniform (V4 (V4 a)) ) => (GLState a) -> ShaderProgram -> IO () Usually this is the...
It is doing correct. For finding text, do this points_no = driver.find_element_by_class_name("fs18").text ...
Virtual base classes can only be initialized by the most derived class. Calls to a constructor of a virtual base from a non most-derived class are ignored and replaced with default constructor calls. This is to ensure that the virtual base subobject is initialized only once: The correct code should...
The simplest thing you can do is pass into the example method an argument that references the Map: public static void example(Map<String, RpgPerson> team) { System.out.println(team.get("Dragon")); } ...
No, this is not possible. Especially since a is a local variable. If a had been a field, there might have been a remote possibility to solve this using some reflection / stack trace hack....
I've never tried this with dynamically generated/compiled classes, but... Try using Class.forName("com.example.YourClassName") to get a reference to the Class: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String) and then use Class.newInstance() to create an instance of the class: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#newInstance() For this to work, com.example.YourClassName would have to be visible to your class loader. For example: Class clazz...
obj is a reference to the object of type foo , your understanding is correct. In line 1 , JVM creates a new instance (ojbect) of type foo (new memory is allocated in the heap) , and obj now stores the reference to that memory location, lets assume that memory...
python,function,class,oop,methods
Not sure I got your question right, but you may want to try: def getStats(self): return "width: %s\nheight: %s\narea: %s\nperimeter: %s" % (self.width, self.height, self.area(), self.perimeter()) To satisfy requirements 4 and 6, I would suggest something like: class Shape(object): def area(self): raise NotImplementedError def perimeter(self): raise NotImplementedError class Rectangle(Shape): def...
c++,class,c++11,data-structures,graph
I advise you to use a Link structure, to represent an edge in the graph: struct Link { Node *N; float weight; } Then each Node can contain vector<Link> neighbors; This way there is no duplication of Nodes. There is a duplication of weights, since if Node A has a...
Since you use $this->my_array and the function has the keyword public, I'm going to assume these two methods are in a class definition, so you also have to define, that you want to call a class method and not a normal function. This means you have to change: usort($this->my_array, 'cmp');...
Raman is right in that all objects inherit the methods of the Object class, so you technically can't have a class without any methods at all. But if you're talking about a class that doesn't override any of those methods, don't have methods of its own, and most/all fields are...
You just use inheritance - there is no need to worry about maintaining an agregate self.tree instance: your subclass will just have the behavior of the original superclass wherever you don't override it. The only non-straightforward part is exactly that for some whatever reason, the lxml library is designed to...
Your can use Reflection Object action = ???; // perhaps you need .newInstance() for action class // Hopefully you have a interface with performLogic String methodName = "performLogic"; try { Method method = action.getClass().getMethod(methodName, param1.class, param2.class); method.invoke(action, param1, param2); } catch (SecurityException | NoSuchMethodException e) { // Error by get...
c++,function,class,inheritance,virtual
1.Constructor design How will you set their gravity center ? Point center_of_grav(a,b); ... Square square(c); // what's the gravity center ? You have to design the constructor of the derived, so that it has all information required to construct the base: Square square(center_of_grav, c); To achieve this, you have to...
You can use reflection APIs to call the exclusiveMethod . The code would look something like - Method m = var.getClass().getMethod("exclusiveMethod", null); if(m != null) { m.invoke(var, null); } You can get more information about relfection APIs here - http://docs.oracle.com/javase/tutorial/reflect/index.html Another way to get this is by casting the var...
The only problem I see is in the implementation of setName itself. You don't use the input variable thename at all. public void setName(String thename){ this.name=name; } The last line should be this.name = thename; But this would not give you the error you say you got (that setName doesn't...
Just call the Parent operator: Child& operator=(const Child& other) { mC = other.mC; Parent::operator=(other); return *this; } Or really, don't implement either operator since both are trivial! ...
You aren't going to run into contention problems due to your classes being static. Your IP.IP() method class is pure (i.e. it does not change the state of anything) and contains no locks, so there is no chance of there being any contention there. You do potentially have problems in...
javascript,class,oop,object,methods
Welcome to the world of javascript where you are not using it to just paint and moves boxes :) Coming to your question: //Initialize objects var spaceButton = new Navigation('#spaceWarp'); var stars1 = new Stars('#stars1'); var stars2 = new Stars('#stars2'); var stars3 = new Stars('#stars3'); The initialization of your objects...
javascript,class,prototype,ecmascript-6
In ES6, there is no "class" when code is running, you just have a constructor function, or an object. So you could do if (typeof Thingy === 'function'){ // It's a function, so it definitely can't be an instance. } else { // It could be anything other than a...
Though B has all the methods and property dose A have, you can not cast object of B to a reference of A. That means - A a = (A) new B(); is invalid unless B extends A. And here A is a final class so you can not extends...
c#,asp.net,entity-framework,class
I think what you want to do on AddStreet looks like this. You save the Street and return the result. public Street AddStreet(string streetName) { Street street = new Street(); street.StreetName = streetName; using (var _db = new DataContext()) { // Dodaj Street u bazu [AD_STREET] _db.DB_Street.Add(street); _db.SaveChanges(); } //...
javascript,class,reactjs,javascript-objects,ecmascript-6
React.Component is a plain javascript function, since es6 classes are syntactic sugar around them. So we could use whatever es5 class-like concept we like e.g. I just borrowed Backbone's extend method here: // From backbone var extend = function(protoProps) { var parent = this; var child; var extendObj = function(obj1,...
For arguments sake, lets assume you didn't declare next to be a pointer, but a value instead: Node<T> next; Then when you assign to next you create a new copy of the original object, leading you to have two unrelated and unconnected copies. A pointer is exactly what it sounds...
Your current code is changing emailObj from an object to a string on each iteration of the loop, instead of amending a property of the object itself. Also note that you can use the . style selector to match elements by their class. To achieve what you require, you can...
c++,class,parameters,header,enumerator
You have a circular dependency problem. Your files can include each other all they want, but the #pragma once at the top means that only one sees the other one; not that each sees the other. There are several ways to go here. One way would be to remove the...
Your getSquare function doesn't do anything, but just defines the variable square (does not return it though). Make it return it as an int, like int myClass::getSqure(int n) { // make sure to change the declaration also int square = n * n; return square; } then do cout <<...
java,class,constructor,instance,accumulator
You should create the Test instance before the loop instead of in each iteration. Test cashPlus = new Test(); do { System.out.print("Enter amount:"); cashMoney = hold.nextDouble(); cashPlus.addPoints(cashMoney); System.out.print("Do you want to enter amount again?(y/n):"); response = hold.next(); if(response.equalsIgnoreCase("n")){ System.out.print("TOTAL: " + cashPlus.getMoney()); } } while(response.equalsIgnoreCase("y")); Each time you create a...
java,class,interface,java-8,utility-method
Going based on the person who coined the Constant Interface pattern an anti-pattern, I would say although you don't intend the client(s) to implement the interface, it's still possible, possibly easier, and shouldn't be allowed: APIs should be easy to use and hard to misuse. It should be easy to...
No, there is no way to achieve that. To access another object, you need a reference to it. If you don't have a reference stored locally, you need a way to find or obtain that reference. If you have neither, you can't access it....
From the docs. First make sure you include the namespace. #using System.Collections.Generic; You can declare a dictionary like this. var dictionary = new Dictionary<string, int>(); // this is the best way! or without var Dictionary<string, int> dictionary = new Dictionary<string, int>(); The way you posed the question it seems like...