Calculate Root of Any Whole Number in Java

The following Java program can find any root of a whole number. The logic is simple. Start by guessing some number and check if that is the correct value. If that overshoots then subtract some from the guess number else add to it. We add or subtract some fixed constant. If that constant is too big then we divide that constant by 10 to get a finer number.

#!java
public class CubeRoot {

    public static void main(String[] args) {
        System.out.println(String.format("%.2f", cubeRoot(0, 2)));
        System.out.println(String.format("%.0f", cubeRoot(8, 0)));
        System.out.println(String.format("%.4f", cubeRoot(10, 4)));

        System.out.println(String.format("%.4f", root(10, 2, 4))); // Square Root
        System.out.println(String.format("%.4f", root(100, 5, 4))); // 5th Root
    }

    private static double cubeRoot(int n, int precision) {
        return root(n, 3, precision);
    }

    private static double root(int n, int root, int precision) {
        double x = n / 5.0; // 5 is better than 4 since this will have bigger
                            // step. 3 is very bad choice since there are some
                            // no.s which will never have rational output when
                            // divided by 3, e.g. 5.
        double powX;
        double d = 10;
        double lastX = 0;
        double lastLastX = 0;
        do {
            powX = Math.pow(x, root);
            if (matches(powX, n, precision))
                return x;
            else {
                if (matches(lastLastX, x, precision)) {
                    // If the lastLast x value is same as current then we are
                    // trapped in a loop, since the current d is not small
                    // enough. We need to now step at finer precisions.
                    d /= 10;
                    if (matches(d, 0, precision + 1)) {
                        return x;
                    }
                }
                lastLastX = lastX;
                lastX = x;
                if (n < powX) {
                    x -= d;
                } else {
                    x += d;
                }
                // System.out.println("(x=" + x + ", d=" + d + ")");
            }
        } while (true);
    }

    private static boolean matches(double a, double b, int precession) {
        return ((int) (a * (long) Math.pow(10, precession)))
                - ((int) (b * (long) Math.pow(10, precession))) == 0;
    }

}

Django-Select2: Select2 for Django

Select2

Select2 is an excellent Javascript framework which transforms mundane <select> fields to cool looking and searchable. This is a very handy when there are quite a number of options to select from.

Basic Select2 options field.

Select2 also allows dynamic fetching of options from server via Ajax. Select2’s webpage has a neat demo of this.

Select2 fetching data via Ajax. In the above screenshot it is using RottenTomatoes’ API to get them.

Django-Select2

Django includes basic select widget, which just generates <select><option>...</option>...</select> tags.  Although their ‘looks’ can be improved using basic CSS, but we hit a usability problem when there are too many options to select from. This is where Django-Select2 comes into picture.

Light Components

Django-Select2 includes many widgets suited to various use-cases. Select2Widget and Select2MultipleWidget widgets are suited for scenarios where we have a static list of choices which may not may not be large. They are not meant to be used when the options are too many, say, in thousands. This is because all those options would have to be pre-rendered onto the page and Javascript would be used to search through them. Said that, they are also one the most easiest to use. They are almost drop-in-replacement for Django’s default select widgets, and they look much much better.

Heavy Components

HeavySelect2Widget and HeavySelect2MultipleWidget widgets are suited for scenarios when the number of options are large and need complex queries (from maybe different data sources) to get the options. This dynamic fetching of options undoubtably requires Ajax communication with the server. Django-Select2 includes a helper JS file which is included automatically, so you need not worry about writing any Ajax related JS code. Although on the server side you do need to create a view specifically to respond to the queries. The format of the response is decided by the JS code being used on the client side. The included abstract view – Select2View, will make sure to format the response into the format expected by the helper JS code. Below is a example on how to use it.

#!python
from django.db.models import Q
from django_select2 import Select2View, NO_ERR_RESP
from .models import Employee

class EmployeeSelect2View(Select2View):
    def check_all_permissions(self, request, *args, **kwargs):
        user = request.user if not (user.is_authenticated() and user.has_perms('emp.view_employees')):
            raise PermissionDenied

    def get_results(self, request, term, page, context):
        emps = Employee.objects.filter( Q(first_name__icontains=term) | Q(last_name__icontains=term) | Q(emp_no__icontains=term))
        res = [ (emp.id, "%s %s" % (emp.first_name, emp.last_name),) for emp in emps ]
        return (NO_ERR_RESP, False, res) # Any error response, Has more results, options list

