And now for some digital nirvana ;-)

Dig this… 16 YouTube Videos all playing from the same SWF… digital nirvana !!!

digital nirvana

Once upon a time, in the not too distant past, I was asked to fix a rather nagging performance issue that involves playing more than 4 videos using a SWF-based streaming video player… well my first impression was to reduce the number of SWFs to just 1 while increasing the number of videos being displayed to something closer to 16 !!!

While I was not told doing this would be “difficult” or otherwise “challenging”… I was met with a certain amount of healthy skepticism and not only because the development team I relayed my solution to was not all that informed as to what the Flash Player might be able to do – they also were not all that informed as to what the Flash Player might be able to do in this regard.

So far, I can tell you all there is no real trick in playing 16 YouTube videos using the same SWF via a Browser – this works !!!   Now I think I will try to update the video player to use something a bit slicker than the standard-run-of-the-mill Chromeless YouTube Video Player…

Gee, I wonder what else I might make this little ditty do… ?!?  Maybe deploy itself to the Android Market ?!?  Oh, yes, this would be far too easy !!!  Try doing this with Java – I dare you !!! – LOL

Enjoy !!!

Why can human knowledge not be quantified ? And why do some people feel the need to try… ?!?

How much experience do you have using blah… ?!?

My response to this kind of query is generally… “A lot”… however saying you have a lot of experience does not seem to satisfy the questions for those who just have to think there is a way to quantify knowledge or experience.

The closest you will ever get to being able to measure human knowledge is…

You can measure how close to your own understanding someone else might be until… they end-up having more than you and then your ability to measure falls apart.

You can make people play guessing games to see if they know some things you think you know but again, the moment the person you want to measure has more than the one doing the measuring the process fails to please.

You cannot measure human intuition…

The ability to reach outside the box cannot be measured.

The ability to do more with one’s mind than has been done in the past cannot be measured.

I have interviewed with some hiring managers who said up-front they did not want anyone who had any kind of intuition…

I have to wonder about anyone who claims to be agains the use of human intuition just because… well my pets won’t be intuitive but they are animals… humans should use intuition because they can… simple as that.

Get over it gang, human knowledge cannot be measured any more than human experience can be measured.

Anyway, I prefer to take myself out of the equation when trying to determine what level of experience someone might have, were I the one faced with trying to staff some kind of software project.

It’s just too easy to become so self-deluded to feel as-though everyone sees it the way I do so as to render oneself so incredibly silly-stupid as to make the process of trying to make the determination useless.

If we all just focus on what the technologies we work with can do and then figure out what these technologies should do and then work on how to make these technologies do what they were not designed to do we might all learn enough to be useful.

Far too many people like to focus only on what the docs say these technologies can do and nothing more.

Python tuples are immutable

Yeah, until you learn how to change the contents of a tuple and then you figure-out there almost no such thing in Python as an immutable Constant other than the mere conceptualization of what immutable might mean so long as you really didn’t want something that is actually immutable and really unchangeable - but again, I might think my windows on the front of my home are immutable so long as nobody ever figure-out how to pick up a rock… in real terms I just cannot be that stupid as to really think, for any period of time, that my windows at home are any more immutable than Python tuples – cuz they are NOT.  Windows can be broken and Python tuples can be modified… rocks and lists were all made to resolve these issues.  On the other hand, I also don’t let just everyone know where I live either… and I don’t leave any loose rocks laying around my front yard.  Immutable is not always immutable… and constants are not always all that constant – at least where Python is concerned.

Sorry Google but when you want to talk to me abut Python you might give some thought to just how many hours I have spent using Python to solve real problems… and “yes” I too read where tuples are immutable but… that’s all the farther that one goes because I happen to know there’s almost no such thing in Python as a Constant where Constant really means “…it can’t be changed…” and by “…can’t be changed…” I mean “…it really cannot be changed…” and by this I mean “…it really cannot be changed because the freaking runtime keeps it from being changed…”.  Talk to me about immutable in Python when there is really no way to make Python change the value of the thing you wish me to think is “immutable”.  Darn, then you learn anyone can code a Python extension that gets a pointer to that pesky immutable variable with the evil intent to make a change without the consent of the Python runtime.  Oops !!!   Hey, maybe I just know Python better than you thought… OR… I am able to see how to get things done when everyone else says it ain’t possible.  Either way, I want to do it more when Google tells me I should not… maybe this has something to do with how one ends-up rebelling against one’s parents… or maybe Google simply wants to take control over how we use Python… either way… whenever I am told it’s not possible I tend to look for ways to make it possible – doing this helps me learn and learning is good.  LOL

 

