signature:
def stitch_macro ( path , output_folder = None ) :
    """Create fiji - macros for stitching all channels and z - stacks for a well .
 Parameters
 path : string
 Well path .
 output _ folder : string
 Folder to store images . If not given well path is used .
 Returns
 output _ files , macros : tuple
 Tuple with filenames and macros for stitched well ."""

implementation:
output_folder = output_folder or path
debug ( 'stitching ' + path + ' to ' + output_folder )
fields = glob ( _pattern ( path , _field ) )
# assume we have rectangle of fields
xs = [ attribute ( field , 'X' ) for field in fields ]
ys = [ attribute ( field , 'Y' ) for field in fields ]
x_min , x_max = min ( xs ) , max ( xs )
y_min , y_max = min ( ys ) , max ( ys )
fields_column = len ( set ( xs ) )
fields_row = len ( set ( ys ) )
# assume all fields are the same
# and get properties from images in first field
images = glob ( _pattern ( fields [ 0 ] , _image ) )
# assume attributes are the same on all images
attr = attributes ( images [ 0 ] )
# find all channels and z - stacks
channels = [ ]
z_stacks = [ ]
for image in images :
    channel = attribute_as_str ( image , 'C' )
    if channel not in channels :
        channels . append ( channel )
    z = attribute_as_str ( image , 'Z' )
    if z not in z_stacks :
        z_stacks . append ( z )
debug ( 'channels ' + str ( channels ) )
debug ( 'z-stacks ' + str ( z_stacks ) )
# create macro
_ , extension = os . path . splitext ( images [ - 1 ] )
if extension == '.tif' : # assume . ome . tif
    extension = '.ome.tif'
macros = [ ]
output_files = [ ]
for Z in z_stacks :
    for C in channels :
        filenames = os . path . join ( _field + '--X{xx}--Y{yy}' , _image + '--L' + attr . L + '--S' + attr . S + '--U' + attr . U + '--V' + attr . V + '--J' + attr . J + '--E' + attr . E + '--O' + attr . O + '--X{xx}--Y{yy}' + '--T' + attr . T + '--Z' + Z + '--C' + C + extension )
        debug ( 'filenames ' + filenames )
        cur_attr = attributes ( filenames ) . _asdict ( )
        f = 'stitched--U{U}--V{V}--C{C}--Z{Z}.png' . format ( ** cur_attr )
        output = os . path . join ( output_folder , f )
        debug ( 'output ' + output )
        output_files . append ( output )
        if os . path . isfile ( output ) : # file already exists
            print ( 'leicaexperiment stitched file already' ' exists {}' . format ( output ) )
            continue
        macros . append ( fijibin . macro . stitch ( path , filenames , fields_column , fields_row , output_filename = output , x_start = x_min , y_start = y_min ) )
return ( output_files , macros )


signature:
def compress ( images , delete_tif = False , folder = None ) :
    """Lossless compression . Save images as PNG and TIFF tags to json . Can be
 reversed with ` decompress ` . Will run in multiprocessing , where
 number of workers is decided by ` ` leicaexperiment . experiment . _ pools ` ` .
 Parameters
 images : list of filenames
 Images to lossless compress .
 delete _ tif : bool
 Wheter to delete original images .
 folder : string
 Where to store images . Basename will be kept .
 Returns
 list of filenames
 List of compressed files ."""

implementation:
if type ( images ) == str : # only one image
    return [ compress_blocking ( images , delete_tif , folder ) ]
filenames = copy ( images )
# as images property will change when looping
return Parallel ( n_jobs = _pools ) ( delayed ( compress_blocking ) ( image = image , delete_tif = delete_tif , folder = folder ) for image in filenames )


signature:
def compress_blocking ( image , delete_tif = False , folder = None , force = False ) :
    """Lossless compression . Save image as PNG and TIFF tags to json . Process
 can be reversed with ` decompress ` .
 Parameters
 image : string
 TIF - image which should be compressed lossless .
 delete _ tif : bool
 Wheter to delete original images .
 force : bool
 Wheter to compress even if . png already exists .
 Returns
 string
 Filename of compressed image , or empty string if compress failed ."""

implementation:
debug ( 'compressing {}' . format ( image ) )
try :
    new_filename , extension = os . path . splitext ( image )
    # remove last occurrence of . ome
    new_filename = new_filename . rsplit ( '.ome' , 1 ) [ 0 ]
    # if compressed file should be put in specified folder
    if folder :
        basename = os . path . basename ( new_filename )
        new_filename = os . path . join ( folder , basename + '.png' )
    else :
        new_filename = new_filename + '.png'
    # check if png exists
    if os . path . isfile ( new_filename ) and not force :
        compressed_images . append ( new_filename )
        msg = "Aborting compress, PNG already" " exists: {}" . format ( new_filename )
        raise AssertionError ( msg )
    if extension != '.tif' :
        msg = "Aborting compress, not a TIFF: {}" . format ( image )
        raise AssertionError ( msg )
    # open image , load and close file pointer
    img = Image . open ( image )
    fptr = img . fp
    # keep file pointer , for closing
    img . load ( )
    # load img - data before switching mode , also closes fp
    # get tags and save them as json
    tags = img . tag . as_dict ( )
    with open ( new_filename [ : - 4 ] + '.json' , 'w' ) as f :
        if img . mode == 'P' : # keep palette
            tags [ 'palette' ] = img . getpalette ( )
        json . dump ( tags , f )
    # check if image is palette - mode
    if img . mode == 'P' : # switch to luminance to keep data intact
        debug ( 'palette-mode switched to luminance' )
        img . mode = 'L'
    if img . mode == 'I;16' : # https : / / github . com / python - pillow / Pillow / issues / 1099
        img = img . convert ( mode = 'I' )
    # compress / save
    debug ( 'saving to {}' . format ( new_filename ) )
    img . save ( new_filename )
    fptr . close ( )
    # windows bug Pillow
    if delete_tif :
        os . remove ( image )
except ( IOError , AssertionError ) as e : # print error - continue
    print ( 'leicaexperiment {}' . format ( e ) )
    return ''
return new_filename


signature:
def decompress ( images , delete_png = False , delete_json = False , folder = None ) :
    """Reverse compression from tif to png and save them in original format
 ( ome . tif ) . TIFF - tags are gotten from json - files named the same as given
 images .
 Parameters
 images : list of filenames
 Image to decompress .
 delete _ png : bool
 Wheter to delete PNG images .
 delete _ json : bool
 Wheter to delete TIFF - tags stored in json files on compress .
 Returns
 list of filenames
 List of decompressed files ."""

implementation:
if type ( images ) == str : # only one image
    return decompress ( [ images ] )
filenames = copy ( images )
# as images property will change when looping
decompressed_images = [ ]
for orig_filename in filenames :
    debug ( 'decompressing {}' . format ( orig_filename ) )
    try :
        filename , extension = os . path . splitext ( orig_filename )
        # if decompressed file should be put in specified folder
        if folder :
            basename = os . path . basename ( filename )
            new_filename = os . path . join ( folder , basename + '.ome.tif' )
        else :
            new_filename = filename + '.ome.tif'
        # check if tif exists
        if os . path . isfile ( new_filename ) :
            decompressed_images . append ( new_filename )
            msg = "Aborting decompress, TIFF already exists:" " {}" . format ( orig_filename )
            raise AssertionError ( msg )
        if extension != '.png' :
            msg = "Aborting decompress, not a " "PNG: {}" . format ( orig_filename )
            raise AssertionError ( msg )
        # open image , load and close file pointer
        img = Image . open ( orig_filename )
        img . load ( )
        # load img - data before switching mode , also closes fp
        # get tags from json
        info = { }
        with open ( filename + '.json' , 'r' ) as f :
            tags = json . load ( f )
            # convert dictionary to original types ( lost in json conversion )
            for tag , val in tags . items ( ) :
                if tag == 'palette' : # hack hack
                    continue
                if type ( val ) == list :
                    val = tuple ( val )
                if type ( val [ 0 ] ) == list : # list of list
                    val = tuple ( tuple ( x ) for x in val )
                info [ int ( tag ) ] = val
        # check for color map
        if 'palette' in tags :
            img . putpalette ( tags [ 'palette' ] )
        # save as tif
        debug ( 'saving to {}' . format ( new_filename ) )
        img . save ( new_filename , tiffinfo = info )
        decompressed_images . append ( new_filename )
        if delete_png :
            os . remove ( orig_filename )
        if delete_json :
            os . remove ( filename + '.json' )
    except ( IOError , AssertionError ) as e : # print error - continue
        print ( 'leicaexperiment {}' . format ( e ) )
return decompressed_images


signature:
def attribute ( path , name ) :
    """Returns the two numbers found behind - - [ A - Z ] in path . If several matches
 are found , the last one is returned .
 Parameters
 path : string
 String with path of file / folder to get attribute from .
 name : string
 Name of attribute to get . Should be A - Z or a - z ( implicit converted to
 uppercase ) .
 Returns
 integer
 Returns number found in path behind - - name as an integer ."""

implementation:
matches = re . findall ( '--' + name . upper ( ) + '([0-9]{2})' , path )
if matches :
    return int ( matches [ - 1 ] )
else :
    return None


signature:
def attribute_as_str ( path , name ) :
    """Returns the two numbers found behind - - [ A - Z ] in path . If several matches
 are found , the last one is returned .
 Parameters
 path : string
 String with path of file / folder to get attribute from .
 name : string
 Name of attribute to get . Should be A - Z or a - z ( implicit converted to
 uppercase ) .
 Returns
 string
 Returns two digit number found in path behind - - name ."""

implementation:
matches = re . findall ( '--' + name . upper ( ) + '([0-9]{2})' , path )
if matches :
    return matches [ - 1 ]
else :
    return None


signature:
def attributes ( path ) :
    """Get attributes from path based on format - - [ A - Z ] . Returns namedtuple
 with upper case attributes equal to what found in path ( string ) and lower
 case as int . If path holds several occurrences of same character , only the
 last one is kept .
 > > > attrs = attributes ( ' / folder / file - - X00 - X01 . tif ' )
 > > > print ( attrs )
 namedtuple ( ' attributes ' , ' X x ' ) ( ' 01 ' , 1)
 > > > print ( attrs . x )
 Parameters
 path : string
 Returns
 collections . namedtuple"""

implementation:
# number of charcters set to numbers have changed in LAS AF X ! !
matches = re . findall ( '--([A-Z]{1})([0-9]{2,4})' , path )
keys = [ ]
values = [ ]
for k , v in matches :
    if k in keys : # keep only last key
        i = keys . index ( k )
        del keys [ i ]
        del values [ i ]
    keys . append ( k )
    values . append ( v )
lower_keys = [ k . lower ( ) for k in keys ]
int_values = [ int ( v ) for v in values ]
attributes = namedtuple ( 'attributes' , keys + lower_keys )
return attributes ( * values + int_values )


signature:
def _pattern ( * names , ** kwargs ) :
    """Returns globbing pattern for name1 / name2 / . . / lastname + ' - - * ' or
 name1 / name2 / . . / lastname + extension if parameter ` extension ` it set .
 Parameters
 names : strings
 Which path to join . Example : _ pattern ( ' path ' , ' to ' , ' experiment ' ) will
 return ` path / to / experiment - - * ` .
 extension : string
 If other extension then - - * is wanted .
 Example : _ pattern ( ' path ' , ' to ' , ' image ' , extension = ' * . png ' ) will return
 ` path / to / image * . png ` .
 Returns
 string
 Joined glob pattern string ."""

implementation:
if 'extension' not in kwargs :
    kwargs [ 'extension' ] = '--*'
return os . path . join ( * names ) + kwargs [ 'extension' ]


