Implementing weak references in Python

Normal Python references to objects increment the object’s reference count thus preventing it from being garbage collected. If a user desires creating weak references, the weakref module can be used: import weakref class Rezha(object): pass To create a weak reference, the ref class is used: # object instance rezha = Rezha() # weak reference to our object r = weakref.ref(rezha) Then, you can call the reference object: print(r) # <weakref at 0x01414E40; to 'Rezha'....

April 30, 2017 · 1 min · Rezha Julio

Translating Scanner tokens into primitive types

The Scanner class can be used to break an input into tokens separated by delimiters. Scanner also has methods to translate each token into one of Java’s primitive types. Delimiters are string patterns and are set in the following way: Scanner s = new Scanner(input); s.useDelimiter(pattern); If we need to read a file containing a set of integers, and calculate the total, we can use Scanner’s nextInt method: int sum = 0; //create a new instance of Scanner Scanner s = new Scanner( new BufferedReader( new FileReader("in....

April 29, 2017 · 1 min · Rezha Julio

Listing a file system's root directories

Using the static FileSystems class, you can get the default FileSystem (note the missing s) through the getDefault() method. The getRootDirectories() method of FileSystem can be used to acquire a list of root directories on a file system. An object of type Iterable is returned, so the directories can be iterated over in the following way: FileSystem sys = FileSystems.getDefault(); Iterable<Path> d = sys.getRootDirectories(); for (Path name: d) { System.out.println(name); } This is available from Java 1....

April 28, 2017 · 1 min · Rezha Julio

The Console class

The Java.io.Console class provides methods to access the character-based console device, if any, associated with the current Java Virtual Machine. This class is attached to the System console internally. Console class provide means to read text and passwords from the console. To read a line as a String: Console console = System.console(); String myString = console.readLine(); To read a password as an array of chars: Console console = System.console(); char[] pw = console....

April 27, 2017 · 1 min · Rezha Julio

Next, Function or Method ?

While in Python 2 it was possible to use both the function next() and the .next() method to iterate over the resulting values of a generator, the later has been removed with the introduction of Python 3. Consider the sample generator: def sample_generator(): yield "a" yield "b" yield "c" In Python 2: a = sample_generator() print(next(a)) # prints 'a' print(a.next()) # prints 'b' But in Python 3: print(next(a)) # prints 'a' print(a....

April 26, 2017 · 1 min · Rezha Julio