How many such views you will need depends totally on your use-case. From Django-Select2 there is no restriction on their reuse. If you feel that writing these views are too much of a hassle then you have an alternate option – sub-class AutoSelect2Field field. In your sub-classed field you need to override security_check(self, request, *args, **kwargs) and get_results(self, request, term, page, context) methods. When your field will be instantiated for the first time, it will register its own instance with AutoResponseView. When the related field is used in the browser, the queries would be directed to AutoResponseView which will direct it to your ‘auto’ field instance. For ‘auto’ fields to work you must use the following code in your urls.py to register the url for AutoResponseView.

#!python
urlpatterns += patterns("", url(r"^select2/", include("django_select2.urls")), )

Django-Select2 Fields

The following fields are available in Django-Select2.

  • Select2ChoiceField – Uses Select2Widget.
  • Select2MultipleChoiceField – Uses Select2MultipleWidget.
  • HeavySelect2ChoiceField – Uses HeavySelect2Widget.
  • HeavySelect2MultipleChoiceField – Uses HeavySelect2MultipleWidget.
  • ModelSelect2Field – Uses Select2ChoiceField. It additionally requires queryset argument. It similar to Django’s ModelChoiceField.
  • AutoSelect2Field – Uses HeavySelect2ChoiceField. Auto register’s itself with AutoResponseView.
  • AutoModelSelect2Field – Similar to AutoSelect2Field, but like ModelSelect2Field, normalizes values to Django model objects.

Download Django-Select2

You can download it or fork it from https://github.com/applegrew/django-select2. You can also add this to you pip requirement files as:-

-e git+https://github.com/applegrew/django-select2.git#egg=django-select2

Update: Now can simply add django_select2 to your pip requirement. If you want to install it manually then you can simply run:-

pip install django_select2

Update: Now you can install beta version of django_select2 compatible with Python3.

pip install Django-Select2-Py3

Closing Statement

It is recommended that you go through the codes to familiarize yourself with how to efficiently use Django-Select2. The code is not very complex so you should not face much problem in understanding it.

iFlickr PHP Script: Create mRSS feed of interesting pictures on Flickr.com

Did you notice the “Flickr Gallery” on top right corner of the home page of this blog? The picture slide show is provided by Google’s Ajax Slide Show, but this post is not about that. Google’s Slide Show needs a mRSS feed, which it parses to get the list of thumbnails it wants to present. mRSS is just a normal RSS feed particularly tailored for presenting media. It gets its ‘m’ from media. In this case it is picture media. For my blog’s “Flickr Gallery”, I have scheduled a cron job which runs every day at 5.30 am UTC. This way every day my blog gets fresh set of interesting pictures to present. You can get a good example of mRSS feed on my site at http://www.applegrew.com/util/if.xml. Safari and Firefox will use their own styling rules to style this XML. If you want to check it out the way I want it, then view it in Google Chrome.

The Script

This PHP script spits out mRSS feed of the interesting pictures on Flickr.com. This script can be invoked from web or directly from command line. When invoked it connects to Flickr using its API and gets the list and all related infos from there. Flickr likes to call this list – Flickr Interestigness.

Download package (License GPL v2)

How to use this script

This scripts accepts a number of parameters:-

  • api_key (Default: NoKeyGiven) – The Flickr API key. Get it from here.
  • pg (Default: 1) – Which page to fetch. This is to help you paginate if that makes sense for you.
  • per_pg (Default: 10) – How many pictures you want per page. So, if you want 11th to 20th most interesting pictures then set pg to 2 and per_pg to 10.
  • thumbnail_type (Default: , i.e. not set) – Possible values are – SquareThumbnail, Small, Medium or *Large. *The picture of the type set here is set as thumbnail picture. If the type specified is not available then no thumbnail is mentioned. If this is not set then all possible picture sizes would be listed as thumbnails in the feed, with the bigger pics at the top.
  • min_size (Default: 0, i.e. not set) – If set (i.e. it is not set to zero) then the pic which is equal or just larger than this dimension will be chosen as thumbnail.

This script can be run from command line as shown below:-

$ /usr/bin/php iflickr.php --api_key=key_here --min_size=240 > mrss.xml

When run from web:-

http://example.com/iflickr.php?api_key=key_here&min_size=240

Please note: To be able to run this from web, you need to set $bind_address variable in the script as empty string.

CInk version 2 finally released!

Finally CInk version 2 has been released.

Some key new things

  • New website with complete API documentation and guides on how you can use CInk JS code.
  • Finally released the full source code of CInk renderer and compiler. License – GPL v3.
  • CInk finally supports all the features of original CFDG, including Paths.
  • CInk has introduced support for texts which extends the capabilities of CFDG considerably. Check out the cool demo – Neon Letters. To learn more about it see – “Text transforms” section here.

Last but not the least, you can post comments on CInk website. The comments section is at the bottom of each page.

Goto Cink website – cink.applegrew.com.

CInk version 0.1 preview

[AG_PH_ON]