signature:
def _set_path ( self , path ) :
    "Set self . path , self . dirname and self . basename ."

implementation:
import os . path
self . path = os . path . abspath ( path )
self . dirname = os . path . dirname ( path )
self . basename = os . path . basename ( path )


signature:
def images ( self ) :
    "List of paths to images ."

implementation:
tifs = _pattern ( self . _image_path , extension = 'tif' )
pngs = _pattern ( self . _image_path , extension = 'png' )
imgs = [ ]
imgs . extend ( glob ( tifs ) )
imgs . extend ( glob ( pngs ) )
return imgs


signature:
def scanning_template ( self ) :
    "Path to { ScanningTemplate } name . xml of experiment ."

implementation:
tmpl = glob ( _pattern ( self . path , _additional_data , _scanning_template , extension = '*.xml' ) )
if tmpl :
    return tmpl [ 0 ]
else :
    return ''


signature:
def well_rows ( self , well_row , well_column ) :
    """All well rows in experiment . Equivalent to - - U in files .
 Returns
 list of ints"""

implementation: return list ( set ( [ attribute ( img , 'u' ) for img in self . images ] ) )


signature:
def image ( self , well_row , well_column , field_row , field_column ) :
    """Get path of specified image .
 Parameters
 well _ row : int
 Starts at 0 . Same as - - U in files .
 well _ column : int
 Starts at 0 . Same as - - V in files .
 field _ row : int
 Starts at 0 . Same as - - Y in files .
 field _ column : int
 Starts at 0 . Same as - - X in files .
 Returns
 string
 Path to image or empty string if image is not found ."""

implementation: return next ( ( i for i in self . images if attribute ( i , 'u' ) == well_column and attribute ( i , 'v' ) == well_row and attribute ( i , 'x' ) == field_column and attribute ( i , 'y' ) == field_row ) , '' )


signature:
def well_images ( self , well_row , well_column ) :
    """Get list of paths to images in specified well .
 Parameters
 well _ row : int
 Starts at 0 . Same as - - V in files .
 well _ column : int
 Starts at 0 . Save as - - U in files .
 Returns
 list of strings
 Paths to images or empty list if no images are found ."""

implementation: return list ( i for i in self . images if attribute ( i , 'u' ) == well_column and attribute ( i , 'v' ) == well_row )


signature:
def field_columns ( self , well_row , well_column ) :
    """Field columns for given well . Equivalent to - - X in files .
 Parameters
 well _ row : int
 Starts at 0 . Same as - - V in files .
 well _ column : int
 Starts at 0 . Same as - - U in files .
 Returns
 list of ints
 Columns found for specified well ."""

implementation:
imgs = self . well_images ( well_row , well_column )
return list ( set ( [ attribute ( img , 'x' ) for img in imgs ] ) )


signature:
def stitch ( self , folder = None ) :
    """Stitches all wells in experiment with ImageJ . Stitched images are
 saved in experiment root .
 Images which already exists are omitted stitching .
 Parameters
 folder : string
 Where to store stitched images . Defaults to experiment path .
 Returns
 list
 Filenames of stitched images . Files which already exists before
 stitching are also returned ."""

implementation:
debug ( 'stitching ' + self . __str__ ( ) )
if not folder :
    folder = self . path
# create list of macros and files
macros = [ ]
files = [ ]
for well in self . wells :
    f , m = stitch_macro ( well , folder )
    macros . extend ( m )
    files . extend ( f )
chopped_arguments = zip ( chop ( macros , _pools ) , chop ( files , _pools ) )
chopped_filenames = Parallel ( n_jobs = _pools ) ( delayed ( fijibin . macro . run ) ( macro = arg [ 0 ] , output_files = arg [ 1 ] ) for arg in chopped_arguments )
# flatten
return [ f for list_ in chopped_filenames for f in list_ ]


signature:
def compress ( self , delete_tif = False , folder = None ) :
    """Lossless compress all images in experiment to PNG . If folder is
 omitted , images will not be moved .
 Images which already exists in PNG are omitted .
 Parameters
 folder : string
 Where to store PNGs . Defaults to the folder they are in .
 delete _ tif : bool
 If set to truthy value , ome . tifs will be deleted after compression .
 Returns
 list
 Filenames of PNG images . Files which already exists before
 compression are also returned ."""

implementation: return compress ( self . images , delete_tif , folder )


signature:
def field_metadata ( self , well_row = 0 , well_column = 0 , field_row = 0 , field_column = 0 ) :
    """Get OME - XML metadata of given field .
 Parameters
 well _ row : int
 Y well coordinate . Same as - - V in files .
 well _ column : int
 X well coordinate . Same as - - U in files .
 field _ row : int
 Y field coordinate . Same as - - Y in files .
 field _ column : int
 X field coordinate . Same as - - X in files .
 Returns
 lxml . objectify . ObjectifiedElement
 lxml object of OME - XML found in slide / chamber / field / metadata ."""

implementation:
def condition ( path ) :
    attrs = attributes ( path )
    return ( attrs . u == well_column and attrs . v == well_row and attrs . x == field_column and attrs . y == field_row )
field = [ f for f in self . fields if condition ( f ) ]
if field :
    field = field [ 0 ]
    filename = _pattern ( field , 'metadata' , _image , extension = '*.ome.xml' )
    filename = glob ( filename ) [ 0 ]
    # resolve , assume found
    return objectify . parse ( filename ) . getroot ( )


signature:
def stitch_coordinates ( self , well_row = 0 , well_column = 0 ) :
    """Get a list of stitch coordinates for the given well .
 Parameters
 well _ row : int
 Y well coordinate . Same as - - V in files .
 well _ column : int
 X well coordinate . Same as - - U in files .
 Returns
 ( xs , ys , attr ) : tuples with float and collections . OrderedDict
 Tuple of x ' s , y ' s and attributes ."""

implementation:
well = [ w for w in self . wells if attribute ( w , 'u' ) == well_column and attribute ( w , 'v' ) == well_row ]
if len ( well ) == 1 :
    well = well [ 0 ]
    tile = os . path . join ( well , 'TileConfiguration.registered.txt' )
    with open ( tile ) as f :
        data = [ x . strip ( ) for l in f . readlines ( ) if l [ 0 : 7 ] == 'image--' for x in l . split ( ';' ) ]
        # flat list
        coordinates = ( ast . literal_eval ( x ) for x in data [ 2 : : 3 ] )
        # flatten
        coordinates = sum ( coordinates , ( ) )
        attr = tuple ( attributes ( x ) for x in data [ 0 : : 3 ] )
    return coordinates [ 0 : : 2 ] , coordinates [ 1 : : 2 ] , attr
else :
    print ( 'leicaexperiment stitch_coordinates' '({}, {}) Well not found' . format ( well_row , well_column ) )


signature:
def create ( self , name , region , size , image , ssh_keys = None , backups = None , ipv6 = None , private_networking = None , wait = True ) :
    """Create a new droplet
 Parameters
 name : str
 Name of new droplet
 region : str
 slug for region ( e . g . , sfo1 , nyc1)
 size : str
 slug for droplet size ( e . g . , 512mb , 1024mb )
 image : int or str
 image id ( e . g . , 12352 ) or slug ( e . g . , ' ubuntu - 14-04 - x64 ' )
 ssh _ keys : list , optional
 default SSH keys to be added on creation
 this is highly recommended for ssh access
 backups : bool , optional
 whether automated backups should be enabled for the Droplet .
 Automated backups can only be enabled when the Droplet is created .
 ipv6 : bool , optional
 whether IPv6 is enabled on the Droplet
 private _ networking : bool , optional
 whether private networking is enabled for the Droplet . Private
 networking is currently only available in certain regions
 wait : bool , default True
 if True then block until creation is complete"""

implementation:
if ssh_keys and not isinstance ( ssh_keys , ( list , tuple ) ) :
    raise TypeError ( "ssh_keys must be a list" )
resp = self . post ( name = name , region = region , size = size , image = image , ssh_keys = ssh_keys , private_networking = private_networking , backups = backups , ipv6 = ipv6 )
droplet = self . get ( resp [ self . singular ] [ 'id' ] )
if wait :
    droplet . wait ( )
# HACK sometimes the IP address doesn ' t return correctly
droplet = self . get ( resp [ self . singular ] [ 'id' ] )
return droplet


signature:
def get ( self , id ) :
    """Retrieve a droplet by id
 Parameters
 id : int
 droplet id
 Returns
 droplet : DropletActions"""

implementation:
info = self . _get_droplet_info ( id )
return DropletActions ( self . api , self , ** info )


signature:
def by_name ( self , name ) :
    """Retrieve a droplet by name ( return first if duplicated )
 Parameters
 name : str
 droplet name
 Returns
 droplet : DropletActions"""

implementation:
for d in self . list ( ) :
    if d [ 'name' ] == name :
        return self . get ( d [ 'id' ] )
raise KeyError ( "Could not find droplet with name %s" % name )


signature:
def resize ( self , size , wait = True ) :
    """Change the size of this droplet ( must be powered off )
 Parameters
 size : str
 size slug , e . g . , 512mb
 wait : bool , default True
 Whether to block until the pending action is completed"""

implementation: return self . _action ( 'resize' , size = size , wait = wait )


signature:
def restore ( self , image , wait = True ) :
    """Restore this droplet with given image id
 A Droplet restoration will rebuild an image using a backup image .
 The image ID that is passed in must be a backup of the current Droplet
 instance . The operation will leave any embedded SSH keys intact .
 Parameters
 image : int or str
 int for image id and str for image slug
 wait : bool , default True
 Whether to block until the pending action is completed"""

implementation: return self . _action ( 'restore' , image = image , wait = wait )


signature:
def rebuild ( self , image , wait = True ) :
    """Rebuild this droplet with given image id
 Parameters
 image : int or str
 int for image id and str for image slug
 wait : bool , default True
 Whether to block until the pending action is completed"""

implementation: return self . _action ( 'rebuild' , image = image , wait = wait )


signature:
def rename ( self , name , wait = True ) :
    """Change the name of this droplet
 Parameters
 name : str
 New name for the droplet
 wait : bool , default True
 Whether to block until the pending action is completed
 Raises
 APIError if region does not support private networking"""

implementation: return self . _action ( 'rename' , name = name , wait = wait )


signature:
def change_kernel ( self , kernel_id , wait = True ) :
    """Change the kernel of this droplet
 Parameters
 kernel _ id : int
 Can be retrieved from output of self . kernels ( )
 wait : bool , default True
 Whether to block until the pending action is completed
 Raises
 APIError if region does not support private networking"""

implementation: return self . _action ( 'change_kernel' , kernel = kernel_id , wait = wait )


signature:
def take_snapshot ( self , name , wait = True ) :
    """Take a snapshot of this droplet ( must be powered off )
 Parameters
 name : str
 Name of the snapshot
 wait : bool , default True
 Whether to block until the pending action is completed"""

implementation: return self . _action ( 'snapshot' , name = name , wait = wait )


signature:
def delete ( self , wait = True ) :
    """Delete this droplet
 Parameters
 wait : bool , default True
 Whether to block until the pending action is completed"""

implementation:
resp = self . parent . delete ( self . id )
if wait :
    self . wait ( )
return resp


signature:
def wait ( self ) :
    """wait for all actions to complete on a droplet"""

implementation:
interval_seconds = 5
while True :
    actions = self . actions ( )
    slept = False
    for a in actions :
        if a [ 'status' ] == 'in-progress' : # n . b . gevent will monkey patch
            time . sleep ( interval_seconds )
            slept = True
            break
    if not slept :
        break


signature:
def ip_address ( self ) :
    """Public ip _ address"""

implementation:
ip = None
for eth in self . networks [ 'v4' ] :
    if eth [ 'type' ] == 'public' :
        ip = eth [ 'ip_address' ]
        break