Here’s what you won’t find coded using HTML 5 !!!!

HTML 5 ?!?  Huh ?!?

Here are 2 rather fun games that don’t use HTML 5 but do use Flash !!!

EdgeWorld

and

Galaxy Online II

Both of these games are fun and both make heavy use of Flash; both of these games will NEVER be coded using HTML 5 without Flash !!!

Why ???

Because HTML 5 without Flash is just too darned easy to hack !!! (See also: The End of JavaScript for the details…)

Heck, Flash is easy enough to hack but HTML 5 is just crazy easy to Hack… and by “Hack” I mean, I can make the silly thing do whatever I want including but not limited to being able to modify the runtime code being executed by my browser.

Any realtime multiplayer game coded using nothing but HTML 5 and JavaScript would simply be far too easy to hack to the point of making it just too easy for any suitably skilled person able to make this ill-fated HTML 5 game do whatever this suitably skilled person might want it to do including but not limited to making one’s in-game characters have god-like powers with infinite resources.

Flash is far more difficult to hack !!!

You can find tools one can use to hack a currently running Flash video game however – nobody gets to change the code without being forced to jump through some rather intense technical hoops and Flash-based SWFs can be obfuscated and encrypted where JavaScript cannot – in real terms.

Long Live Flash !!!

Hey, I just cannot be an Adobe-hater !!!

I happen to think Flash has more to offer than HTML 5 even though there are those who seem to want Flash to cease to exist… I think Flash is here to stay !!!

I never thought I might ever find a Free-to-Play Flash game I might be tempted to dump real money into and then I bumped into Galaxy Online II and suddenly I began to feel as-though I might be able to take-over the whole Galaxy… now I think Free-To-Play games can be really super cool as well as rather lucrative when they are well done !!!

Enjoy the games !!!

 

What does Google think about Python ?!?

Earlier today I had the opportunity to speak with someone from Google who shared these thoughts with me in regard to Python…

  • Python tuple objects are immutable.
    • Tuple objects lack the methods that allow elements of a tuple to be modified however… tuple objects can be recast into lists, list objects are not so immutable, after the change has been made the lists can be recast as tuples, as follows:
      • x = (1,2) # x is a tuple
      • try:
      •     x[0] = 11 # this throws an error
      • exception:
      •     print ‘Error Will Robinson…’
      • x = list(x) # now x is a list
      • x[0] = 11 # this will not throw an error
      • x = tuple(x) # x is now a tuple once again
    • Obviously the guy from Google who thinks he knows Python failed to understand this one simple thing about tuple objects – “tuples were made to be cast as lists”.
      • Python tuple objects are as immutable as your typical window pane is not breakable… so long as you “think” your typical window pane cannot be broken and nobody ever picks-up a rock you are right… however… rocks were made to be thrown by people who have hands.
      • The fact is… there are no objects in Python that are truly immutable however tuple objects lack the methods that allow tuple members to be changed unless one recasts a tuple as a list and then back again after one makes the desired changes.
    • Additionally, one could create a tuple subclass that allows tuple members to be modified.
  • When a global variable is assigned a tuple it is not possible to make any changes to that global variable.
    • This is just False !!!
      • There is NOTHING special about variables that hold onto tuple object instances.
    • It is possible to make Constants using Python however this does not come with Python’s Standard Library.
      • Tuples are NOT Constants !!!
        • Variables that hold onto tuple pointers are NOT Constants !!!
      • Not even a Python Constant will be truly immutable even when a Global Variable is used to point to the Instance of a Python Constant.
        • The only way to make a Global or Static Variable in Python capable of being truly immutable is to place that Constant into a Module that lacks the ability to allow the Constant to be changed at runtime.
        • Your typical Python Global Variable can be changed, which is to say your typical Global Variable is Read-Write and can be assigned to a different value that can be a different Instance of a Python object.
  • The special thing about inheritance is multiple inheritance.
    • One man’s special is another man’s who-cares ?!?
    • Apparently even Google’s Search Engine does not even know “what is special about python inheritance“… LOL
      • You might think something “special” about Python might be clearly special to everybody however this is just NOTthe case in this instance…
        • Is it any wonder I might not know this specific aspect when, it seems, not enough other people do know about it to make it to the first page of a Google search… ROFL
          • On the other hand, not even this Google guy was aware of how special this aspect of Python was to himself but then we can all hold things close to our own hearts without getting approval from the rest of the world…