For past few weeks I have been on working on this. This has come out to be quite good. The above video shows rendering being done on latest Google Chrome browser. I have tested my code in Chrome and FireFox 5, and it works with reasonable performance.

About CInk

Sometime back I stumbled upon Aza Raskin’s very inspiring and beautiful Algorithm Ink[sup] 1[/sup]. It’s easy to use and you can create some truly amazing art. From there I learnt that it is a Javascript implementation of Context Free Design Grammar (CFDG), invented by Chris Coyne[sup]2[/sup]. Also, that CFDG contains more language constructs which Algorithm Ink didn’t support, like loops, z-index, etc. Instead it provided a link to C implementation of CFDG – Context Free Art[sup]3[/sup]. When I saw what still more amazing stuffs people have done there, particularly a B/W artwork, “Bleak” [sup]4[/sup], then I decided of re-implementing CFDG in Javascript.

Why Javascript

CInk is not a replacement for its C counterpart – Context Free, but it adds to it. First this allows a way for random nettizens to stumble on it and create something amazing, even if by chance. Second, CInk clearly separates parsing and rendering logics, making it possible to be used to draw your site’s background. Yeah I find that cool. 😉 Third, as a side-effect of the trick Aza used to keep the browser from locking up as the script draws the art, makes for a visual treat. Which the C counterpart cannot, as it is too efficient and fast to render. 😛

Algorithm Ink

CInk can be considered an enhancement of Algorithm Ink, as the rendering logic’s fundamental concepts are from it.  Except for that it is purely a new product. The parser has been created using JSCC[sup]5[/sup] with slightly modified grammar than given in Context Free’s source code.  Output rendered by CInk is now very much like its Context Free. CInk retains support for MOUSEMOVE and MOUSECLICK predefined rules, introduced by Aza. One major difference between CInk and Algorithm Ink is that, unlike Context Free, Algorithm Ink used HSL to RGB color conversion, but CInk uses HSV to RGB conversion. Also CInk code has been made modular and it doesn’t litter the global namespace.

Overall CInk is compatible to Algorithm Ink and Context Free. So, codes for Algorithm Ink will run in CInk and codes for Context Free may need to be scaled down. You can use size {} command for that.

Future

This is just a preview. I haven’t released CInk yet. It will be online when I have created its site. It will be GPL licensed. Currently path commands like LINETO, etc. are not supported, but will be in little future. Though tile{} command is supported but the output will be less than appealing. I am not sure if it is possible to fix this now. For now tile{} will remain broken. Since <canvas> doesn’t support z-indexes, so CInk creates stack of them when rendering a code that refers to z indices. At the end of the rendering all these stacks are merged into the one. This is of course a hack, but can’t help it unless HTML5 specification and browser developers do something about it.

  1. http://azarask.in/projects/algorithm-ink (Algorithm Ink)
  2. http://korsh.com/cfdg/ (CFDG inventor)
  3. http://www.contextfreeart.org/mediawiki/index.php/Context_Free_Art:About (Context Free Art)
  4. http://www.contextfreeart.org/gallery/view.php?id=2550 (Bleak Artwork)
  5. http://jscc.jmksf.com/ (JS Compiler Compiler)

jDCBot nearing its finale – The 1.0 milestone

The open source project DC client framework jDCBot (http://jdcbot.sourceforge.net) I have been working on is now nearing its 1.0 milestone. Version 1.0 means that it will have all the required features that a DC client framework should have, like – managing shared files, hashing them, creating file lists, queuing downloads and resuming them when the source is available, multi-source downloading, etc.

This framework has been created from scratch, so unlike other DC clients which share DC++‘s code for the core functionality and hence provide similar features, jDCBot will provided unorthodox features. For example DC++ clients and its derivatives allow users only to provide different user names and passwords for different hubs. jDCBot on the other hand allows you to be passive or active in different hubs. So you can be passive and active both at the same time. This is useful in situations when say you are inside your college LAN and you want to connect to hubs inside the LAN and outside on the Internet too. In this case DC++ and derivatives will force you to be passive, but in jDCBot you can be active for inside your LAN and passive for outside the LAN. Well, you also get to set different descriptions, email addresses and connection types too.

There some other cool features too which are not present in other clients like allowing you to set different upload speeds for different users (this way you can give your friends a boost), blocking upload to particular users (could be misused but we are giving the power and it is upto the clients who will use jDCBot to make the decisions), using the virtual file list concept which allows the users to organize their share into virtual directories without actually reorganizing the files, the file names in file list can even be different from the original allowing the user to rename the file in the file list without rehashing or allowing the user to re-associate the virtual file with the actual file after the original file name/path changes so that rehashing is not required, and many more. Last but not the least it is pure JAVA framework and hence is platform independent and is very modular.