if ip is None :
    raise ValueError ( "No public IP found" )
return ip


signature:
def private_ip ( self ) :
    """Private ip _ address"""

implementation:
ip = None
for eth in self . networks [ 'v4' ] :
    if eth [ 'type' ] == 'private' :
        ip = eth [ 'ip_address' ]
        break
if ip is None :
    raise ValueError ( "No private IP found" )
return ip


signature:
def connect ( self , interactive = False ) :
    """Open SSH connection to droplet
 Parameters
 interactive : bool , default False
 If True then SSH client will prompt for password when necessary
 and also print output to console"""

implementation:
from poseidon . ssh import SSHClient
rs = SSHClient ( self . ip_address , interactive = interactive )
return rs


signature:
def send_request ( self , kind , resource , url_components , ** kwargs ) :
    """Send a request to the REST API
 Parameters
 kind : str , { get , delete , put , post , head }
 resource : str
 url _ components : list or tuple to be appended to the request URL
 Notes
 kwargs contain request parameters to be sent as request data"""

implementation:
url = self . format_request_url ( resource , * url_components )
meth = getattr ( requests , kind )
headers = self . get_request_headers ( )
req_data = self . format_parameters ( ** kwargs )
response = meth ( url , headers = headers , data = req_data )
data = self . get_response ( response )
if response . status_code >= 300 :
    msg = data . pop ( 'message' , 'API request returned error' )
    raise APIError ( msg , response . status_code , ** data )
return data


signature:
def format_parameters ( self , ** kwargs ) :
    """Properly formats array types"""

implementation:
req_data = { }
for k , v in kwargs . items ( ) :
    if isinstance ( v , ( list , tuple ) ) :
        k = k + '[]'
    req_data [ k ] = v
return req_data


signature:
def format_request_url ( self , resource , * args ) :
    """create request url for resource"""

implementation: return '/' . join ( ( self . api_url , self . api_version , resource ) + tuple ( str ( x ) for x in args ) )


signature:
def send_request ( self , kind , url_components , ** kwargs ) :
    """Send a request for this resource to the API
 Parameters
 kind : str , { ' get ' , ' delete ' , ' put ' , ' post ' , ' head ' }"""

implementation: return self . api . send_request ( kind , self . resource_path , url_components , ** kwargs )


signature:
def list ( self , url_components = ( ) ) :
    """Send list request for all members of a collection"""

implementation:
resp = self . get ( url_components )
return resp . get ( self . result_key , [ ] )


signature:
def get ( self , id , ** kwargs ) :
    """Get single unit of collection"""

implementation: return ( super ( MutableCollection , self ) . get ( ( id , ) , ** kwargs ) . get ( self . singular , None ) )


signature:
def transfer ( self , region ) :
    """Transfer this image to given region
 Parameters
 region : str
 region slug to transfer to ( e . g . , sfo1 , nyc1)"""

implementation:
action = self . post ( type = 'transfer' , region = region ) [ 'action' ]
return self . parent . get ( action [ 'resource_id' ] )


signature:
def get ( self , id ) :
    """id or slug"""

implementation:
info = super ( Images , self ) . get ( id )
return ImageActions ( self . api , parent = self , ** info )


signature:
def update ( self , id , name ) :
    """id or fingerprint"""

implementation: return super ( Keys , self ) . update ( id , name = name )


signature:
def create ( self , name , ip_address ) :
    """Creates a new domain
 Parameters
 name : str
 new domain name
 ip _ address : str
 IP address for the new domain"""

implementation: return ( self . post ( name = name , ip_address = ip_address ) . get ( self . singular , None ) )


signature:
def records ( self , name ) :
    """Get a list of all domain records for the given domain name
 Parameters
 name : str
 domain name"""

implementation:
if self . get ( name ) :
    return DomainRecords ( self . api , name )


signature:
def rename ( self , id , name ) :
    """Change the name of this domain record
 Parameters
 id : int
 domain record id
 name : str
 new name of record"""

implementation: return super ( DomainRecords , self ) . update ( id , name = name ) [ self . singular ]


signature:
def create ( self , type , name = None , data = None , priority = None , port = None , weight = None ) :
    """Parameters
 type : str
 { A , AAAA , CNAME , MX , TXT , SRV , NS }
 name : str
 Name of the record
 data : object , type - dependent
 type = = ' A ' : IPv4 address
 type = = ' AAAA ' : IPv6 address
 type = = ' CNAME ' : destination host name
 type = = ' MX ' : mail host name
 type = = ' TXT ' : txt contents
 type = = ' SRV ' : target host name to direct requests for the service
 type = = ' NS ' : name server that is authoritative for the domain
 priority :
 port :
 weight :"""

implementation:
if type == 'A' and name is None :
    name = self . domain
return self . post ( type = type , name = name , data = data , priority = priority , port = port , weight = weight ) [ self . singular ]


signature:
def get ( self , id , ** kwargs ) :
    """Retrieve a single domain record given the id"""

implementation: return super ( DomainRecords , self ) . get ( id , ** kwargs )


signature:
def logon ( self , username , password ) :
    """Logs the user on to FogBugz .
 Returns None for a successful login ."""

implementation:
if self . _token :
    self . logoff ( )
try :
    response = self . __makerequest ( 'logon' , email = username , password = password )
except FogBugzAPIError :
    e = sys . exc_info ( ) [ 1 ]
    raise FogBugzLogonError ( e )
self . _token = response . token . string
if type ( self . _token ) == CData :
    self . _token = self . _token . encode ( 'utf-8' )


signature:
def __encode_multipart_formdata ( self , fields , files ) :
    """fields is a sequence of ( key , value ) elements for regular form fields .
 files is a sequence of ( filename , filehandle ) files to be uploaded
 returns ( content _ type , body )"""

implementation:
BOUNDARY = _make_boundary ( )
if len ( files ) > 0 :
    fields [ 'nFileCount' ] = str ( len ( files ) )
crlf = '\r\n'
buf = BytesIO ( )
for k , v in fields . items ( ) :
    if DEBUG :
        print ( "field: %s: %s" % ( repr ( k ) , repr ( v ) ) )
    lines = [ '--' + BOUNDARY , 'Content-disposition: form-data; name="%s"' % k , '' , str ( v ) , '' , ]
    buf . write ( crlf . join ( lines ) . encode ( 'utf-8' ) )
n = 0
for f , h in files . items ( ) :
    n += 1
    lines = [ '--' + BOUNDARY , 'Content-disposition: form-data; name="File%d"; ' 'filename="%s"' % ( n , f ) , '' , ]
    buf . write ( crlf . join ( lines ) . encode ( 'utf-8' ) )
    lines = [ 'Content-type: application/octet-stream' , '' , '' , ]
    buf . write ( crlf . join ( lines ) . encode ( 'utf-8' ) )
    buf . write ( h . read ( ) )
    buf . write ( crlf . encode ( 'utf-8' ) )
buf . write ( ( '--' + BOUNDARY + '--' + crlf ) . encode ( 'utf-8' ) )
content_type = "multipart/form-data; boundary=%s" % BOUNDARY
return content_type , buf . getvalue ( )


signature:
def chop ( list_ , n ) :
    "Chop list _ into n chunks . Returns a list ."

implementation:
# could look into itertools also , might be implemented there
size = len ( list_ )
each = size // n
if each == 0 :
    return [ list_ ]
chopped = [ ]
for i in range ( n ) :
    start = i * each
    end = ( i + 1 ) * each
    if i == ( n - 1 ) : # make sure we get all items , let last worker do a litte more
        end = size
    chopped . append ( list_ [ start : end ] )
return chopped


signature:
def get_first ( ) :
    """return first droplet"""

implementation:
client = po . connect ( )
# this depends on the DIGITALOCEAN _ API _ KEY envvar
all_droplets = client . droplets . list ( )
id = all_droplets [ 0 ] [ 'id' ]
# I ' m cheating because I only have one droplet
return client . droplets . get ( id )


signature:
def take_snapshot ( droplet , name ) :
    """Take a snapshot of a droplet
 Parameters
 name : str
 name for snapshot"""

implementation:
print "powering off"
droplet . power_off ( )
droplet . wait ( )
# wait for pending actions to complete
print "taking snapshot"
droplet . take_snapshot ( name )
droplet . wait ( )
snapshots = droplet . snapshots ( )
print "Current snapshots"
print snapshots


signature:
def allowed_operations ( self ) :
    """Retrieves the allowed operations for this request ."""

implementation:
if self . slug is not None :
    return self . meta . detail_allowed_operations
return self . meta . list_allowed_operations


signature:
def assert_operations ( self , * args ) :
    """Assets if the requested operations are allowed in this context ."""

implementation:
if not set ( args ) . issubset ( self . allowed_operations ) :
    raise http . exceptions . Forbidden ( )


signature:
def make_response ( self , data = None ) :
    """Fills the response object from the passed data ."""

implementation:
if data is not None : # Prepare the data for transmission .
    data = self . prepare ( data )
    # Encode the data using a desired encoder .
    self . response . write ( data , serialize = True )


signature:
def get ( self , request , response ) :
    """Processes a ` GET ` request ."""

implementation:
# Ensure we ' re allowed to read the resource .
self . assert_operations ( 'read' )
# Delegate to ` read ` to retrieve the items .
items = self . read ( )
# if self . slug is not None and not items :
# # Requested a specific resource but nothing is returned .
# # Attempt to resolve by changing what we understand as
# # a slug to a path .
# self . path = self . path + self . slug if self . path else self . slug
# self . slug = None
# # Attempt to retreive the resource again .
# items = self . read ( )
# Ensure that if we have a slug and still no items that a 404
# is rasied appropriately .
if not items :
    raise http . exceptions . NotFound ( )
if ( isinstance ( items , Iterable ) and not isinstance ( items , six . string_types ) ) and items : # Paginate over the collection .
    items = pagination . paginate ( self . request , self . response , items )
# Build the response object .
self . make_response ( items )


signature:
def post ( self , request , response ) :
    """Processes a ` POST ` request ."""

implementation:
if self . slug is not None : # Don ' t know what to do an item access .
    raise http . exceptions . NotImplemented ( )
# Ensure we ' re allowed to create a resource .
self . assert_operations ( 'create' )
# Deserialize and clean the incoming object .
data = self . _clean ( None , self . request . read ( deserialize = True ) )
# Delegate to ` create ` to create the item .
item = self . create ( data )
# Build the response object .
self . response . status = http . client . CREATED
self . make_response ( item )


signature:
def put ( self , request , response ) :
    """Processes a ` PUT ` request ."""

implementation:
if self . slug is None : # Mass - PUT is not implemented .
    raise http . exceptions . NotImplemented ( )
# Check if the resource exists .
target = self . read ( )
# Deserialize and clean the incoming object .
data = self . _clean ( target , self . request . read ( deserialize = True ) )
if target is not None : # Ensure we ' re allowed to update the resource .
    self . assert_operations ( 'update' )
    try : # Delegate to ` update ` to create the item .
        self . update ( target , data )
    except AttributeError : # No read method defined .
        raise http . exceptions . NotImplemented ( )
    # Build the response object .
    self . make_response ( target )
else : # Ensure we ' re allowed to create the resource .
    self . assert_operations ( 'create' )
    # Delegate to ` create ` to create the item .
    target = self . create ( data )
    # Build the response object .
    self . response . status = http . client . CREATED
    self . make_response ( target )


signature:
def delete ( self , request , response ) :
    """Processes a ` DELETE ` request ."""

implementation:
if self . slug is None : # Mass - DELETE is not implemented .
    raise http . exceptions . NotImplemented ( )