I was disappointed in how little this one guy from Google seems to know about Python OR maybe I just dug deeper into Python than Google has…

OR

Maybe this Google guy think only hackers play-around with Python to the point of knowing the language inside and out and maybe this Google guy is only able to use Python in the most superficial way possible. ?!?

The great thing about computers is Computer Science… we can all test our assumptions to see whether or not our assumptions are correct or as-correct as we with them to be.

Also it’s refreshing to me to realize how human this one Google Guy is because he is not immune from wishful thinking where Python is concerned.  He “wishes” Python was a much better language than it is.  He “wishes” tuples are actually as immutable as he “wishes” them to be even though the language does not support his wishes, he continues to harbor his fanciful wishes.  This speaks well of his inner-child…

I like to stick with the Science… the way Python actually works… devoid of my own wishful thinking… Python tuples are no more immutable than my nose is unable to be cut off… I prefer to leave my nose intact just as one would have to prefer to leave a tuple instance unchanged but not because a tuple CANNOT be changed, just that one prefers a tuple to be immutable.

Try it for yourself and you be the judge !!!

How can you tell when a software algorithm can be parallelized ?!?

Parallelization is a pet project of mine and has been for many years…

Recently while interviewing at Paypal, who by the way does NOT hire talent and especially NOT talent who has a conscience… more on Paypal later…

Parallelization…

Algorithms that seek to collect data can be more easily parallelized than the other kind.

This means Analytics Application are ripe for parallelization because Analytics is all about collecting aggregations from raw data.

How to…

All you need is a bit of experience with TCP/IP in the form of connecting a Process running on one computer to a Process running on another computer – repeat this as often as possible and you too can create a network of Processing Nodes each of which is connected to the rest – the real magic lies in how you achieve this goal in an efficient manner.

Next, you need to find a way to ask each Processing Node to perform part of the Aggregation Process using one chunk of data each.

Then find a way to get each Processing Node to make the request for its chunk of data at the same time, or as close to the same time as possible.

Then find a way to collect the results from each Processing Node in a parallel manner – again this is where you will find some magic.

HINT: TCP/IP is useful because it allows many requests to be made at the same time while allowing many results to be collected very quickly.

Before you know it you have the framework for parallelization but again there is ample room for doing some magic within the framework.

HINT: Python is easier because Stackless Python combined with multi-threading combined with TCP/IP combined with Parallel Python and Cython and Psycho… can’t get this much bang for the buck from Ruby but you can surely try if you must.

HINT: If you are me then you are more able to use your experience to make your typical non-aggregating algorithm into one that does perform some kind of aggregation… ;-)

Paypal’s Interviewing Practices and the lack of ethics

Once upon a time I interviewed with a guy at Paypal who asked me to code a datetime object using an unspecified language who also did not stop to consider his goal had already been accomplished in just about every computer language he or I might wish to use… I mentioned this during the interview and he failed to respond with anything other than his lack of desire to continue… My question was driven by my desire to be ethical since I consider it unethical to write code where an existing solution has already been accomplished and I wanted to know “why” I was being asked to violate my own sense of ethics – not that I am opposed to violating my own sense of ethics so long as I can respond to the questions I might be asked to give later during the deposition in case the request results in legal action as most ethical breaches will eventually.  I have to wonder about professionals who have not spent any of their time thinking about what may or may not be ethical behavior.

Why “ethics” ?

Because I am a professional software engineer who, from time to time, write code by the hour and if I were to spend billable time (as would be the case for Paypal in this instance) working on code I knew had already been written I would feel as-though I was taking money under false pretenses and this would be a breach of ethics for me – not that this guy at Paypal would feel the same because he apparently had no ethical problems with asking me to work on code I would not otherwise have to build.  Maybe if those who ask contractors to work would also stand behind their requests someone like me would not need to develop a sense of ethics… think about it because I have.

Realistic Interviews !?!

 I think professional interviews should be 100% reflective of real life which means if I were actually asked by some manager to work on some kind of datetime object and I actually did so rather than using one that already exists I would hope I would be considered to be less than honest because aren’t I supposed to know what software objects already exist versus the ones that don’t ?!?
