Skip Navigation
Contrast AAA
  • JavaScript startsWith and endsWith Implementation for Strings

    Posted on Wednesday, July 01, 2009

    JavaScript is missing the sometimes useful startsWith and endsWith functions that are available in Python, C#, etc. One can argue that startsWith is not necessary since its just as easy to check the index of the prefix and compare to 0:

    function strStartsWith(str, prefix) {
        return str.indexOf(prefix) === 0;
    }
    

    Using indexOf to implement endsWith is possible as well but not as cool and short as using regular expressions:

    function strEndsWith(str, suffix) {
        return str.match(suffix+"$")==suffix;
    }
    

    If you are a fan of monkey-patching JavaScript's builtin classes:

    String.prototype.startsWith = function(prefix) {
        return this.indexOf(prefix) === 0;
    }
    
    String.prototype.endsWith = function(suffix) {
        return this.match(suffix+"$") == suffix;
    };
    

    Then you can do:

    >>> "rickyrosario.com".startsWith("ricky")
    true
    >>> "rickyrosario.com".endsWith(".com")
    true
    
    Be the first to respond... Leave Your Comment
  • TwitAPI.com - Twitter API Explorer

    Posted on Wednesday, May 27, 2009

    The official Twitter API documentation is not bad, but being in a wiki it's usability isn't great. I found myself frequently clicking back and forth to find different API methods. So, I spent a couple of nights creating a tool to learn and explore the Twitter API interactively.

    TwitAPI.com

    twitapi.com screenshot

    In addition to the (hopefully) better usability, you can enter parameters and call the methods to see the response.

    The site itself was built on Django and uses Twitter OAuth for authentication and for making authenticated API calls.

    Be the first to respond... Leave Your Comment
  • See Which Twitterers Don’t Follow You Back In 15 Lines of Python

    Posted on Wednesday, May 13, 2009

    Today, I came across a Ruby script that Jerod Santo blogged about yesterday: See Which Twitterers Don’t Follow You Back In Less Than 15 Lines of Ruby. I quickly felt the need to implement the same in Python to see how much code it would take.

    I used the awesome Minimalist Twitter API for Python, which I have used and blogged about before. After a couple refactorings, I ended up with 15 lines:

    from twitter.api import Twitter
    
    USERNAME = 'r1cky' # set to your/any username
    
    twitter = Twitter() # username/password not required for these calls
    friends = twitter.friends.ids(screen_name=USERNAME)
    followers = twitter.followers.ids(screen_name=USERNAME)
    guilty = [x for x in friends if x not in followers]
    
    print "There are %s tweeps you follow who do not follow you" % len(guilty)
    
    for user_id in guilty:
        user = twitter.users.show(user_id=user_id)
        print "%s follows %s and has %s followers." % \
                  (user['name'], user['friends_count'], user['followers_count'] )
    

    It does seem like more code than the Ruby version. I especially like how you can subtract one array from the another in Ruby:

    guilty = base.friend_ids - base.follower_ids
    

    I am not sure that this can be made as elegant in Python... Can it?

    To make the code re-usable, I created a function that takes a username and returns the users that don't follow back:

    from twitter.api import Twitter
    
    def no_follow_back(username):
        twitter = Twitter()   # username/password not required for these calls
        friends = twitter.friends.ids(screen_name=username)
        followers = twitter.followers.ids(screen_name=username)
    
        def get_user_by_id(user_id):
            return twitter.users.show(user_id=user_id)
    
        return [get_user_by_id(x) for x in friends if x not in followers]
    

    A usage example (I saved the function above in a file called twitfun.py):

    >>> from twitfun import no_follow_back
    >>> guilty = no_follow_back('papajuans')
    >>> len(guilty)
    16
    >>> guilty[0]["screen_name"]
    u'shanselman'
    
    One person has commented... Read Comments | Leave Your Comment
  • Improved GeoIP Lookup Function in Python

    Posted on Tuesday, April 28, 2009

    The other day I found another GeoIP lookup service that happens to also return JSON, which is awesome given the great JSON support in Python. The JSON returned looks like this:

    {
    "Ip" : "74.125.45.100",
    "Status" : "OK",
    "CountryCode" : "US",
    "CountryName" : "United States",
    "RegionCode" : "06",
    "RegionName" : "California",
    "City" : "Mountain View",
    "ZipPostalCode" : "94043",
    "Latitude" : "37.4192",
    "Longitude" : "-122.057",
    }
    

    Today, the service I was using seems to be dead so I quickly reimplemented my function and it turned out much cleaner.

    from urllib import urlopen, quote
    import simplejson
    
    GEOIP_LOOKUP_URL = 'http://iplocationtools.com/ip_query.php?ip=%s&output=json'
    
    def geo_ip_lookup(ip_address):
        """
        Look up the geo information based on the IP address passed in
        """
        lookup_url = GEOIP_LOOKUP_URL % ip_address
        json_response = simplejson.loads(urlopen(lookup_url).read())
    
        return {
                'country_code': json_response['CountryCode'],
                'country_name': json_response['CountryName'],
                'locality': json_response['City'],
                'region': json_response['RegionName'],
                'longitude': json_response['Longitude'],
                'latitude': json_response['Latitude']
        }
    
    

    Just like before, from the interpreter:

    >>> geo_ip_lookup('81.83.5.11')
    {'locality': u'Gent', 'region': u'Oost-Vlaanderen', 'longitude': u'3.7167', 'latitude': u'51.05', 'country_code': u'BE', 'country_name': u'Belgium'}
    >>>
    

    JSON FTW!

    Be the first to respond... Leave Your Comment
  • Quick and Dirty GeoIP Lookup Function in Python

    Posted on Tuesday, March 10, 2009

    I found a free GeoIP lookup service, that happens to have a simple API for getting the result in XML: http://api.hostip.info/?ip=65.34.176.69. The returned XML looks like this:

    
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <HostipLookupResultSet version="1.0.0" xmlns="http://www.hostip.info/api" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.hostip.info/api/hostip-1.0.0.xsd">
     <gml:description<This is the Hostip Lookup Service</gml:description>
     <gml:name>hostip</gml:name>
     <gml:boundedBy>
      <gml:Null>inapplicable</gml:Null>
     </gml:boundedBy>
     <gml:featureMember>
    
      <Hostip>
       <gml:name>Miami, FL</gml:name>
       <countryName>UNITED STATES</countryName>
       <countryAbbrev>US</countryAbbrev>
       <!-- Co-ordinates are available as lng,lat -->
       <ipLocation>
        <gml:PointProperty>
    
         <gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
          <gml:coordinates>-80.2108,25.7757</gml:coordinates>
         </gml:Point>
        </gml:PointProperty>
       </ipLocation>
      </Hostip>
     </gml:featureMember>
    </HostipLookupResultSet>
    

    I had never done anything with XML in python so I figured I would write a function to wrap the API call. A few google searches led me to minidom and the rest was cake. The function takes in an IP address (string) and returns a dictionary with the geo information. I am a python noob and this code feels a little sketchy to me, so any feedback is more than welcome!

    
    import urllib
    from xml.dom import minidom
    
    GEO_IP_LOOKUP_URL = 'http://api.hostip.info/?ip=%s'
    GML_NS = 'http://www.opengis.net/gml'
    
    def geo_ip_lookup(ip_address):
        """
        Look up the geo information based on the IP address passed in
        """
        dom = minidom.parse(urllib.urlopen(GEO_IP_LOOKUP_URL % ip_address))
        elem = dom.getElementsByTagName('Hostip')[0]
        location = elem.getElementsByTagNameNS(GML_NS, 'name')[0].firstChild.data.partition(',')
    
        try:
            latlong = elem.getElementsByTagNameNS(GML_NS, 'coordinates')[0].firstChild.data.partition(',')
        except:
            # lat/long isnt always returned
            latlong = None
    
        return {
                'country_code': elem.getElementsByTagName('countryAbbrev')[0].firstChild.data,
                'country_name': elem.getElementsByTagName('countryName')[0].firstChild.data,
                'locality': location[0].strip(),
                'region': location[2].strip(),
                'longitude': latlong[0].strip() if latlong else '',
                'latitude': latlong[2].strip() if latlong else ''
        }
    

    Calling it from the interpreter:

    >>> geo_ip_lookup('65.34.176.69')
    {'locality': u'Miami', 'region': u'FL', 'longitude': u'-80.2108', 'latitude': u'25.7757', 'country_code': u'US', 'country_name': u'UNITED STATES'}
    >>>
    
    Be the first to respond... Leave Your Comment

More Posts:

wow sarah palin stepping down --- more tweets

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

386 ms | login | html5 | top