# Ensure we ' re allowed to destroy a resource .
self . assert_operations ( 'destroy' )
# Delegate to ` destroy ` to destroy the item .
self . destroy ( )
# Build the response object .
self . response . status = http . client . NO_CONTENT
self . make_response ( )


signature:
def link ( self , request , response ) :
    """Processes a ` LINK ` request .
 A ` LINK ` request is asking to create a relation from the currently
 represented URI to all of the ` Link ` request headers ."""

implementation:
from armet . resources . managed . request import read
if self . slug is None : # Mass - LINK is not implemented .
    raise http . exceptions . NotImplemented ( )
# Get the current target .
target = self . read ( )
# Collect all the passed link headers .
links = self . _parse_link_headers ( request [ 'Link' ] )
# Pull targets for each represented link .
for link in links : # Delegate to a connector .
    self . relate ( target , read ( self , link [ 'uri' ] ) )
# Build the response object .
self . response . status = http . client . NO_CONTENT
self . make_response ( )


signature:
def create_project ( self ) :
    '''Creates a base Django project'''

implementation:
if os . path . exists ( self . _py ) :
    prj_dir = os . path . join ( self . _app_dir , self . _project_name )
    if os . path . exists ( prj_dir ) :
        if self . _force :
            logging . warn ( 'Removing existing project' )
            shutil . rmtree ( prj_dir )
        else :
            logging . warn ( 'Found existing project; not creating (use --force to overwrite)' )
            return
    logging . info ( 'Creating project' )
    p = subprocess . Popen ( 'cd {0} ; {1} startproject {2} > /dev/null' . format ( self . _app_dir , self . _ve_dir + os . sep + self . _project_name + os . sep + 'bin' + os . sep + 'django-admin.py' , self . _project_name ) , shell = True )
    os . waitpid ( p . pid , 0 )
else :
    logging . error ( 'Unable to find Python interpreter in virtualenv' )
    return


signature:
def ilike_helper ( default ) :
    """Helper function that performs an ` ilike ` query if a string value
 is passed , otherwise the normal default operation ."""

implementation:
@ functools . wraps ( default )
def wrapped ( x , y ) : # String values should use ILIKE queries .
    if isinstance ( y , six . string_types ) and not isinstance ( x . type , sa . Enum ) :
        return x . ilike ( "%" + y + "%" )
    else :
        return default ( x , y )
return wrapped


signature:
def parse ( text , encoding = 'utf8' ) :
    """Parse the querystring into a normalized form ."""

implementation:
# Decode the text if we got bytes .
if isinstance ( text , six . binary_type ) :
    text = text . decode ( encoding )
return Query ( text , split_segments ( text ) )


signature:
def split_segments ( text , closing_paren = False ) :
    """Return objects representing segments ."""

implementation:
buf = StringIO ( )
# The segments we ' re building , and the combinators used to combine them .
# Note that after this is complete , this should be true :
# len ( segments ) = = len ( combinators ) + 1
# Thus we can understand the relationship between segments and combinators
# like so :
# s1 ( c1 ) s2 ( c2 ) s3 ( c3 ) where sN are segments and cN are combination
# functions .
# TODO : Figure out exactly where the querystring died and post cool
# error messages about it .
segments = [ ]
combinators = [ ]
# A flag dictating if the last character we processed was a group .
# This is used to determine if the next character ( being a combinator )
# is allowed to
last_group = False
# The recursive nature of this function relies on keeping track of the
# state of iteration . This iterator will be passed down to recursed calls .
iterator = iter ( text )
# Detection for exclamation points . only matters for this situation :
# foo = bar & ! ( bar = baz )
last_negation = False
for character in iterator :
    if character in COMBINATORS :
        if last_negation :
            buf . write ( constants . OPERATOR_NEGATION )
        # The string representation of our segment .
        val = buf . getvalue ( )
        reset_stringio ( buf )
        if not last_group and not len ( val ) :
            raise ValueError ( 'Unexpected %s.' % character )
        # When a group happens , the previous value is empty .
        if len ( val ) :
            segments . append ( parse_segment ( val ) )
        combinators . append ( COMBINATORS [ character ] )
    elif character == constants . GROUP_BEGIN : # Recursively go into the next group .
        if buf . tell ( ) :
            raise ValueError ( 'Unexpected %s' % character )
        seg = split_segments ( iterator , True )
        if last_negation :
            seg = UnarySegmentCombinator ( seg )
        segments . append ( seg )
        # Flag that the last entry was a grouping , so that we don ' t panic
        # when the next character is a logical combinator
        last_group = True
        continue
    elif character == constants . GROUP_END : # Build the segment for anything remaining , and then combine
    # all the segments .
        val = buf . getvalue ( )
        # Check for unbalanced parens or an empty thing : foo = bar & ( ) ; bar = baz
        if not buf . tell ( ) or not closing_paren :
            raise ValueError ( 'Unexpected %s' % character )
        segments . append ( parse_segment ( val ) )
        return combine ( segments , combinators )
    elif character == constants . OPERATOR_NEGATION and not buf . tell ( ) :
        last_negation = True
        continue
    else :
        if last_negation :
            buf . write ( constants . OPERATOR_NEGATION )
        if last_group :
            raise ValueError ( 'Unexpected %s' % character )
        buf . write ( character )
    last_negation = False
    last_group = False
else : # Check and see if the iterator exited early ( unbalanced parens )
    if closing_paren :
        raise ValueError ( 'Expected %s.' % constants . GROUP_END )
    if not last_group : # Add the final segment .
        segments . append ( parse_segment ( buf . getvalue ( ) ) )
# Everything completed normally , combine all the segments into one
# and return them .
return combine ( segments , combinators )


signature:
def parse_directive ( key ) :
    """Takes a key of type ( foo : bar ) and returns either the key and the
 directive , or the key and None ( for no directive . )"""

implementation:
if constants . DIRECTIVE in key :
    return key . split ( constants . DIRECTIVE , 1 )
else :
    return key , None


signature:
def parse_segment ( text ) :
    "we expect foo = bar"

implementation:
if not len ( text ) :
    return NoopQuerySegment ( )
q = QuerySegment ( )
# First we need to split the segment into key / value pairs . This is done
# by attempting to split the sequence for each equality comparison . Then
# discard any that did not split properly . Then chose the smallest key
# ( greedily chose the first comparator we encounter in the string )
# followed by the smallest value ( greedily chose the largest comparator
# possible . )
# translate into [ ( ' = ' , ' foo = bar ' ) ]
equalities = zip ( constants . OPERATOR_EQUALITIES , itertools . repeat ( text ) )
# Translate into [ ( ' = ' , [ ' foo ' , ' bar ' ] ) ]
equalities = map ( lambda x : ( x [ 0 ] , x [ 1 ] . split ( x [ 0 ] , 1 ) ) , equalities )
# Remove unsplit entries and translate into [ ( ' = ' : [ ' foo ' , ' bar ' ] ) ]
# Note that the result from this stage is iterated over twice .
equalities = list ( filter ( lambda x : len ( x [ 1 ] ) > 1 , equalities ) )
# Get the smallest key and use the length of that to remove other items
key_len = len ( min ( ( x [ 1 ] [ 0 ] for x in equalities ) , key = len ) )
equalities = filter ( lambda x : len ( x [ 1 ] [ 0 ] ) == key_len , equalities )
# Get the smallest value length . thus we have the earliest key and the
# smallest value .
op , ( key , value ) = min ( equalities , key = lambda x : len ( x [ 1 ] [ 1 ] ) )
key , directive = parse_directive ( key )
if directive :
    op = constants . OPERATOR_EQUALITY_FALLBACK
    q . directive = directive
# Process negation . This comes in both foo . not = and foo ! = forms .
path = key . split ( constants . SEP_PATH )
last = path [ - 1 ]
# Check for ! =
if last . endswith ( constants . OPERATOR_NEGATION ) :
    last = last [ : - 1 ]
    q . negated = not q . negated
# Check for foo . not =
if last == constants . PATH_NEGATION :
    path . pop ( - 1 )
    q . negated = not q . negated
q . values = value . split ( constants . SEP_VALUE )
# Check for suffixed operators ( foo . gte = bar ) . Prioritize suffixed
# entries over actual equality checks .
if path [ - 1 ] in constants . OPERATOR_SUFFIXES : # The case where foo . gte < = bar , which obviously makes no sense .
    if op not in constants . OPERATOR_FALLBACK :
        raise ValueError ( 'Both path-style operator and equality style operator ' 'provided.  Please provide only a single style operator.' )
    q . operator = constants . OPERATOR_SUFFIX_MAP [ path [ - 1 ] ]
    path . pop ( - 1 )
else :
    q . operator = constants . OPERATOR_EQUALITY_MAP [ op ]
if not len ( path ) :
    raise ValueError ( 'No attribute navigation path provided.' )
q . path = path
return q


signature:
def set ( self , target , value ) :
    """Set the value of this attribute for the passed object ."""

implementation:
if not self . _set :
    return
if self . path is None : # There is no path defined on this resource .
# We can do no magic to set the value .
    self . set = lambda * a : None
    return None
if self . _segments [ target . __class__ ] : # Attempt to resolve access to this attribute .
    self . get ( target )
if self . _segments [ target . __class__ ] : # Attribute is not fully resolved ; an interim segment is null .
    return
# Resolve access to the parent object .
# For a single - segment path this will effectively be a no - op .
parent_getter = compose ( * self . _getters [ target . __class__ ] [ : - 1 ] )
target = parent_getter ( target )
# Make the setter .
func = self . _make_setter ( self . path . split ( '.' ) [ - 1 ] , target . __class__ )
# Apply the setter now .
func ( target , value )
# Replace this function with the constructed setter .
def setter ( target , value ) :
    func ( parent_getter ( target ) , value )
self . set = setter


signature:
def parse ( specifiers ) :
    """Consumes set specifiers as text and forms a generator to retrieve
 the requested ranges .
 @ param [ in ] specifiers
 Expected syntax is from the byte - range - specifier ABNF found in the
 [ RFC 2616 ] ; eg . 15-17,151 , - 16,26-278,15
 @ returns
 Consecutive tuples that describe the requested range ; eg . ( 1 , 72 ) or
 (1 , 1 ) [ read as 1 to 72 or 1 to 1 ] ."""

implementation:
specifiers = "" . join ( specifiers . split ( ) )
for specifier in specifiers . split ( ',' ) :
    if len ( specifier ) == 0 :
        raise ValueError ( "Range: Invalid syntax; missing specifier." )
    count = specifier . count ( '-' )
    if ( count and specifier [ 0 ] == '-' ) or not count : # Single specifier ; return as a tuple to itself .
        yield int ( specifier ) , int ( specifier )
        continue
    specifier = list ( map ( int , specifier . split ( '-' ) ) )
    if len ( specifier ) == 2 : # Range specifier ; return as a tuple .
        if specifier [ 0 ] < 0 or specifier [ 1 ] < 0 : # Negative indexing is not supported in range specifiers
        # as stated in the HTTP / 1.1 Range header specification .
            raise ValueError ( "Range: Invalid syntax; negative indexing " "not supported in a range specifier." )
        if specifier [ 1 ] < specifier [ 0 ] : # Range must be for at least one item .
            raise ValueError ( "Range: Invalid syntax; stop is less than start." )
        # Return them as a immutable tuple .
        yield tuple ( specifier )
        continue
    # Something weird happened .
    raise ValueError ( "Range: Invalid syntax." )


signature:
def paginate ( request , response , items ) :
    """Paginate an iterable during a request .
 Magically splicling an iterable in our supported ORMs allows LIMIT and
 OFFSET queries . We should probably delegate this to the ORM or something
 in the future ."""

implementation:
# TODO : support dynamic rangewords and page lengths
# TODO : support multi - part range requests
# Get the header
header = request . headers . get ( 'Range' )
if not header : # No range header ; move along .
    return items