Consider the other side of this coin… what if I approached my manager at Paypal and asked him or her for permission to work on something and the something I asked to work-on already exists as some kind of open source thing I could have much more easily used ?!?   Would I have to not be completely dishonest if I were being paid by the hour to spend billable time working on something that already exists ?!?  I would think so but then I have a sense of ethics and a desire to not waste my professional time.
Interviews should be as realistic as possible in terms of professional expectations and professional ethics.
Nonetheless… I will remain as ethical as I can be even when it takes money out of my pocket because this is the right thing to do !!!
And those who lack ethics are generally punished by the legal system sooner or later…

Yet another Ruby on Rails Programming Test *yawn*

So here we are again with yet another Ruby on Rails Programming Test !!!

Maybe someday people will just take as proof everything else I have publishing here but that day has apparently not yet arrived…

The Problem – Not exactly any kind of real business problem…

Rails Exercise:

We’d like you to create a simple Rails 3 application.
Create models that allow a user to follow another user.
The user model’s only attribute is “name”. You may scaffold the create action.
Create an interface that accepts post requests that allows users to
“follow” other users.
The user’s “index” action should list all of the users.
The user’s “show” action should show:
1) The user’s name
2) The users the user is currently following (with a button to remove
that following)
3) The users the user is not following (with a button to add that following)
4)  The users currently following this user
Do not create a login system for this exercise.

The Solution

Download it from this link; only 600 KB  !!!

SalesForce.Com Issues/Gotchas aka. Bugs/Defects (Redux)

Yet another undocumented SalesForce Bug has been found !!!

This bring my personal count to 4 and climbing…

It is rather odd these kinds of defects can exist in such a prestigious framework as SalesForce/VisualForce/Apex with so many people using it when other web-based Frameworks (Django and others) do NOT exhibit such behaviors.

I have revised #2 and #3 while adding some additional issues since my last post:  (This is where experience counts… since I know what is expected when unexpected things begin to happen…)

SalesForce.Com Issues/Gotchas aka. Bugs/Defects

1). Cannot reference null values for <apex:outputText/> or <apex:inputText/>.
2). Cannot reference non-String objects with <apex:outputText/> or <apex:inputText/>.
2a). Under some circumstances VisualForce will allow String objects to be referenced by <apex:outputText/> or <apex:inputText/> tags however after a certain threshold has been reached the Force IDE will begin to complain about what it calls SObject references after which the only acceptable correction is to reference the result from a SOQL query – this can clash with #2 for some obvious reasons.
3). Cannot retrieve the Parameters from ApexPages.currentPage() more than exactly once because the associated [Parameters] information is lost for subsequent invocations.
4). Cannot pass back the ApexPages.currentPage() when expecting the user to make a correction in the <apex:inputText/> because the VisualForce page will remember the values from the Parameters thus ignoring user inputs for subsequent form posts.

SSH Man-in-the-Middle (Soft Hack)

A successful SSH based Man-in-the-Middle Attack might go something like this – there are a couple of assumptions but lazy or novice users will probably fall for some if not all of this.

Assumption #1

This works best for users of newly established VMs such as those one might provide via Amazon EC2.

Assumption #2

Users who simply do not pay close attention to the details will fall for much of what this attack seeks to accomplish.

Assumption #3

SSH Terminal Emulation is required by this hack.  This can be easily built using Python and Paramiko.

Assumption #4

SCP Emulation is also required to make this hack work. This can be easily built using Python and Paramiko.

Assumption #5

The end-user connects to the man-in-the-middle via SSH Terminal Emulation to begin using the newly created VM Instance via password login or a key-pair provided by the attacker – this works best when the end-user will just go along with the process of allowing someone else to do most of the work such as but not limited to allowing someone else to establish the key-pair for a seemingly newly created VM instance.

Assumption #6

Assuming the end-user chose to connect using SCP via a password, the man-in-the-middle need not even know if the provided password is correct since the SSH Terminal Emulation is just window-dressing.

Assumption #7

The SSH Terminal and SCP Emulation is all fake – I was almost sure this was already understood by most readers.  The end-user will “see” what is expected to be a newly installed Linux file system with either nothing in the .ssh folder or a key-pair that was provided for the user – the goal here is to get the end-user to accept the man-in-the-middle as legit even though it is not at-all legit.

