I'm going through this example of a force based layout.
http://bl.ocks.org/sathomas/774d02a21dc1c714def8
The layout is defined as
force = d3.layout.force()
.size([width, height])
.nodes(dataNodes)
.links(dataLinks);
Later in the code though the author iterates through the link array with this call
force.linkStrength(function(link) {
if (link.className === 'red') return 0.1;
return 1;
});
How does the author know that function(link) will iterate over the link array and not the node array?
Because when you write this:
force = d3.layout.force()
.size([width, height])
.nodes(dataNodes)
.links(dataLinks);
You're doing what is called a method chaining. d3.js is known to use them a lot and each method chaining (with this framework at least) returns an object, depending of the method you call. With this particular code, it acts this way:
Set the size of the force object and return the force object
Set the nodes of the force object and return the nodes property of force
Set the links of the nodes object, and return the links property of nodes
So, each method chaining that you add returns something different. At the end of all the method calls, the whole thing will be considered as returning the return value of your last call, and it will assign it to the variable at the left of the = operator. Here, your force variable.
It's exactly as if you wrote:
force = d3.layout.force()
force = force.size([width, height])
force = force.nodes(dataNodes)
force = force.links(dataLinks)
When, later on, you iterate over your force variable, you necessarily iterate over the links array, because that's what you assigned to force.
Tip 1: The tricky part is that here, and generally in d3.js, each method does not return the same objects. Both d3.layout.force() and size() return the actual force object, whereas nodes() returns the nodes object and links() returns the links object. It's cascading method chaining. Each element of the chain is called on the object returned by the previous method call.
Tip 2: you can understand from this that it's not necessarily the best fit to name this variable force.
There's also a cool explanation that goes into further details from Scott Murray.
Related
I was learning emptyArray() in Kotlin, but I can't assign values in it (which is for obvious) and neither I can set it's size. What is the use of emptyArray in Kotlin?
There are cases where you want to fallback to an empty array or empty list. For example:
return someInputArray?.filterNotNull() ?: emptyArray()
In this case if I have a valid input array, I filter out null values, otherwise if the source array was null I return an empty array. Therefore an array is always returned instead of a null. Empty lists and arrays are probably more common than passing around nullable lists or arrays in Kotlin.
So yes, it is empty and you cannot add to it, just as no JVM array is expandable once allocated.
Similar to the java.util.Collections.emptyList() methods and its counterparts for Maps, etc., these methods are handy when you are calling a method which takes an array/collection as argument, but you don't want/need to provide any elements in that collection. You can either instantiate a new empty array/collection or use one of the helper methods.
If the above use case is very common in your scenario, you are safing memory by using the helpers as always the same instance is reused instead of creating new instances again and again. Otherwise it's mainly "syntax candy" making your code more readable and easier to understand.
emptyArray() function returns an empty array of size 0. it doesn't take any paramters (Nor size, neither elements). you can use it as rvalue in assignment operations. You can use empty array to dump all the values in a pre-existing arrays and set it's size to 0.
Note: it is better to return an empty than returning an array of nulls, as it'll not create any null point exceptions in further operations.
var array=arrayOf(1,2,3,4,5);
array = emptyArray() //The array datais dumped and size is set to 0;
array = arrayOf(0,1,2)
Arrays are fixed size containers. The emptyArray() function creates an array of 0 length, and you really can't do much with this. You can't store anything in it, and you can't resize it.
A common use case where you need an empty array would be as a default value for a property that will be set to a different array at a later point. This can be better than storing null in that property by default, because you don't have to deal with handling the possible null value when your code uses the array. For example, you can safely iterate over an empty array.
For a simple example:
class NumberHolder {
var numbers: Array<Int> = emptyArray()
fun printNumbers() {
numbers.forEach { println(it) }
}
}
The usage of this class would look something like this:
val nh = NumberHolder()
nh.printNumbers() // prints nothing
nh.numbers = arrayOf(1, 2, 3)
nh.printNumbers() // prints 1, 2, and 3 on separate lines
RealBasic's Introspection is kinda of different than what I expected.
My intention is:
Create a MainObject from which other objects will inherit two, three methods, to simplify.
Method 1-> Returns to the child class itself all of its properties, types and values.
Method 2-> Would call Method1 and with the information, save the child Object.
So, for method 1 I thought about writing a generalised introspection which for each child class would easily return what I need for Method 2 to do its work.
Why do I want this? So I can have tens of objects knowing how to save, draw themselves without worrying too much about a modification here or there on the properties etc...
But using what RealBasic tutorials and reference offers doesn't work, since it requires me to have it happening outside the object etc... i.e.: I can easily, inside ObjectA, get ObjectB's properties, methods etc, but I want to get inside ObjectA, A's properties, not B's
Thanks in advance...
I've found out how... Very simple, create the MainClass and inside of it a simple method WhoAmI which could return an array, dictionary etc...
Dim thisClassTypeInfo As Introspection.TypeInfo = Introspection.GetType(Self)
Dim thisClassProperties() As Introspection.PropertyInfo = thisClassTypeInfo.GetProperties
Dim thisClassMethods() As Introspection.MethodInfo = thisClassTypeInfo.GetMethods
For Each myProperty As Introspection.PropertyInfo In thisClassProperties
// Then here use myProperty.Name, myProperty.Value(Self).StringValue
// or myProperty.Value(Self).anyotheroption and create a dictionary
// or array with the results and return it.
Next
I am using GPARs asynchronous functions to fire off a process as each line in a file is parsed.
I am seeing some strange behavior that makes me wonder if I have an issue with thread safety.
Let's say I have a current object that is being loaded up with values from the current row in an input spreadsheet, like so:
Uploader {
MyRowObject currentRowObject
}
Once it has all the values from the current row, I fire off an async closure that looks a bit like this:
Closure processCurrentRowObject = { ->
myService.processCurrentRowObject (currentRowObject)
}.asyncFun()
It is defined in the same class, so it has access to the currentRowObject.
While that is off and running, I parse the next row, and start by creating a new object:
MyObject currentObject = new MyObject()
and start loading it up with values.
I assumed that this would be safe, that the asynchronous function would be pointing to the previous object. However, I wonder if because I am letting the closure bind to the reference, if somehow the reference is getting updated in the async function, and I am pulling the object instance out from under it, so to speak - changing it while it's trying to work on the previous instance.
If so, any suggestions for fixing? Or am I safe?
Thanks!
I'm not sure I fully understand your case, however, here's a quick tip.
Since it is always dangerous to share a single mutable object among threads, I'd recommend to completely separate the row objects used for different rows:
final localRowObject = currentRowObject
currentRowObject = null
Closure processCurrentRowObject = { ->
myService.processCurrentRowObject (localRowObject)
}.asyncFun()
I wrote a simple tag manager class in matlab, and I'm struggling (or maybe over-thinking ;-) with naming my class methods appropriately. The class is called tag_manager. Here are my question regarding a clear API and implementation:
for adding a tag, should I call the method add or add_tag? same goes for removing.
for renaming a tag, should I call the method rename_tag or rename?
I always feel like adding the _tag suffix, so that it is clear what a method is acting upon.
nbr_tags is a counter that keep track on the number of tags that are currently stored. I sometimes need to access this number, and so instead of going through the list of tags and calculating the number of entries, I thought to return this value through a class method. Is return_nbr_tags the way to go, or could this be named more succinctly?
Very often, I need to know the index of a tag, which is in turn used to look up some elements in some other matrix. In order to prevent code to become to long, I called this method simply inx() which is supposed to be an abbreviation for return_tag_index. I'm aware that today I do know what inx() stands for, but in two weeks from now I'll probably won't be able to remember. So what is the best way of naming these kind of methods?
here's the class definition:
properties (SetAccess = private, GetAccess = public)
tag_names = {}; % store the tags
tag_rel_indx = []; % the relative tag index
tag_abs_indx = []; % the absolute tag index
end
properties (SetAccess = private, GetAccess = public, Hidden = true)
nbr_tags = 0;
abs_tag_counter = 0;
end
methods
% add single tag to list. should be 'add' or 'add_tag'?
function obj = add_tag(obj, name)
end
% remove single tag from list
function obj = remove_tag(obj, name)
end
% short-cut for 'return_tag_index'
function indx = inx(obj, name)
indx = return_tag_index(obj, name);
end
% rename tag
function obj = rename_tag(obj, old_name, new_name)
end
% re-order tags by name
function obj = reorder_by_name(obj)
end
% return number of tags stored in tagmanager
function nbr_tags = return_nbr_tags(obj)
nbr_tags = obj.nbr_tags;
end
end
Thanks a lot!
There is always a trade-off between using highly explicit function names (which is really helpful to understand code) and creating code that's easy to develop and use. If you need to make shortcut names for methods, it's a sign that you have moved to far toward explicit function names.
In your case, since you're creating a tag manager, I would drop tag from the methods, and instead start the convention of instantiating your tag manager class as tags = tagManager;, such that the method of adding tags is written either tags.add(...) or add(tags,...). Adding more explicit method names will help, though, when you're adding something other than tags, e.g. tags.addGroup. Your index method then becomes index(tags,name), which is, in my eyes, both short and clear.
PS: Why have a returnNumberOfTags method? You can just read from the property, and add set/get methods if necessary.
In my opinion, and having had to use other people's code before, I find it VERY helpful when the method/function names are clear and descriptive. I'd much rather someone be verbose with the name of their function but at the same time you don't want to be overly verbose with it.
For instance your return number of tags function. I would personally name that something like GetNumberOfTags. For functions that I use to set a particular value I use SetParticularValue.
I do lean away from the underscores though. That's probably most just a habit I picked up from the coding practices we have at work.
The biggest thing to remember is being consistent throughout the whole class. AND don't forget to have useful comments if the function isn't entirely clear =P It's horrible when you have to come back through and rework someone's code and there's a real dirth of information about what variables are being used for and what the function really is meant to do ;).
Yeah, I'm struggling with that. I cannot distinguish among them because every explanation I read is so unclear and philosophical enough. Can someone clear up these definitions for me ? Thanks guys.
These definitions apply as much to procedural-programming as oop ? Thanks.
Over time, the way people use each of these terms has changed (and will likely keep changing), but here's what they probably mean if you're reading articles written in the last decade or so:
Functions (aka subroutines) are relatively self-contained, relatively independent pieces of code that make up a larger program.
Methods are functions attached to specific classes (or instances) in object-oriented programming.
Properties are an object-oriented idiom. The term describes a one or two functions (depending on the desired program behavior) - a 'getter' that retrieves a value and a 'setter' that sets a value. By convention, properties usually don't have many side-effects. (And the side-effects they do have usually have limited scope: they may validate the item being set, notify listeners of a change, or convert an object's private data to or from a publicly-declared type.)
Function is a combination of instructions coupled together to achieve some result. It may take arguments and return result. If a function doesn't return a result it is usually called a procedure. Examples:
function drawLine(x1, y1, x2, y2):
// draws a line using Bresenham's algorithm from x1,y1 to x2,y2.
// doesn't return anything
function <number> add(a, b):
// adds a to b and returns the result as a number
return a + b
So functions are to do some particular work. For example, when you need to draw a polygon of 3 lines as a part of a vector image it is more convenient to call drawLine thrice than to put all the routine for line drawing inline.
Methods ("member functions") are similar to functions, they belongs to classes or objects and usually expresses the verbs of the objects/class. For example, an object of type Window usually would have methods open and close which do corresponding operations to the object they belong.
Properties are as in everyday language and technically are fields of objects/classes with dedicated getter/setter routines (which can be considered as methods. There are languages that don't have properties and this behavior is achieved using a private field+get/set methods.).
Field - A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.
Property - A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field.
Method - A method is a code block containing a series of statements. In C#, every executed instruction is done so in the context of a method.
Procedure - A procedure is a code block containing a series of statements.
Function - A function is a code block containing a series of statements. That return operation result.
Function is a standalone construction like trim(), strlen(), fopen() etc.
function myAbcFunction() { ... }
Method is a function of object. It is defined in class. Property is just property of object:
class MyClass {
public $property; // Public property: $objInstance->property
protected $property2; // Protected property
public function doSth() {
// That's a method. $objInstance->doSth();
}
}
I suggest read the manual Classes and Objects chapter.
In OOP the primary structure is an object.
Method is a named action which can be applied to the object.
Property is a named value, which the object has. For example, object Human has the property 'Age'.
function is a more general thing, than a method. It is just an action, that doesn't belong to any object. But method is a function that belongs to the object.
a)Function
Refers to block of statements that perform a particular task and return a value.
b)Procedure
Refers to the building blocks of a program that do not return a value when called.
c)Method
Refers to the action that object can perform.