# do some validation
prefix = RANGE_SPECIFIER + '='
if not header . find ( prefix ) == 0 : # This is not using a range specifier that we understand
    raise exceptions . RequestedRangeNotSatisfiable ( )
else : # Chop the prefix off the header and parse it
    ranges = parse ( header [ len ( prefix ) : ] )
ranges = list ( ranges )
if len ( ranges ) > 1 :
    raise exceptions . RequestedRangeNotSatisfiable ( 'Multiple ranges in a single request is not yet supported.' )
start , end = ranges [ 0 ]
# Make sure the length is not higher than the total number allowed .
max_length = request . resource . count ( items )
end = min ( end , max_length )
response . status = client . PARTIAL_CONTENT
response . headers [ 'Content-Range' ] = '%d-%d/%d' % ( start , end , max_length )
response . headers [ 'Accept-Ranges' ] = RANGE_SPECIFIER
# Splice and return the items .
items = items [ start : end + 1 ]
return items


signature:
def indexesOptional ( f ) :
    """Decorate test methods with this if you don ' t require strict index checking"""

implementation:
stack = inspect . stack ( )
_NO_INDEX_CHECK_NEEDED . add ( '%s.%s.%s' % ( f . __module__ , stack [ 1 ] [ 3 ] , f . __name__ ) )
del stack
return f


signature:
def read ( self , deserialize = False , format = None ) :
    """Read and return the request data .
 @ param [ in ] deserialize
 True to deserialize the resultant text using a determiend format
 or the passed format .
 @ param [ in ] format
 A specific format to deserialize in ; if provided , no detection is
 done . If not provided , the content - type header is looked at to
 determine an appropriate deserializer ."""

implementation:
if deserialize :
    data , _ = self . deserialize ( format = format )
    return data
content = self . _read ( )
if not content :
    return ''
if type ( content ) is six . binary_type :
    content = content . decode ( self . encoding )
return content


signature:
def use ( ** kwargs ) :
    """Updates the active resource configuration to the passed
 keyword arguments .
 Invoking this method without passing arguments will just return the
 active resource configuration .
 @ returns
 The previous configuration ."""

implementation:
config = dict ( use . config )
use . config . update ( kwargs )
return config


signature:
def try_delegation ( method ) :
    '''This decorator wraps descriptor methods with a new method that tries
 to delegate to a function of the same name defined on the owner instance
 for convenience for dispatcher clients .'''

implementation:
@ functools . wraps ( method )
def delegator ( self , * args , ** kwargs ) :
    if self . try_delegation : # Try to dispatch to the instance ' s implementation .
        inst = getattr ( self , 'inst' , None )
        if inst is not None :
            method_name = ( self . delegator_prefix or '' ) + method . __name__
            func = getattr ( inst , method_name , None )
            if func is not None :
                return func ( * args , ** kwargs )
    # Otherwise run the decorated func .
    return method ( self , * args , ** kwargs )
return delegator


signature:
def register ( self , method , args , kwargs ) :
    '''Given a single decorated handler function ,
 prepare , append desired data to self . registry .'''

implementation:
invoc = self . dump_invoc ( * args , ** kwargs )
self . registry . append ( ( invoc , method . __name__ ) )


signature:
def gen_methods ( self , * args , ** kwargs ) :
    '''Find all method names this input dispatches to . This method
 can accept * args , * * kwargs , but it ' s the gen _ dispatch method ' s
 job of passing specific args to handler methods .'''

implementation:
dispatched = False
for invoc , methodname in self . registry :
    args , kwargs = self . loads ( invoc )
    yield getattr ( self . inst , methodname ) , args , kwargs
    dispatched = True
if dispatched :
    return
# Try the generic handler .
generic_handler = getattr ( self . inst , 'generic_handler' , None )
if generic_handler is not None :
    yield generic_handler , args , kwargs
# Give up .
msg = 'No method was found for %r on %r.'
raise self . DispatchError ( msg % ( ( args , kwargs ) , self . inst ) )


signature:
def get_method ( self , * args , ** kwargs ) :
    '''Find the first method this input dispatches to .'''

implementation:
for method in self . gen_methods ( * args , ** kwargs ) :
    return method
msg = 'No method was found for %r on %r.'
raise self . DispatchError ( msg % ( ( args , kwargs ) , self . inst ) )


signature:
def dispatch ( self , * args , ** kwargs ) :
    '''Find and evaluate / return the first method this input dispatches to .'''

implementation:
for result in self . gen_dispatch ( * args , ** kwargs ) :
    return result


signature:
def gen_dispatch ( self , * args , ** kwargs ) :
    '''Find and evaluate / yield every method this input dispatches to .'''

implementation:
dispatched = False
for method_data in self . gen_methods ( * args , ** kwargs ) :
    dispatched = True
    result = self . apply_handler ( method_data , * args , ** kwargs )
    yield result
    # return self . yield _ from _ handler ( result )
if dispatched :
    return
msg = 'No method was found for %r on %r.'
raise self . DispatchError ( msg % ( ( args , kwargs ) , self . inst ) )


signature:
def gen_method_keys ( self , * args , ** kwargs ) :
    '''Given a node , return the string to use in computing the
 matching visitor methodname . Can also be a generator of strings .'''

implementation:
token = args [ 0 ]
for mro_type in type ( token ) . __mro__ [ : - 1 ] :
    name = mro_type . __name__
    yield name


signature:
def gen_methods ( self , * args , ** kwargs ) :
    '''Find all method names this input dispatches to .'''

implementation:
token = args [ 0 ]
inst = self . inst
prefix = self . _method_prefix
for method_key in self . gen_method_keys ( * args , ** kwargs ) :
    method = getattr ( inst , prefix + method_key , None )
    if method is not None :
        yield method
# Fall back to built - in types , then types , then collections .
typename = type ( token ) . __name__
yield from self . check_basetype ( token , typename , self . builtins . get ( typename ) )
for basetype_name in self . interp_types :
    yield from self . check_basetype ( token , basetype_name , getattr ( self . types , basetype_name , None ) )
for basetype_name in self . abc_types :
    yield from self . check_basetype ( token , basetype_name , getattr ( self . collections , basetype_name , None ) )
# Try the generic handler .
yield from self . gen_generic ( )


signature:
def apply_handler ( self , method_data , * args , ** kwargs ) :
    '''Call the dispatched function , optionally with other data
 stored / created during . register and . prepare . Assume the arguments
 passed in by the dispathcer are the only ones required .'''

implementation:
if isinstance ( method_data , tuple ) :
    len_method = len ( method_data )
    method = method_data [ 0 ]
    if 1 < len_method :
        args = method_data [ 1 ]
    if 2 < len_method :
        kwargs = method_data [ 2 ]
else :
    method = method_data
return method ( * args , ** kwargs )


signature:
def parse ( cls , s , required = False ) :
    """Parse string to create an instance
 : param str s : String with requirement to parse
 : param bool required : Is this requirement required to be fulfilled ? If not , then it is a filter ."""

implementation:
req = pkg_resources . Requirement . parse ( s )
return cls ( req , required = required )


signature:
def add ( self , requirements , required = None ) :
    """Add requirements to be managed
 : param list / Requirement requirements : List of : class : ` BumpRequirement ` or : class : ` pkg _ resources . Requirement `
 : param bool required : Set required flag for each requirement if provided ."""

implementation:
if isinstance ( requirements , RequirementsManager ) :
    requirements = list ( requirements )
elif not isinstance ( requirements , list ) :
    requirements = [ requirements ]
for req in requirements :
    name = req . project_name
    if not isinstance ( req , BumpRequirement ) :
        req = BumpRequirement ( req , required = required )
    elif required is not None :
        req . required = required
    add = True
    if name in self . requirements :
        for existing_req in self . requirements [ name ] :
            if req == existing_req :
                add = False
                break
            # Need to replace existing as the new req will be used to bump next , and req . required could be
            # updated .
            replace = False
            # Two pins : Use highest pinned version
            if ( req . specs and req . specs [ 0 ] [ 0 ] == '==' and existing_req . specs and existing_req . specs [ 0 ] [ 0 ] == '==' ) :
                if pkg_resources . parse_version ( req . specs [ 0 ] [ 1 ] ) < pkg_resources . parse_version ( existing_req . specs [ 0 ] [ 1 ] ) :
                    req . requirement = existing_req . requirement
                replace = True
            # Replace Any
            if not ( req . specs and existing_req . specs ) :
                if existing_req . specs :
                    req . requirement = existing_req . requirement
                replace = True
            if replace :
                req . required |= existing_req . required
                if existing_req . required_by and not req . required_by :
                    req . required_by = existing_req . required_by
                self . requirements [ name ] . remove ( existing_req )
                break
    if add :
        self . requirements [ name ] . append ( req )


signature:
def check ( self , context , version = None ) :
    """Check off requirements that are met by name / version .
 : param str | Bump | Requirement context : Either package name , requirement string , : class : ` Bump ` ,
 : class : ` BumpRequirement ` , or
 : class : ` pkg _ resources . Requirement instance
 : return : True if any requirement was satisified by context"""

implementation:
req_str = None
self . checked . append ( ( context , version ) )
if isinstance ( context , str ) and not version :
    context = BumpRequirement . parse ( context )
if isinstance ( context , Bump ) :
    name = context . name
    if context . new_version and context . new_version [ 0 ] == '==' :
        version = context . new_version [ 1 ]
    else :
        req_str = str ( context )
elif isinstance ( context , ( pkg_resources . Requirement , BumpRequirement ) ) :
    name = context . project_name
    if context . specs and context . specs [ 0 ] [ 0 ] == '==' :
        version = context . specs [ 0 ] [ 1 ]
    else :
        req_str = str ( context )
else :
    name = context
if name in self :
    self . matched_name = True
    for req in self [ name ] :
        if req . required and ( version and version in req or req_str == str ( req ) ) :
            req . required = False
            return True
return False


signature:
def satisfied_by_checked ( self , req ) :
    """Check if requirement is already satisfied by what was previously checked
 : param Requirement req : Requirement to check"""

implementation:
req_man = RequirementsManager ( [ req ] )
return any ( req_man . check ( * checked ) for checked in self . checked )


signature:
def from_requirement ( cls , req , changes = None ) :
    """Create an instance from : class : ` pkg _ resources . Requirement ` instance"""

implementation: return cls ( req . project_name , req . specs and '' . join ( req . specs [ 0 ] ) or '' , changes = changes )


signature:
def as_requirement ( self ) :
    """Convert back to a : class : ` pkg _ resources . Requirement ` instance"""

implementation:
if self . new_version :
    return pkg_resources . Requirement . parse ( self . name + '' . join ( self . new_version ) )
else :
    return pkg_resources . Requirement . parse ( self . name )


signature:
def require ( self , req ) :
    """Add new requirements that must be fulfilled for this bump to occur"""

implementation:
reqs = req if isinstance ( req , list ) else [ req ]
for req in reqs :
    if not isinstance ( req , BumpRequirement ) :
        req = BumpRequirement ( req )
    req . required = True
    req . required_by = self
    self . requirements . append ( req )


signature:
def requirements_for_changes ( self , changes ) :
    """Parse changes for requirements
 : param list changes :"""

implementation:
requirements = [ ]
reqs_set = set ( )
if isinstance ( changes , str ) :
    changes = changes . split ( '\n' )
if not changes or changes [ 0 ] . startswith ( '-' ) :
    return requirements