Assumption #8

Once the end-user has either accepted the provided key-pair or uploaded a real public key the fun can begin.

Assumption #9

Now that the end-user has jumped through all the required hoops and is really using a fake SSH/SCP Terminal Session the user will make requests of the fake man-in-the-middle “proxy” (the man-in-the-middle will coax the end-user into uploading a real Public Key – the one the real end-point is using – the end-user will also be coaxed into revealing the Private Key’s Passphrase all the while thinking this makes the whole system that much more secure…); you can probably see where this is going by now.  If not, there is still some hope for your soul.

Assumption #10

The Internet is a huge house of cards surrounded by smoke and mirrors and enough assumptions to allow almost any hacker with sufficient skill to achieve whatever may be desired.  User’s have to know more than the hackers they share their Internet experiences with… most users do not.

Enjoy !!!

Ubuntu Enterprise Linux 11.04

Everyone knows RHEL (Red Hat Enterprise Linux) is all “Enterprise” just because “Enterprise” is in the name – Doh !

Now I give you Ubuntu Enterprise Linux 11.04

Method #1

This is really super-simple because as my readers know, the simpler the better even when simpler is largely overlooked by the masses just because it may be perceived to be just-too-simple.

  1. Install RHEL (any version works) in the computer of your choice, the computer cannot be older than 2009 to work. (DO NOT USE A VM)
  2. Install the latest VirtualBox version 4 or later.
  3. Create a VM using VirtuBox 4.x in RHEL.
  4. Install Ubuntu Server or Desktop 11.04 in the VM you created in Step #3.
  5. Done !
Now all I/O will flow through the Magic Unicorn OS known as Red Hat – and now Ubuntu is using Red Hat for everything one might want to use Red Hat for.
Just in case some of you are reaching for your phones to call the nearest Asylum to have little ole me admitted on a 72 hour administrative hold… LOL  Keep in mind this is being done by your nearest Citrix Xen Server 5.6 because it too uses RHEL as the host OS in which you will be expected to run your Guest OS in a VM – hehe.
I actually proposed this to a Manager I have been working with but the idea was not embraced, probably because it just makes too damned much sense especially if the product you are managing runs in Debian but your I.T. support people are telling you they only want to support RHEL because it is the blessed OS for the Enterprise.
This same technique works great for any guest OS – Windows in Red Hat and other variations.

Method #2

Install apt-get in Red Hat – don’t laugh this has been done – google it.
At the end of the day, Linux code is Linux code and works in any Linux – all roads lead to the same China where Linux is concerned.  Even those who say they are adding special powers to their favorite Linux (RHEL) are really doing very little other than branding the same Linux everyone else is using for their own use.  If any Linux were gonna have Magic Unicorn Powers it would surely be RHEL because it says it is “Enterprise” and it should surely be measurable better than the rest but this just ain’t the case, in real terms.
Slap apt-get into RHEL and you get the best of Ubuntu in RHEL without Ubuntu.

Conclusions

Crazy ideas only seem “crazy” until they catch on with the masses.
Not all that long ago we all might have scoffed at the idea of using Virtual Machines rather than real computers until we learned just what the Cost of Operation is for a real server – deploy real servers by the thousands and then get ready to buy your own small power plant because that’s exactly what you will need every time you see the electric bill.
The idea of running a VM inside a host OS is nothing more than yet another way to achieve the same goal as VMWare for ESX and other products you have to spend real money to get.
Cheers.

SleepyMongoose meets the Python after dark

 

For a while now I have been looking for a reasonable

REST-based NoSQL Database I can use from the Google App Engine just to avoid
having to pay Google for their database fees.

Earlier today… I was able to make the SleepyMongoose
snuggle-up with the Python for some after-hours fun in the dark.

SleepyMongoose

You can read-up about SleepyMongoose here.

It’s a REST-based interface for MongoDB that runs as a lightweight Python HTTP
Server – I will eventually get around to making this SleepyMongoose wake-up by
shoving some Stackless Python into it just for fun and because Stackless always
makes Python work better.

So what does the SleepyMongoose need once I get around to
using it from the Google App Engine ?

SleepyMongoose needs a slick Python wrapper so I don’t gotta
deal with all that REST stuff which after-all the REST interface is only needed
because Google doesn’t seem to care much about bandwidth consumption for
anything other than their own database and it just makes sense to make Google
give me a FREE No-Cost MongoDb Proxy which is what this is all leading to
anyway.

SleepyMongoose meets the Python

 So, since I am a pretty good Python coder I chose to whip-up

a Magic little object that allows me to get away from REST and right into
Python objects.

I implemented the SleepyMongoose API as documented in their Wiki.

Keep in mind the code presented here requires the Vyper
Logix Library as found here (shameless
plug, of course
).

Here’s a sample of what the usage looks like:

from vyperlogix import
mongodb

 

if (__name__ == ‘__main__’):

    import os,sys

   

    sm = mongodb.SleepyMongoose(’127.0.0.1:27080′).db(‘gps_1M’).collection(‘num_connections’)

    results = sm.connect()

    print ‘sm.connect() #1
–> ‘
,results

 

    results = sm.server(‘mongodb://127.0.0.1:65535′).connect()

    print ‘sm.connect() #2
–> ‘
,results

 

    results = sm.server(‘mongodb://127.0.0.1:65535′).name(‘backup’).connect()

    print ‘sm.connect() #3
–> ‘
,results

 

    results = sm.docs({“x”:2}).insert()

    print ‘sm.insert() #1
–> ‘
,results

 

    results = sm.find({“x”:2})

    print ‘sm.find() #1 –>
,results

 

    results = sm.criteria({“x”:2}).remove()

    print ‘sm.remove() #1
–> ‘
,results

 

    results = sm.docs().insert({“x”:3})

    print ‘sm.insert() #1
–> ‘
,results

 

    results = sm.find({“x”:3})

    print ‘sm.find() #2 –>
,results

 

    results = sm.remove({“x”:3})

    print ‘sm.remove() #2
–> ‘
,results

 

    results = sm.docs([{"x":2},{"x":3}]).insert()

    print ‘sm.insert() #3
–> ‘
,results

 

    results = sm.criteria({“x”:2}).remove()

    print ‘sm.remove() #3
–> ‘
,results

 

    results = sm.criteria([{"x":3}]).remove()

    print ‘sm.remove() #4
–> ‘
,results

 

    results = sm.insert([{"x":2},{"x":3}])

    print ‘sm.insert() #4
–> ‘
,results

 

    results = sm.remove({“x”:2})

    print ‘sm.remove() #5
–> ‘
,results

 

    results = sm.remove([{"x":3}])

    print ‘sm.remove() #6
–> ‘
,results

    pass

Here’s the rest of the code:  (Simple and to the point, no nonsense code,
in a few hours…)

__copyright__ = “”"\

(c). Copyright 2008-2011,
Vyper Logix Corp., All Rights Reserved.

 

Published under Creative
Commons License

(http://creativecommons.org/licenses/by-nc/3.0/)

restricted to
non-commercial educational use only.,

 

http://www.VyperLogix.com
for details

 

THE AUTHOR VYPER LOGIX
CORP DISCLAIMS ALL WARRANTIES WITH REGARD TO

THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND

FITNESS, IN NO EVENT SHALL
THE AUTHOR BE LIABLE FOR ANY SPECIAL,

INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING

FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT,

NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION

WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE !

 

USE AT YOUR OWN RISK.

“”"

import logging

 

import urllib2

 

import simplejson

 

from vyperlogix import
misc

from vyperlogix.misc import _utils

from vyperlogix.classes import MagicObject

 

arg0 = lambda args:args[0] if (misc.isIterable(args)) and (len(args) > 0) and (misc.isString(args[0])) else None

list0 = lambda args:args[0] if (misc.isIterable(args)) and (len(args) > 0) and ( (misc.isList(args[0])) or (misc.isDict(args[0])) ) else []

int0 = lambda args:args[0] if (misc.isIterable(args)) and (len(args) > 0) and (misc.isInteger(args[0])) else None

bool0 = lambda args:args[0] if (misc.isIterable(args)) and (len(args) > 0) and (misc.isBooleanString(args[0])) else None

 

__only__ = lambda value,target:value if (str(value).lower().capitalize() == str(target).lower().capitalize()) else None

 

class SleepyMongoose(MagicObject.MagicObject2):

    def __init__(self,sleepy_mongoose):

        ”’

        See
also: https://github.com/kchodorow/sleepy.mongoose/wiki/

        ”’

        toks = sleepy_mongoose.split(‘:’)

        try:

            self.__sleepy_mongoose__ =
sleepy_mongoose if (misc.isString(toks[0]) and misc.isInteger(int(toks[-1]))) else None

        except:

            self.__sleepy_mongoose__ =
None

        self.__database__ = None

        self.__collection__ = None

        self.__server__ = None

        self.__server_name__ = None

        self.__last_exception__ =
None

        self.__n__ = None

        self.__docs__ = None

        self.__criteria__ = None

        self.__newobj__ = None

        self.__fields__ = None

        self.__sort__ = None

        self.__skip__ = None

        self.__limit__ = None

        self.__explain__ = None

        self.__batch_size__ = None

        self.__id__ = None

       

    def __http_get__(self,url):

        data = None

        try:

            response = urllib2.urlopen(url)

            json = response.read()

            data = simplejson.loads(json)

        except Exception, ex:

            self.__last_exception__ =
_utils.formattedException(details=ex)

            data = None

        return data

 

    def __http_post__(self,url,parms=()):

        from vyperlogix.url._urllib2 import
http_post

        data = None

        try:

            json = http_post(url,parms)

            data = simplejson.loads(json)

        except Exception, ex:

            self.__last_exception__ =
_utils.formattedException(details=ex)

            data = None

        return data

 

    def __handle_exceptions__(self):

        if (not self.__sleepy_mongoose__):

            logging.error(‘ERROR: Cannot understand “SleepyMongoose(%s)”‘
% (self.__sleepy_mongoose__))

        elif (not self.__database__):

            logging.error(‘ERROR: Cannot understand “db(%s)”‘ % (self.__database__))

        elif (not self.__collection__):

            logging.error(‘ERROR: Cannot understand “collection(%s)”‘
% (self.__collection__))

   

    def __getattr__(self,name):

        self.__n__ = name

        return super(SleepyMongoose, self).__getattr__(name)

 

    def __call__(self,*args,**kwargs):

        if (self.__n__ == ‘db’):

            self.__database__ = arg0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘collection’):

            self.__collection__ =
arg0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘server’):

            self.__server__ = arg0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘name’):

            self.__server_name__ =