for line in changes :
    line = line . strip ( ' -+*' )
    if not line :
        continue
    match = IS_REQUIREMENTS_RE2 . search ( line )
    # or IS _ REQUIREMENTS _ RE . match ( line )
    if match :
        for match in REQUIREMENTS_RE . findall ( match . group ( 1 ) ) :
            if match [ 1 ] :
                version = '==' + match [ 2 ] if match [ 1 ] . startswith ( ' to ' ) else match [ 1 ]
                req_str = match [ 0 ] + version
            else :
                req_str = match [ 0 ]
            if req_str not in reqs_set :
                reqs_set . add ( req_str )
                try :
                    requirements . append ( pkg_resources . Requirement . parse ( req_str ) )
                except Exception as e :
                    log . warn ( 'Could not parse requirement "%s" from changes: %s' , req_str , e )
return requirements


signature:
def package_changes ( self , name , current_version , new_version ) :
    """List of changes for package name from current _ version to new _ version , in descending order .
 If current version is higher than new version ( downgrade ) , then a minus sign will be prefixed to each change ."""

implementation:
if pkg_resources . parse_version ( current_version ) > pkg_resources . parse_version ( new_version ) :
    downgrade_sign = '- '
    ( current_version , new_version ) = ( new_version , current_version )
else :
    downgrade_sign = None
changes = self . _package_changes ( name , current_version , new_version )
if changes and downgrade_sign :
    changes = [ downgrade_sign + c for c in changes ]
return changes


signature:
def _bump ( self , existing_req = None , bump_reqs = None ) :
    """Bump an existing requirement to the desired requirement if any .
 Subclass can override this ` _ bump ` method to change how each requirement is bumped .
 BR = Bump to Requested Version
 BL = Bump to Latest Version
 BLR = Bump to Latest Version per Requested Requirement
 BROL = Bump to Requested Version or Latest ( if Pin )
 N = No Bump
 ERR = Error
 C = Version Conflict
 Pin case " requires = " will be required .
 Filter case " requires = " will be :
 1 ) From user = Required
 2 ) From bump = bump / require if existing = One , otherwise print warning .
 Filter Case : :
 Bump : None Any One Many
 Existing :
 None N N N N
 Any N N BR BR
 One BL BL BR BR
 Many N N BR BR
 Pin Case : :
 Bump : None Any One Many
 Existing :
 None N N N N
 Any N N BR BLR *
 One BL BL BR BLR *
 Many N N BR BLR *
 Add / Require Case : :
 Bump : None Any One Many
 Existing :
 None N BROL BROL BROL
 : param pkg _ resources . Requirement existing _ req : Existing requirement if any
 : param list bump _ reqs : List of ` BumpRequirement `
 : return Bump : Either a : class : ` Bump ` instance or None
 : raise BumpAccident :"""

implementation:
if existing_req or bump_reqs and any ( r . required for r in bump_reqs ) :
    name = existing_req and existing_req . project_name or bump_reqs [ 0 ] . project_name
    log . info ( 'Checking %s' , name )
    bump = current_version = new_version = None
    if bump_reqs : # BLR : Pin with Many bump requirements
        if self . should_pin ( ) and ( len ( bump_reqs ) > 1 or bump_reqs [ 0 ] and bump_reqs [ 0 ] . specs and bump_reqs [ 0 ] . specs [ 0 ] [ 0 ] != '==' ) :
            log . debug ( 'Bump to latest within requirements: %s' , bump_reqs )
            new_version = self . latest_version_for_requirements ( bump_reqs )
            current_version = ( existing_req and existing_req . specs and existing_req . specs [ 0 ] [ 0 ] == '==' and existing_req . specs [ 0 ] [ 1 ] )
            if current_version == new_version :
                return None
            bump = Bump ( name , ( '==' , new_version ) )
        elif len ( bump_reqs ) > 1 :
            raise BumpAccident ( 'Not sure which requirement to use for %s: %s' % ( name , ', ' . join ( str ( r ) for r in bump_reqs ) ) )
        # BR : Pin with One bump requirement or Filter with One or Many bump requirements or
        # Bump to Any required .
        elif bump_reqs [ 0 ] . specs or not ( existing_req or self . should_pin ( ) or bump_reqs [ 0 ] . specs ) :
            log . debug ( 'Bump to requirement: %s' , bump_reqs )
            latest_version = self . latest_version_for_requirements ( bump_reqs )
            new_version = ( bump_reqs [ 0 ] . specs and bump_reqs [ 0 ] . specs [ 0 ] [ 0 ] == '==' and bump_reqs [ 0 ] . specs [ 0 ] [ 1 ] or latest_version )
            current_version = ( existing_req and existing_req . specs and existing_req . specs [ 0 ] [ 0 ] == '==' and existing_req . specs [ 0 ] [ 1 ] )
            if current_version == new_version :
                return None
            if len ( bump_reqs [ 0 ] . specs ) > 1 :
                version = ( ',' . join ( s [ 0 ] + s [ 1 ] for s in bump_reqs [ 0 ] . specs ) , )
            elif bump_reqs [ 0 ] . specs :
                version = bump_reqs [ 0 ] . specs [ 0 ]
            else :
                version = None
            bump = Bump ( name , version )
    # BL : Pin to Latest
    if not bump and ( existing_req and existing_req . specs and existing_req . specs [ 0 ] [ 0 ] == '==' or self . should_pin ( ) and not existing_req ) :
        log . debug ( 'Bump to latest: %s' , bump_reqs or name )
        current_version = existing_req and existing_req . specs [ 0 ] [ 1 ]
        new_version = self . latest_package_version ( name )
        if current_version == new_version :
            return None
        if not new_version :
            raise BumpAccident ( 'No published version found for %s' % name )
        bump = Bump ( name , ( '==' , new_version ) )
    if bump and current_version and new_version and self . detail :
        changes = self . package_changes ( bump . name , current_version , new_version )
        bump . changes . extend ( changes )
        if self . should_pin ( ) :
            bump . require ( self . requirements_for_changes ( changes ) )
    if bump :
        log . debug ( 'Bumped %s' , bump )
        if bump . requirements :
            log . info ( 'Changes in %s require: %s' , bump . name , ', ' . join ( sorted ( str ( r ) for r in bump . requirements ) ) )
    return bump if str ( bump ) != str ( existing_req ) else None


signature:
def bump ( self , bump_reqs = None , ** kwargs ) :
    """Bump dependencies using given requirements .
 : param RequirementsManager bump _ reqs : Bump requirements manager
 : param dict kwargs : Additional args from argparse . Some bumpers accept user options , and some not .
 : return : List of : class : ` Bump ` changes made ."""

implementation:
bumps = { }
for existing_req in sorted ( self . requirements ( ) , key = lambda r : r . project_name ) :
    if bump_reqs and existing_req . project_name not in bump_reqs :
        continue
    bump_reqs . check ( existing_req )
    try :
        bump = self . _bump ( existing_req , bump_reqs . get ( existing_req . project_name ) )
        if bump :
            bumps [ bump . name ] = bump
            bump_reqs . check ( bump )
    except Exception as e :
        if bump_reqs and bump_reqs . get ( existing_req . project_name ) and all ( r . required_by is None for r in bump_reqs . get ( existing_req . project_name ) ) :
            raise
        else :
            log . warn ( e )
for reqs in bump_reqs . required_requirements ( ) . values ( ) :
    name = reqs [ 0 ] . project_name
    if name not in bumps and self . should_add ( name ) :
        try :
            bump = self . _bump ( None , reqs )
            if bump :
                bumps [ bump . name ] = bump
                bump_reqs . check ( bump )
        except Exception as e :
            if all ( r . required_by is None for r in reqs ) :
                raise
            else :
                log . warn ( e )
self . bumps . update ( bumps . values ( ) )
return bumps . values ( )


signature:
def reverse ( self ) :
    """Restore content in target file to be before any changes"""

implementation:
if self . _original_target_content :
    with open ( self . target , 'w' ) as fp :
        fp . write ( self . _original_target_content )


signature:
def serialize ( self , data = None ) :
    """Transforms the object into an acceptable format for transmission .
 @ throws ValueError
 To indicate this serializer does not support the encoding of the
 specified object ."""

implementation:
if data is not None and self . response is not None : # Set the content type .
    self . response [ 'Content-Type' ] = self . media_types [ 0 ]
    # Write the encoded and prepared data to the response .
    self . response . write ( data )
# Return the serialized data .
# This has normally been transformed by a base class .
return data


signature:
def cons ( collection , value ) :
    """Extends a collection with a value ."""

implementation:
if isinstance ( value , collections . Mapping ) :
    if collection is None :
        collection = { }
    collection . update ( ** value )
elif isinstance ( value , six . string_types ) :
    if collection is None :
        collection = [ ]
    collection . append ( value )
elif isinstance ( value , collections . Iterable ) :
    if collection is None :
        collection = [ ]
    collection . extend ( value )
else :
    if collection is None :
        collection = [ ]
    collection . append ( value )
return collection


signature:
def _merge ( options , name , bases , default = None ) :
    """Merges a named option collection ."""

implementation:
result = None
for base in bases :
    if base is None :
        continue
    value = getattr ( base , name , None )
    if value is None :
        continue
    result = utils . cons ( result , value )
value = options . get ( name )
if value is not None :
    result = utils . cons ( result , value )
return result or default


signature:
def parse_requirements ( requirements , in_file = None ) :
    """Parse string requirements into list of : class : ` pkg _ resources . Requirement ` instances
 : param str requirements : Requirements text to parse
 : param str in _ file : File the requirements came from
 : return : List of requirements
 : raises ValueError : if failed to parse"""

implementation:
try :
    return list ( pkg_resources . parse_requirements ( requirements ) )
except Exception as e :
    in_file = ' in %s' % in_file if in_file else ''
    raise ValueError ( '{} {}' . format ( e , in_file ) )


signature:
def package_info ( cls , package ) :
    """All package info for given package"""

implementation:
if package not in cls . package_info_cache :
    package_json_url = 'https://pypi.python.org/pypi/%s/json' % package
    try :
        logging . getLogger ( 'requests' ) . setLevel ( logging . WARN )
        response = requests . get ( package_json_url )
        response . raise_for_status ( )
        cls . package_info_cache [ package ] = simplejson . loads ( response . text )
    except Exception as e :
        log . debug ( 'Could not get package info from %s: %s' , package_json_url , e )
        cls . package_info_cache [ package ] = None
return cls . package_info_cache [ package ]


signature:
def all_package_versions ( package ) :
    """All versions for package"""

implementation:
info = PyPI . package_info ( package )
return info and sorted ( info [ 'releases' ] . keys ( ) , key = lambda x : x . split ( ) , reverse = True ) or [ ]


signature:
def insert ( self , name , index , value ) :
    """Insert a value at the passed index in the named header ."""

implementation: return self . _sequence [ name ] . insert ( index , value )


signature:
def close ( self ) :
    """Flush and close the stream .
 This is called automatically by the base resource on resources
 unless the resource is operating asynchronously ; in that case ,
 this method MUST be called in order to signal the end of the request .
 If not the request will simply hang as it is waiting for some
 thread to tell it to return to the client ."""

implementation:
# Ensure we ' re not closed .
self . require_not_closed ( )
if not self . streaming or self . asynchronous : # We ' re not streaming , auto - write content - length if not
# already set .
    if 'Content-Length' not in self . headers :
        self . headers [ 'Content-Length' ] = self . tell ( )
# Flush out the current buffer .
self . flush ( )
# We ' re done with the response ; inform the HTTP connector
# to close the response stream .
self . _closed = True


signature:
def write ( self , chunk , serialize = False , format = None ) :
    """Writes the given chunk to the output buffer .
 @ param [ in ] chunk
 Either a byte array , a unicode string , or a generator . If ` chunk `
 is a generator then calling ` self . write ( < generator > ) ` is
 equivalent to :
 @ code
 for x in < generator > :
 self . write ( x )
 self . flush ( )
 @ endcode
 @ param [ in ] serialize
 True to serialize the lines in a determined serializer .
 @ param [ in ] format
 A specific format to serialize in ; if provided , no detection is
 done . If not provided , the accept header ( as well as the URL
 extension ) is looked at to determine an appropriate serializer ."""

implementation:
# Ensure we ' re not closed .
self . require_not_closed ( )
if chunk is None : # There is nothing here .
    return
if serialize or format is not None : # Forward to the serializer to serialize the chunk
# before it gets written to the response .
    self . serialize ( chunk , format = format )
    return
# ` serialize ` invokes write ( . . . )
if type ( chunk ) is six . binary_type : # Update the stream length .
    self . _length += len ( chunk )
    # If passed a byte string , we hope the user encoded it properly .
    self . _stream . write ( chunk )
elif isinstance ( chunk , six . string_types ) :
    encoding = self . encoding
    if encoding is not None : # If passed a string , we can encode it for the user .
        chunk = chunk . encode ( encoding )
    else : # Bail ; we don ' t have an encoding .
        raise exceptions . InvalidOperation ( 'Attempting to write textual data without an encoding.' )
    # Update the stream length .
    self . _length += len ( chunk )
    # Write the encoded data into the byte stream .
    self . _stream . write ( chunk )
elif isinstance ( chunk , collections . Iterable ) : # If passed some kind of iterator , attempt to recurse into
# oblivion .
    for section in chunk :
        self . write ( section )
else : # Bail ; we have no idea what to do with this .
    raise exceptions . InvalidOperation ( 'Attempting to write something not recognized.' )


signature:
def serialize ( self , data , format = None ) :
    """Serializes the data into this response using a serializer .
 @ param [ in ] data
 The data to be serialized .
 @ param [ in ] format
 A specific format to serialize in ; if provided , no detection is
 done . If not provided , the accept header ( as well as the URL
 extension ) is looked at to determine an appropriate serializer .
 @ returns
 A tuple of the serialized text and an instance of the
 serializer used ."""

implementation: return self . _resource . serialize ( data , response = self , format = format )


signature:
def flush ( self ) :
    """Flush the write buffers of the stream .
 This results in writing the current contents of the write buffer to
 the transport layer , initiating the HTTP / 1.1 response . This initiates
 a streaming response . If the ` Content - Length ` header is not given
 then the chunked ` Transfer - Encoding ` is applied ."""

implementation:
# Ensure we ' re not closed .
self . require_not_closed ( )
# Pull out the accumulated chunk .
chunk = self . _stream . getvalue ( )
self . _stream . truncate ( 0 )
self . _stream . seek ( 0 )
# Append the chunk to the body .
self . body = chunk if ( self . _body is None ) else ( self . _body + chunk )
if self . asynchronous : # We are now streaming because we ' re asynchronous .
    self . streaming = True


signature:
def send ( self , * args , ** kwargs ) :
    """Writes the passed chunk and flushes it to the client ."""

implementation:
self . write ( * args , ** kwargs )
self . flush ( )


signature:
def end ( self , * args , ** kwargs ) :
    """Writes the passed chunk , flushes it to the client ,
 and terminates the connection ."""

implementation:
self . send ( * args , ** kwargs )
self . close ( )


implementation: return self . headers . insert ( index , value )


signature:
def create_project ( self ) :
    """Creates a base Flask project"""

implementation:
if os . path . exists ( self . _py ) :
    prj_dir = os . path . join ( self . _app_dir , self . _project_name )
    if os . path . exists ( prj_dir ) :
        if self . _force :
            logging . warn ( 'Removing existing project' )
            shutil . rmtree ( prj_dir )
        else :
            logging . warn ( 'Found existing project; not creating (use --force to overwrite)' )
            return
    logging . info ( 'Creating project' )
    os . makedirs ( prj_dir )
    # create the flask project stub
    app = """#!/usr/bin/env python\n""" """from flask import Flask\n""" """app = Flask(__name__)\n\n""" """@app.route(\"/\")\n""" """def hello():\n""" """    return \"Hello from Flask...\"\n\n""" """if __name__==\"__main__\":\n""" """    app.run()\n\n"""
    with open ( os . path . join ( prj_dir , 'app.py' ) , 'w' ) as f :
        f . write ( app )
else :
    logging . error ( 'Unable to find Python interpreter in virtualenv' )
    return


signature:
def replaced_directory ( dirname ) :
    """This ` ` Context Manager ` ` is used to move the contents of a directory
 elsewhere temporarily and put them back upon exit . This allows testing
 code to use the same file directories as normal code without fear of
 damage .
 The name of the temporary directory which contains your files is yielded .
 : param dirname :
 Path name of the directory to be replaced .
 Example :
 . . code - block : : python
 with replaced _ directory ( ' / foo / bar / ' ) as rd :
 # " / foo / bar / " has been moved & renamed
 with open ( ' / foo / bar / thing . txt ' , ' w ' ) as f :
 f . write ( ' stuff ' )
 f . close ( )
 # got here ? = > " / foo / bar / is now restored and temp has been wiped ,
 # " thing . txt " is gone"""

implementation:
if dirname [ - 1 ] == '/' :
    dirname = dirname [ : - 1 ]
full_path = os . path . abspath ( dirname )
if not os . path . isdir ( full_path ) :
    raise AttributeError ( 'dir_name must be a directory' )
base , name = os . path . split ( full_path )
# create a temporary directory , move provided dir into it and recreate the
# directory for the user
tempdir = tempfile . mkdtemp ( )
shutil . move ( full_path , tempdir )
os . mkdir ( full_path )
try :
    yield tempdir
finally : # done context , undo everything
    shutil . rmtree ( full_path )
    moved = os . path . join ( tempdir , name )
    shutil . move ( moved , base )
    shutil . rmtree ( tempdir )


signature:
def capture_stdout ( ) :
    """This ` ` Context Manager ` ` redirects STDOUT to a ` ` StringIO ` ` objects
 which is returned from the ` ` Context ` ` . On exit STDOUT is restored .
 Example :
 . . code - block : : python
 with capture _ stdout ( ) as capture :
 print ( ' foo ' )
 # got here ? = > capture . getvalue ( ) will now have " foo \\ n " """

implementation:
stdout = sys . stdout
try :
    capture_out = StringIO ( )
    sys . stdout = capture_out
    yield capture_out
finally :
    sys . stdout = stdout


signature:
def capture_stderr ( ) :
    """This ` ` Context Manager ` ` redirects STDERR to a ` ` StringIO ` ` objects
 which is returned from the ` ` Context ` ` . On exit STDERR is restored .
 Example :
 . . code - block : : python
 with capture _ stderr ( ) as capture :
 print ( ' foo ' )
 # got here ? = > capture . getvalue ( ) will now have " foo \\ n " """

implementation:
stderr = sys . stderr
try :
    capture_out = StringIO ( )
    sys . stderr = capture_out
    yield capture_out
finally :
    sys . stderr = stderr


signature:
def create ( self , a , b , c ) :
    """. . _ createoptions :
 Create an option object used to start the manager
 : param a : The path of the config directory
 : type a : str
 : param b : The path of the user directory
 : type b : str
 : param c : The " command line " options of the openzwave library
 : type c : str
 : see : destroyoptions _"""

implementation:
self . options = CreateOptions ( str_to_cppstr ( a ) , str_to_cppstr ( b ) , str_to_cppstr ( c ) )
return True


signature:
def addOptionBool ( self , name , value ) :
    """. . _ addOptionBool :
 Add a boolean option .
 : param name : The name of the option .
 : type name : str
 : param value : The value of the option .
 : type value : boolean
 : return : The result of the operation .
 : rtype : bool
 : see : addOption _ , addOptionInt _ , addOptionString _"""

implementation: return self . options . AddOptionBool ( str_to_cppstr ( name ) , value )


signature:
def addOptionInt ( self , name , value ) :
    """. . _ addOptionInt :
 Add an integer option .
 : param name : The name of the option .
 : type name : str
 : param value : The value of the option .
 : type value : boolean
 : return : The result of the operation .
 : rtype : bool
 : see : addOption _ , addOptionBool _ , addOptionString _"""

implementation: return self . options . AddOptionInt ( str_to_cppstr ( name ) , value )


signature:
def addOptionString ( self , name , value , append = False ) :
    """. . _ addOptionString :
 Add a string option .
 : param name : The name of the option . Option names are case insensitive and must be unique .
 : type name : str
 : param value : The value of the option .
 : type value : str
 : param append : Setting append to true will cause values read from the command line
 or XML file to be concatenated into a comma delimited set . If _ append is false ,
 newer values will overwrite older ones .
 : type append : boolean
 : return : The result of the operation .
 : rtype : bool
 : see : addOption _ , addOptionBool _ , addOptionInt _"""

implementation: return self . options . AddOptionString ( str_to_cppstr ( name ) , str_to_cppstr ( value ) , append )


signature:
def addOption ( self , name , value ) :
    """. . _ addOption :
 Add an option .
 : param name : The name of the option .
 : type name : string
 : param value : The value of the option .
 : type value : boolean , integer , string
 : return : The result of the operation .
 : rtype : bool
 : see : addOptionBool _ , addOptionInt _ , addOptionString _"""

implementation:
if name not in PyOptionList :
    return False
if PyOptionList [ name ] [ 'type' ] == "String" :
    return self . addOptionString ( name , value )
elif PyOptionList [ name ] [ 'type' ] == "Bool" :
    return self . addOptionBool ( name , value )
elif PyOptionList [ name ] [ 'type' ] == "Int" :
    return self . addOptionInt ( name , value )
return False


signature:
def getOption ( self , name ) :
    """. . _ getOption :
 Retrieve option of a value .
 : param name : The name of the option .
 : type name : string
 : return : The value
 : rtype : boolean , integer , string or None
 : see : getOptionAsBool _ , getOptionAsInt _ , getOptionAsString _"""

implementation:
if name not in PyOptionList :
    return None
if PyOptionList [ name ] [ 'type' ] == "String" :
    return self . getOptionAsString ( name )
elif PyOptionList [ name ] [ 'type' ] == "Bool" :
    return self . getOptionAsBool ( name )
elif PyOptionList [ name ] [ 'type' ] == "Int" :
    return self . getOptionAsInt ( name )
return False


signature:
def urls ( cls ) :
    """Builds the URL configuration for this resource ."""

implementation: return urls . patterns ( '' , urls . url ( r'^{}(?:$|(?P<path>[/:(.].*))' . format ( cls . meta . name ) , cls . view , name = 'armet-api-{}' . format ( cls . meta . name ) , kwargs = { 'resource' : cls . meta . name } ) )


signature:
def dump ( obj , fp , startindex = 1 , separator = DEFAULT , index_separator = DEFAULT ) :
    '''Dump an object in req format to the fp given .
 : param Mapping obj : The object to serialize . Must have a keys method .
 : param fp : A writable that can accept all the types given .
 : param separator : The separator between key and value . Defaults to u ' | ' or b ' | ' , depending on the types .
 : param index _ separator : The separator between key and index . Defaults to u ' _ ' or b ' _ ' , depending on the types .'''

implementation:
if startindex < 0 :
    raise ValueError ( 'startindex must be non-negative, but was {}' . format ( startindex ) )
try :
    firstkey = next ( iter ( obj . keys ( ) ) )
except StopIteration :
    return
if isinstance ( firstkey , six . text_type ) :
    converter = six . u
else :
    converter = six . b
default_separator = converter ( '|' )
default_index_separator = converter ( '_' )
newline = converter ( '\n' )
if separator is DEFAULT :
    separator = default_separator
if index_separator is DEFAULT :
    index_separator = default_index_separator