arg0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘docs’):

            self.__docs__ = list0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘criteria’):

            self.__criteria__ = list0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘fields’):

            self.__fields__ = list0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘sort’):

            self.__sort__ = list0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘skip’):

            self.__skip__ = int0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘limit’):

            self.__limit__ = int0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘batch_size’):

            self.__batch_size__ =
int0(args)

            self.__reset_magic__()

        elif (self.__id__ == ‘id’):

            self.__id__ = int0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘explain’):

            self.__explain__ =
__only__(bool0(args),‘True’)

            self.__reset_magic__()

        elif (self.__n__ == ‘newobj’):

            self.__newobj__ = list0(args)

            self.__reset_magic__()

        elif (self.__n__ == ‘find’):

            if (self.__sleepy_mongoose__)
and (self.__database__) and (self.__collection__):

                p = []

                if (self.__criteria__):

                    p.append(tuple(["criteria",simplejson.dumps(self.__criteria__)]))

                    self.__criteria__ = None

                if (self.__fields__):

                    p.append(tuple(["fields",simplejson.dumps(self.__fields__)]))

                    self.__fields__ = None

                if (self.__sort__):

                    p.append(tuple(["sort",simplejson.dumps(self.__sort__)]))

                    self.__sort__ = None

                if (self.__skip__):

                    p.append(tuple(["skip",'%d'%(self.__skip__)]))

                    self.__skip__ = None

                if (self.__limit__):

                    p.append(tuple(["limit",'%d'%(self.__limit__)]))

                    self.__limit__ = None

                if (self.__explain__):

                    p.append(tuple(["explain",'%s'%(self.__explain__)]))

                    self.__explain__ = None

                if (self.__batch_size__):

                    p.append(tuple(["batch_size",'%d'%(self.__batch_size__)]))

                    self.__batch_size__ = None

                if (self.__server_name__):

                    p.append(tuple(["name",self.__server_name__]))

                url = ‘http://%s/%s/%s/_%s’
% (self.__sleepy_mongoose__,self.__database__,self.__collection__,self.__n__)

                return self.__http_post__(url,tuple(p))

            else:

                self.__handle_exceptions__()

            self.__reset_magic__()

        elif (self.__n__ == ‘insert’):

            if (self.__sleepy_mongoose__)