for key , value in six . iteritems ( obj ) :
    if isinstance ( value , ( list , tuple , set ) ) :
        for index , item in enumerate ( value , start = startindex ) :
            fp . write ( key )
            fp . write ( index_separator )
            fp . write ( converter ( str ( index ) ) )
            fp . write ( separator )
            fp . write ( item )
            fp . write ( newline )
    else :
        fp . write ( key )
        fp . write ( separator )
        fp . write ( value )
        fp . write ( newline )


signature:
def dumps ( obj , startindex = 1 , separator = DEFAULT , index_separator = DEFAULT ) :
    '''Dump an object in req format to a string .
 : param Mapping obj : The object to serialize . Must have a keys method .
 : param separator : The separator between key and value . Defaults to u ' | ' or b ' | ' , depending on the types .
 : param index _ separator : The separator between key and index . Defaults to u ' _ ' or b ' _ ' , depending on the types .'''

implementation:
try :
    firstkey = next ( iter ( obj . keys ( ) ) )
except StopIteration :
    return str ( )
if isinstance ( firstkey , six . text_type ) :
    io = StringIO ( )
else :
    io = BytesIO ( )
dump ( obj = obj , fp = io , startindex = startindex , separator = separator , index_separator = index_separator , )
return io . getvalue ( )


signature:
def load ( fp , separator = DEFAULT , index_separator = DEFAULT , cls = dict , list_cls = list ) :
    '''Load an object from the file pointer .
 : param fp : A readable filehandle .
 : param separator : The separator between key and value . Defaults to u ' | ' or b ' | ' , depending on the types .
 : param index _ separator : The separator between key and index . Defaults to u ' _ ' or b ' _ ' , depending on the types .
 : param cls : A callable that returns a Mapping that is filled with pairs . The most common alternate option would be OrderedDict .
 : param list _ cls : A callable that takes an iterable and returns a sequence .'''

implementation:
converter = None
output = cls ( )
arraykeys = set ( )
for line in fp :
    if converter is None :
        if isinstance ( line , six . text_type ) :
            converter = six . u
        else :
            converter = six . b
        default_separator = converter ( '|' )
        default_index_separator = converter ( '_' )
        newline = converter ( '\n' )
        if separator is DEFAULT :
            separator = default_separator
        if index_separator is DEFAULT :
            index_separator = default_index_separator
    key , value = line . strip ( ) . split ( separator , 1 )
    keyparts = key . split ( index_separator )
    try :
        index = int ( keyparts [ - 1 ] )
        endwithint = True
    except ValueError :
        endwithint = False
    # We do everything in - place to ensure that we maintain order when using
    # an OrderedDict .
    if len ( keyparts ) > 1 and endwithint : # If this is an array key
        basekey = key . rsplit ( index_separator , 1 ) [ 0 ]
        if basekey not in arraykeys :
            arraykeys . add ( basekey )
        if basekey in output : # If key already exists as non - array , fix it
            if not isinstance ( output [ basekey ] , dict ) :
                output [ basekey ] = { - 1 : output [ basekey ] }
        else :
            output [ basekey ] = { }
        output [ basekey ] [ index ] = value
    else :
        if key in output and isinstance ( output [ key ] , dict ) :
            output [ key ] [ - 1 ] = value
        else :
            output [ key ] = value
# Convert array keys
for key in arraykeys :
    output [ key ] = list_cls ( pair [ 1 ] for pair in sorted ( six . iteritems ( output [ key ] ) ) )
return output


signature:
def loads ( s , separator = DEFAULT , index_separator = DEFAULT , cls = dict , list_cls = list ) :
    '''Loads an object from a string .
 : param s : An object to parse
 : type s : bytes or str
 : param separator : The separator between key and value . Defaults to u ' | ' or b ' | ' , depending on the types .
 : param index _ separator : The separator between key and index . Defaults to u ' _ ' or b ' _ ' , depending on the types .
 : param cls : A callable that returns a Mapping that is filled with pairs . The most common alternate option would be OrderedDict .
 : param list _ cls : A callable that takes an iterable and returns a sequence .'''

implementation:
if isinstance ( s , six . text_type ) :
    io = StringIO ( s )
else :
    io = BytesIO ( s )
return load ( fp = io , separator = separator , index_separator = index_separator , cls = cls , list_cls = list_cls , )


signature:
def bump ( ) :
    """CLI entry point to bump requirements in requirements . txt or pinned . txt"""

implementation:
parser = argparse . ArgumentParser ( description = bump . __doc__ )
parser . add_argument ( 'names' , nargs = '*' , help = """
      Only bump dependencies that match the name.
      Name can be a product group name defined in workspace.cfg.
      To bump to a specific version instead of latest, append version to name
      (i.e. requests==1.2.3 or 'requests>=1.2.3'). When > or < is used, be sure to quote.""" )
parser . add_argument ( '--add' , '--require' , action = 'store_true' , help = 'Add the `names` to the requirements file if they don\'t exist.' )
parser . add_argument ( '--file' , help = 'Requirement file to bump. Defaults to requirements.txt and pinned.txt' )
parser . add_argument ( '--force' , action = 'store_true' , help = 'Force a bump even when certain bump requirements are not met.' )
parser . add_argument ( '-d' , '--detail' , '--dependencies' , action = 'store_true' , help = 'If available, show detailed changes. ' 'For pinned.txt, pin parsed dependency requirements from changes' )
parser . add_argument ( '-n' , '--dry-run' , action = 'store_true' , help = 'Perform a dry run without making changes' )
parser . add_argument ( '--debug' , action = 'store_true' , help = 'Turn on debug mode' )
args = parser . parse_args ( )
targets = [ args . file ] if args . file else [ 'requirements.txt' , 'pinned.txt' ]
level = logging . DEBUG if args . debug else logging . INFO
logging . basicConfig ( level = level , format = '[%(levelname)s] %(message)s' )
try :
    bumper = BumperDriver ( targets , full_throttle = args . force , detail = args . detail , test_drive = args . dry_run )
    bumper . bump ( args . names , required = args . add , show_detail = args . detail )
except Exception as e :
    if args . debug :
        raise
    else :
        log . error ( e )
        sys . exit ( 1 )


signature:
def bump ( self , filter_requirements , required = False , show_summary = True , show_detail = False , ** kwargs ) :
    """Bump dependency requirements using filter .
 : param list filter _ requirements : List of dependency filter requirements .
 : param bool required : Require the filter _ requirements to be met ( by adding if possible ) .
 : param bool show _ summary : Show summary for each bump made .
 : param bool show _ detail : Show detail for each bump made if available .
 : return : Tuple with two elements : Dict of target file to bump message , List of : class : ` Bump `
 : raise BumpAccident : for any bump errors"""

implementation:
found_targets = [ target for target in self . targets if os . path . exists ( target ) ]
if not found_targets :
    raise BumpAccident ( 'None of the requirement file(s) were found: %s' % ', ' . join ( self . targets ) )
bump_reqs = RequirementsManager ( )
if filter_requirements :
    requirements = parse_requirements ( filter_requirements )
    bump_reqs . add ( requirements , required = required )
try :
    for target in found_targets :
        log . debug ( 'Target: %s' , target )
        target_bumpers = [ ]
        target_bump_reqs = RequirementsManager ( bump_reqs )
        loops = 0
        while True : # Insurance to ensure that we don ' t get stuck forever .
            loops += 1
            if loops > 5 :
                log . debug ( 'Too many transitive bump loops. Bailing out.' )
                break
            if not target_bumpers :
                target_bumpers = [ model ( target , detail = self . detail , test_drive = self . test_drive ) for model in self . bumper_models if model . likes ( target ) ]
                if not target_bumpers :
                    log . debug ( 'No bumpers found that can bump %s. Defaulting to %s' , target , self . default_model )
                    target_bumpers = [ self . default_model ( target , detail = self . detail , test_drive = self . test_drive ) ]
                self . bumpers . extend ( target_bumpers )
            new_target_bump_reqs = RequirementsManager ( )
            for bumper in target_bumpers :
                target_bumps = bumper . bump ( target_bump_reqs )
                self . bumps . update ( dict ( ( b . name , b ) for b in target_bumps ) )
                for bump in target_bumps :
                    for new_req in bump . requirements :
                        if not ( bump_reqs . satisfied_by_checked ( new_req ) or target_bump_reqs . satisfied_by_checked ( new_req ) ) :
                            new_target_bump_reqs . add ( new_req )
            bump_reqs . matched_name |= target_bump_reqs . matched_name
            bump_reqs . checked . extend ( target_bump_reqs . checked )
            if new_target_bump_reqs :
                bump_reqs . add ( new_target_bump_reqs )
            target_bump_reqs = RequirementsManager ( list ( r for r in new_target_bump_reqs if r . project_name not in self . bumps ) )
            if not target_bump_reqs :
                break
    if not self . bumpers :
        raise BumpAccident ( 'No bumpers found for %s' % ', ' . join ( found_targets ) )
    if bump_reqs and not bump_reqs . matched_name :
        raise BumpAccident ( 'None of the provided filter names were found in %s' % ', ' . join ( found_targets ) )
    if self . bumps :
        for bump in self . bumps . values ( ) :
            bump_reqs . check ( bump )
        for reqs in bump_reqs . required_requirements ( ) . values ( ) :
            for req in reqs :
                if not self . full_throttle :
                    use_force = 'Use --force to ignore / force the bump' if req . required_by else ''
                    raise BumpAccident ( 'Requirement "%s" could not be met so ' 'bump can not proceed. %s' % ( req , use_force ) )
        if self . test_drive :
            log . info ( "Changes that would be made:\n" )
        messages = { }
        for bumper in self . bumpers :
            if bumper . bumps :
                if not self . test_drive :
                    bumper . update_requirements ( )
                if self . test_drive or show_summary :
                    msg = bumper . bump_message ( self . test_drive or show_detail )
                    if self . test_drive :
                        print ( msg )
                    else :
                        rewords = [ ( 'Bump ' , 'Bumped ' ) , ( 'Pin ' , 'Pinned ' ) , ( 'Require ' , 'Updated requirements: ' ) ]
                        for word , new_word in rewords :
                            if msg . startswith ( word ) :
                                msg = msg . replace ( word , new_word , 1 )
                                break
                        log . info ( msg )
                messages [ bumper . target ] = bumper . bump_message ( True )
        return messages , self . bumps
    else :
        log . info ( 'No need to bump. Everything is up to date!' )
        return { } , [ ]
except Exception :
    if not self . test_drive and self . bumps :
        map ( lambda b : b . reverse ( ) , self . bumpers )
    raise


signature:
def reverse ( self ) :
    """Reverse all bumpers"""

implementation:
if not self . test_drive and self . bumps :
    map ( lambda b : b . reverse ( ) , self . bumpers )


signature:
def _expand_targets ( self , targets , base_dir = None ) :
    """Expand targets by looking for ' - r ' in targets ."""

implementation:
all_targets = [ ]
for target in targets :
    target_dirs = [ p for p in [ base_dir , os . path . dirname ( target ) ] if p ]
    target_dir = target_dirs and os . path . join ( * target_dirs ) or ''
    target = os . path . basename ( target )
    target_path = os . path . join ( target_dir , target )
    if os . path . exists ( target_path ) :
        all_targets . append ( target_path )
        with open ( target_path ) as fp :
            for line in fp :
                if line . startswith ( '-r ' ) :
                    _ , new_target = line . split ( ' ' , 1 )
                    all_targets . extend ( self . _expand_targets ( [ new_target . strip ( ) ] , base_dir = target_dir ) )
return all_targets


signature:
def get_nginx_config ( self ) :
    """Gets the Nginx config for the project"""

implementation:
if os . path . exists ( self . _nginx_config ) :
    return open ( self . _nginx_config , 'r' ) . read ( )
else :
    return None