and (self.__database__) and (self.__collection__):

                p = []

                if (self.__docs__):

                    p.append(tuple(["docs",simplejson.dumps(self.__docs__)]))

                    self.__docs__ = None

                else:

                    p.append(tuple(["docs",simplejson.dumps(list0(args))]))

                    self.__docs__ = None

                if (self.__server_name__):

                    p.append(tuple(["name",self.__server_name__]))

                url = ‘http://%s/%s/%s/_%s’
% (self.__sleepy_mongoose__,self.__database__,self.__collection__,self.__n__)

                return self.__http_post__(url,tuple(p))

            else:

                self.__handle_exceptions__()

            self.__reset_magic__()

        elif (self.__n__ == ‘update’):

            if (self.__sleepy_mongoose__)
and (self.__database__) and (self.__collection__):

                p = []

                if (self.__criteria__):

                    p.append(tuple(["criteria",simplejson.dumps(self.__criteria__)]))

                    self.__criteria__ = None

                if (self.__newobj__):

                    p.append(tuple(["newobj",simplejson.dumps(self.__newobj__)]))

                    self.__newobj__ = None

                if (self.__server_name__):

                    p.append(tuple(["name",self.__server_name__]))

                url = ‘http://%s/%s/%s/_%s’
% (self.__sleepy_mongoose__,self.__database__,self.__collection__,self.__n__)

                return self.__http_post__(url,tuple(p))

            else:

                self.__handle_exceptions__()

            self.__reset_magic__()

        elif (self.__n__ == ‘more’):

            if (self.__sleepy_mongoose__)
and (self.__database__) and (self.__collection__):

                p = []

                if (self.__id__):

                    p.append(tuple(["id",'%d'%(self.__id__)]))

                    self.__id__ = None

                if (self.__batch_size__):

                    p.append(tuple(["batch_size",'%d'%(self.__batch_size__)]))

                    self.__batch_size__ = None

                if (self.__server_name__):

                    p.append(tuple(["name",self.__server_name__]))

                q = ‘?’+‘&’.join(['='.join(list(t)) for t in p]) if (len(p) > 0) else

                url = ‘http://%s/%s/%s/_%s%s’
% (self.__sleepy_mongoose__,self.__database__,self.__collection__,self.__n__,q)

                return self.__http_get__(url)

            else:

                self.__handle_exceptions__()

            self.__reset_magic__()

        elif (self.__n__ == ‘cmd’):

            if (self.__sleepy_mongoose__)
and (self.__database__):

                p = []

                _c_ = list0(args)

                if (_c_):

                    p.append(tuple(["cmd",simplejson.dumps(_c_)]))

                url = ‘http://%s/%s/_%s’ % (self.__sleepy_mongoose__,self.__database__,self.__n__)

                return self.__http_post__(url,tuple(p))

            else:

                self.__handle_exceptions__()

            self.__reset_magic__()

        elif (self.__n__ == ‘remove’):

            if (self.__sleepy_mongoose__)
and (self.__database__) and (self.__collection__):

                p = []

                if (self.__criteria____):

                    p.append(tuple(["criteria",simplejson.dumps(self.__criteria____)]))

                    self.__criteria____ = None

                else:

                    p.append(tuple(["criteria",simplejson.dumps(list0(args))]))

                    self.__criteria____ = None

                if (self.__server_name__):

                    p.append(tuple(["name",self.__server_name__]))

                url = ‘http://%s/%s/%s/_%s’
% (self.__sleepy_mongoose__,self.__database__,self.__collection__,self.__n__)

                return self.__http_post__(url,tuple(p))

            else:

                self.__handle_exceptions__()

            self.__reset_magic__()

        elif (self.__n__ == ‘connect’):

            _token = self.__n__

            if (self.__sleepy_mongoose__):

                p = []

                if (self.__server__):

                    p.append(tuple(["server",self.__server__]))

                if (self.__server_name__):

                    p.append(tuple(["name",self.__server_name__]))

                url = ‘http://%s/_%s’ % (self.__sleepy_mongoose__,_token)

                return self.__http_post__(url,tuple(p))

            else:

                self.__handle_exceptions__()

            self.__reset_magic__()

        else:

            logging.debug(‘DEBUG: Cannot understand “%s(%s,%s)”‘ % (self.n,args,kwargs))

        return self

 

 

Follow

Get every new post delivered to your Inbox.

Join 328 other followers