idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
61,100
def decodepackbits ( encoded ) : func = ord if sys . version [ 0 ] == '2' else lambda x : x result = [ ] i = 0 try : while True : n = func ( encoded [ i ] ) + 1 i += 1 if n < 129 : result . extend ( encoded [ i : i + n ] ) i += n elif n > 129 : result . extend ( encoded [ i : i + 1 ] * ( 258 - n ) ) i += 1 except IndexError : pass return b'' . join ( result ) if sys . version [ 0 ] == '2' else bytes ( result )
Decompress PackBits encoded byte string .
61,101
def unpackints ( data , dtype , itemsize , runlen = 0 ) : if itemsize == 1 : data = numpy . fromstring ( data , '|B' ) data = numpy . unpackbits ( data ) if runlen % 8 : data = data . reshape ( - 1 , runlen + ( 8 - runlen % 8 ) ) data = data [ : , : runlen ] . reshape ( - 1 ) return data . astype ( dtype ) dtype = numpy . dtype ( dtype ) if itemsize in ( 8 , 16 , 32 , 64 ) : return numpy . fromstring ( data , dtype ) if itemsize < 1 or itemsize > 32 : raise ValueError ( "itemsize out of range: %i" % itemsize ) if dtype . kind not in "biu" : raise ValueError ( "invalid dtype" ) itembytes = next ( i for i in ( 1 , 2 , 4 , 8 ) if 8 * i >= itemsize ) if itembytes != dtype . itemsize : raise ValueError ( "dtype.itemsize too small" ) if runlen == 0 : runlen = len ( data ) // itembytes skipbits = runlen * itemsize % 8 if skipbits : skipbits = 8 - skipbits shrbits = itembytes * 8 - itemsize bitmask = int ( itemsize * '1' + '0' * shrbits , 2 ) dtypestr = '>' + dtype . char unpack = struct . unpack l = runlen * ( len ( data ) * 8 // ( runlen * itemsize + skipbits ) ) result = numpy . empty ( ( l , ) , dtype ) bitcount = 0 for i in range ( len ( result ) ) : start = bitcount // 8 s = data [ start : start + itembytes ] try : code = unpack ( dtypestr , s ) [ 0 ] except Exception : code = unpack ( dtypestr , s + b'\x00' * ( itembytes - len ( s ) ) ) [ 0 ] code = code << ( bitcount % 8 ) code = code & bitmask result [ i ] = code >> shrbits bitcount += itemsize if ( i + 1 ) % runlen == 0 : bitcount += skipbits return result
Decompress byte string to array of integers of any bit size < = 32 .
61,102
def stripnull ( string ) : i = string . find ( b'\x00' ) return string if ( i < 0 ) else string [ : i ]
Return string truncated at first null character .
61,103
def _fromfile ( self ) : self . _fd . seek ( 0 ) try : self . byte_order = { b'II' : '<' , b'MM' : '>' } [ self . _fd . read ( 2 ) ] except KeyError : raise ValueError ( "not a valid TIFF file" ) version = struct . unpack ( self . byte_order + 'H' , self . _fd . read ( 2 ) ) [ 0 ] if version == 43 : self . offset_size , zero = struct . unpack ( self . byte_order + 'HH' , self . _fd . read ( 4 ) ) if zero or self . offset_size != 8 : raise ValueError ( "not a valid BigTIFF file" ) elif version == 42 : self . offset_size = 4 else : raise ValueError ( "not a TIFF file" ) self . pages = [ ] while True : try : page = TIFFpage ( self ) self . pages . append ( page ) except StopIteration : break if not self . pages : raise ValueError ( "empty TIFF file" )
Read TIFF header and all page records from file .
61,104
def asarray ( self , key = None , series = None ) : if key is None and series is None : series = 0 if series is not None : pages = self . series [ series ] . pages else : pages = self . pages if key is None : pass elif isinstance ( key , int ) : pages = [ pages [ key ] ] elif isinstance ( key , slice ) : pages = pages [ key ] elif isinstance ( key , collections . Iterable ) : pages = [ pages [ k ] for k in key ] else : raise TypeError ( 'key must be an int, slice, or sequence' ) if len ( pages ) == 1 : return pages [ 0 ] . asarray ( ) elif self . is_nih : result = numpy . vstack ( p . asarray ( colormapped = False , squeeze = False ) for p in pages ) if pages [ 0 ] . is_palette : result = numpy . take ( pages [ 0 ] . color_map , result , axis = 1 ) result = numpy . swapaxes ( result , 0 , 1 ) else : if self . is_ome and any ( p is None for p in pages ) : firstpage = next ( p for p in pages if p ) nopage = numpy . zeros_like ( firstpage . asarray ( ) ) result = numpy . vstack ( ( p . asarray ( ) if p else nopage ) for p in pages ) if key is None : try : result . shape = self . series [ series ] . shape except ValueError : warnings . warn ( "failed to reshape %s to %s" % ( result . shape , self . series [ series ] . shape ) ) result . shape = ( - 1 , ) + pages [ 0 ] . shape else : result . shape = ( - 1 , ) + pages [ 0 ] . shape return result
Return image data of multiple TIFF pages as numpy array .
61,105
def _fromfile ( self ) : fd = self . parent . _fd byte_order = self . parent . byte_order offset_size = self . parent . offset_size fmt = { 4 : 'I' , 8 : 'Q' } [ offset_size ] offset = struct . unpack ( byte_order + fmt , fd . read ( offset_size ) ) [ 0 ] if not offset : raise StopIteration ( ) tags = self . tags fd . seek ( offset ) fmt , size = { 4 : ( 'H' , 2 ) , 8 : ( 'Q' , 8 ) } [ offset_size ] try : numtags = struct . unpack ( byte_order + fmt , fd . read ( size ) ) [ 0 ] except Exception : warnings . warn ( "corrupted page list" ) raise StopIteration ( ) for _ in range ( numtags ) : tag = TIFFtag ( self . parent ) tags [ tag . name ] = tag if self . is_lsm : pos = fd . tell ( ) for name , reader in CZ_LSM_INFO_READERS . items ( ) : try : offset = self . cz_lsm_info [ "offset_" + name ] except KeyError : continue if not offset : continue fd . seek ( offset ) try : setattr ( self , "cz_lsm_" + name , reader ( fd , byte_order ) ) except ValueError : pass fd . seek ( pos )
Read TIFF IFD structure and its tags from file .
61,106
def _fromdata ( self , code , dtype , count , value , name = None ) : self . code = int ( code ) self . name = name if name else str ( code ) self . dtype = TIFF_DATA_TYPES [ dtype ] self . count = int ( count ) self . value = value
Initialize instance from arguments .
61,107
def _fromfile ( self , parent ) : fd = parent . _fd byte_order = parent . byte_order self . _offset = fd . tell ( ) self . value_offset = self . _offset + parent . offset_size + 4 fmt , size = { 4 : ( 'HHI4s' , 12 ) , 8 : ( 'HHQ8s' , 20 ) } [ parent . offset_size ] data = fd . read ( size ) code , dtype = struct . unpack ( byte_order + fmt [ : 2 ] , data [ : 4 ] ) count , value = struct . unpack ( byte_order + fmt [ 2 : ] , data [ 4 : ] ) if code in TIFF_TAGS : name = TIFF_TAGS [ code ] [ 0 ] elif code in CUSTOM_TAGS : name = CUSTOM_TAGS [ code ] [ 0 ] else : name = str ( code ) try : dtype = TIFF_DATA_TYPES [ dtype ] except KeyError : raise ValueError ( "unknown TIFF tag data type %i" % dtype ) fmt = '%s%i%s' % ( byte_order , count * int ( dtype [ 0 ] ) , dtype [ 1 ] ) size = struct . calcsize ( fmt ) if size > parent . offset_size or code in CUSTOM_TAGS : pos = fd . tell ( ) tof = { 4 : 'I' , 8 : 'Q' } [ parent . offset_size ] self . value_offset = struct . unpack ( byte_order + tof , value ) [ 0 ] fd . seek ( self . value_offset ) if code in CUSTOM_TAGS : readfunc = CUSTOM_TAGS [ code ] [ 1 ] value = readfunc ( fd , byte_order , dtype , count ) fd . seek ( 0 , 2 ) if isinstance ( value , dict ) : value = Record ( value ) elif code in TIFF_TAGS or dtype [ - 1 ] == 's' : value = struct . unpack ( fmt , fd . read ( size ) ) else : value = read_numpy ( fd , byte_order , dtype , count ) fd . seek ( 0 , 2 ) fd . seek ( pos ) else : value = struct . unpack ( fmt , value [ : size ] ) if not code in CUSTOM_TAGS : if len ( value ) == 1 : value = value [ 0 ] if dtype . endswith ( 's' ) : value = stripnull ( value ) self . code = code self . name = name self . dtype = dtype self . count = count self . value = value
Read tag structure from open file . Advance file cursor .
61,108
def set_xylims ( self , lims , axes = None , panel = 'top' , ** kws ) : panel = self . get_panel ( panel ) panel . set_xylims ( lims , axes = axes , ** kws )
set xy limits
61,109
def onThemeColor ( self , color , item ) : bconf = self . panel_bot . conf if item == 'grid' : bconf . set_gridcolor ( color ) elif item == 'bg' : bconf . set_bgcolor ( color ) elif item == 'frame' : bconf . set_framecolor ( color ) elif item == 'text' : bconf . set_textcolor ( color ) bconf . canvas . draw ( )
pass theme colors to bottom panel
61,110
def add_entry_points ( self , names ) : names = util . return_set ( names ) self . entry_point_names . update ( names )
adds names to the internal collection of entry points to track
61,111
def set_entry_points ( self , names ) : names = util . return_set ( names ) self . entry_point_names = names
sets the internal collection of entry points to be equal to names
61,112
def remove_entry_points ( self , names ) : names = util . return_set ( names ) util . remove_from_set ( self . entry_point_names , names )
removes names from the set of entry points to track .
61,113
def to_absolute_paths ( paths ) : abspath = os . path . abspath paths = return_set ( paths ) absolute_paths = { abspath ( x ) for x in paths } return absolute_paths
helper method to change paths to absolute paths . Returns a set object paths can be either a single object or iterable
61,114
def update ( self , line = None ) : if line : markercolor = self . markercolor if markercolor is None : markercolor = self . color self . set_label ( self . label , line = line ) self . set_color ( self . color , line = line ) self . set_style ( self . style , line = line ) self . set_drawstyle ( self . drawstyle , line = line ) self . set_marker ( self . marker , line = line ) self . set_markersize ( self . markersize , line = line ) self . set_linewidth ( self . linewidth , line = line )
set a matplotlib Line2D to have the current properties
61,115
def _init_trace ( self , n , color , style , linewidth = 2.5 , zorder = None , marker = None , markersize = 6 ) : while n >= len ( self . traces ) : self . traces . append ( LineProperties ( ) ) line = self . traces [ n ] label = "trace %i" % ( n + 1 ) line . label = label line . drawstyle = 'default' if zorder is None : zorder = 5 * ( n + 1 ) line . zorder = zorder if color is not None : line . color = color if style is not None : line . style = style if linewidth is not None : line . linewidth = linewidth if marker is not None : line . marker = marker if markersize is not None : line . markersize = markersize self . traces [ n ] = line
used for building set of traces
61,116
def set_gridcolor ( self , color ) : self . gridcolor = color for ax in self . canvas . figure . get_axes ( ) : for i in ax . get_xgridlines ( ) + ax . get_ygridlines ( ) : i . set_color ( color ) i . set_zorder ( - 1 ) if callable ( self . theme_color_callback ) : self . theme_color_callback ( color , 'grid' )
set color for grid
61,117
def set_bgcolor ( self , color ) : self . bgcolor = color for ax in self . canvas . figure . get_axes ( ) : if matplotlib . __version__ < '2.0' : ax . set_axis_bgcolor ( color ) else : ax . set_facecolor ( color ) if callable ( self . theme_color_callback ) : self . theme_color_callback ( color , 'bg' )
set color for background of plot
61,118
def set_framecolor ( self , color ) : self . framecolor = color self . canvas . figure . set_facecolor ( color ) if callable ( self . theme_color_callback ) : self . theme_color_callback ( color , 'frame' )
set color for outer frame
61,119
def set_textcolor ( self , color ) : self . textcolor = color self . relabel ( ) if callable ( self . theme_color_callback ) : self . theme_color_callback ( color , 'text' )
set color for labels and axis text
61,120
def draw_legend ( self , show = None , auto_location = True , delay_draw = False ) : "redraw the legend" if show is not None : self . show_legend = show axes = self . canvas . figure . get_axes ( ) try : lgn = self . mpl_legend if lgn : for i in lgn . get_texts ( ) : i . set_text ( '' ) for i in lgn . get_lines ( ) : i . set_linewidth ( 0 ) i . set_markersize ( 0 ) i . set_marker ( 'None' ) lgn . draw_frame ( False ) lgn . set_visible ( False ) except : pass labs = [ ] lins = [ ] for ax in axes : for xline in ax . get_lines ( ) : xlab = xline . get_label ( ) if ( xlab != '_nolegend_' and len ( xlab ) > 0 ) : lins . append ( xline ) for l in lins : xl = l . get_label ( ) if not self . show_legend : xl = '' labs . append ( xl ) labs = tuple ( labs ) lgn = axes [ 0 ] . legend if self . legend_onaxis . startswith ( 'off' ) : lgn = self . canvas . figure . legend if self . legend_loc == 'best' : self . legend_loc = 'upper right' if self . show_legend : self . mpl_legend = lgn ( lins , labs , prop = self . legendfont , loc = self . legend_loc ) self . mpl_legend . draw_frame ( self . show_legend_frame ) if matplotlib . __version__ < '2.0' : facecol = axes [ 0 ] . get_axis_bgcolor ( ) else : facecol = axes [ 0 ] . get_facecolor ( ) self . mpl_legend . legendPatch . set_facecolor ( facecol ) if self . draggable_legend : self . mpl_legend . draggable ( True , update = 'loc' ) self . legend_map = { } for legline , legtext , mainline in zip ( self . mpl_legend . get_lines ( ) , self . mpl_legend . get_texts ( ) , lins ) : legline . set_picker ( 5 ) legtext . set_picker ( 5 ) self . legend_map [ legline ] = ( mainline , legline , legtext ) self . legend_map [ legtext ] = ( mainline , legline , legtext ) legtext . set_color ( self . textcolor ) self . set_added_text_size ( ) if not delay_draw : self . canvas . draw ( )
redraw the legend
61,121
def set_legend_location ( self , loc , onaxis ) : "set legend location" self . legend_onaxis = 'on plot' if not onaxis : self . legend_onaxis = 'off plot' if loc == 'best' : loc = 'upper right' if loc in self . legend_abbrevs : loc = self . legend_abbrevs [ loc ] if loc in self . legend_locs : self . legend_loc = loc
set legend location
61,122
def unzoom ( self , full = False , delay_draw = False ) : if full : self . zoom_lims = self . zoom_lims [ : 1 ] self . zoom_lims = [ ] elif len ( self . zoom_lims ) > 0 : self . zoom_lims . pop ( ) self . set_viewlimits ( ) if not delay_draw : self . canvas . draw ( )
unzoom display 1 level or all the way
61,123
def add_text ( self , text , x , y , ** kws ) : self . panel . add_text ( text , x , y , ** kws )
add text to plot
61,124
def add_arrow ( self , x1 , y1 , x2 , y2 , ** kws ) : self . panel . add_arrow ( x1 , y1 , x2 , y2 , ** kws )
add arrow to plot
61,125
def ExportTextFile ( self , fname , title = 'unknown plot' ) : "save plot data to external file" buff = [ "# Plot Data for %s" % title , "#---------------------------------" ] out = [ ] labels = [ ] itrace = 0 for ax in self . panel . fig . get_axes ( ) : for line in ax . lines : itrace += 1 x = line . get_xdata ( ) y = line . get_ydata ( ) ylab = line . get_label ( ) if len ( ylab ) < 1 : ylab = 'Y%i' % itrace for c in ' .:";|/\\(){}[]\'&^%*$+=-?!@#' : ylab = ylab . replace ( c , '_' ) xlab = ( ' X%d' % itrace + ' ' * 3 ) [ : 4 ] ylab = ' ' * ( 18 - len ( ylab ) ) + ylab + ' ' out . extend ( [ x , y ] ) labels . extend ( [ xlab , ylab ] ) if itrace == 0 : return buff . append ( '# %s' % ( ' ' . join ( labels ) ) ) npts = [ len ( a ) for a in out ] for i in range ( max ( npts ) ) : oline = [ ] for a in out : d = np . nan if i < len ( a ) : d = a [ i ] oline . append ( gformat ( d , 12 ) ) buff . append ( ' ' . join ( oline ) ) buff . append ( '' ) with open ( fname , 'w' ) as fout : fout . write ( "\n" . join ( buff ) ) fout . close ( ) self . write_message ( "Exported data to '%s'" % fname , panel = 0 )
save plot data to external file
61,126
def add_plugin_filepaths ( self , filepaths , except_blacklisted = True ) : self . file_manager . add_plugin_filepaths ( filepaths , except_blacklisted )
Adds filepaths to internal state . Recommend passing in absolute filepaths . Method will attempt to convert to absolute paths if they are not already .
61,127
def set_plugin_filepaths ( self , filepaths , except_blacklisted = True ) : self . file_manager . set_plugin_filepaths ( filepaths , except_blacklisted )
Sets internal state to filepaths . Recommend passing in absolute filepaths . Method will attempt to convert to absolute paths if they are not already .
61,128
def add_blacklisted_filepaths ( self , filepaths , remove_from_stored = True ) : self . file_manager . add_blacklisted_filepaths ( filepaths , remove_from_stored )
Add filepaths to blacklisted filepaths . If remove_from_stored is True any filepaths in internal state will be automatically removed .
61,129
def collect_filepaths ( self , directories ) : plugin_filepaths = set ( ) directories = util . to_absolute_paths ( directories ) for directory in directories : filepaths = util . get_filepaths_from_dir ( directory ) filepaths = self . _filter_filepaths ( filepaths ) plugin_filepaths . update ( set ( filepaths ) ) plugin_filepaths = self . _remove_blacklisted ( plugin_filepaths ) return plugin_filepaths
Collects and returns every filepath from each directory in directories that is filtered through the file_filters . If no file_filters are present passes every file in directory as a result . Always returns a set object
61,130
def add_plugin_filepaths ( self , filepaths , except_blacklisted = True ) : filepaths = util . to_absolute_paths ( filepaths ) if except_blacklisted : filepaths = util . remove_from_set ( filepaths , self . blacklisted_filepaths ) self . plugin_filepaths . update ( filepaths )
Adds filepaths to the self . plugin_filepaths . Recommend passing in absolute filepaths . Method will attempt to convert to absolute paths if they are not already .
61,131
def set_plugin_filepaths ( self , filepaths , except_blacklisted = True ) : filepaths = util . to_absolute_paths ( filepaths ) if except_blacklisted : filepaths = util . remove_from_set ( filepaths , self . blacklisted_filepaths ) self . plugin_filepaths = filepaths
Sets filepaths to the self . plugin_filepaths . Recommend passing in absolute filepaths . Method will attempt to convert to absolute paths if they are not already .
61,132
def remove_plugin_filepaths ( self , filepaths ) : filepaths = util . to_absolute_paths ( filepaths ) self . plugin_filepaths = util . remove_from_set ( self . plugin_filepaths , filepaths )
Removes filepaths from self . plugin_filepaths . Recommend passing in absolute filepaths . Method will attempt to convert to absolute paths if not passed in .
61,133
def set_file_filters ( self , file_filters ) : file_filters = util . return_list ( file_filters ) self . file_filters = file_filters
Sets internal file filters to file_filters by tossing old state . file_filters can be single object or iterable .
61,134
def add_file_filters ( self , file_filters ) : file_filters = util . return_list ( file_filters ) self . file_filters . extend ( file_filters )
Adds file_filters to the internal file filters . file_filters can be single object or iterable .
61,135
def remove_file_filters ( self , file_filters ) : self . file_filters = util . remove_from_list ( self . file_filters , file_filters )
Removes the file_filters from the internal state . file_filters can be a single object or an iterable .
61,136
def add_blacklisted_filepaths ( self , filepaths , remove_from_stored = True ) : filepaths = util . to_absolute_paths ( filepaths ) self . blacklisted_filepaths . update ( filepaths ) if remove_from_stored : self . plugin_filepaths = util . remove_from_set ( self . plugin_filepaths , filepaths )
Add filepaths to blacklisted filepaths . If remove_from_stored is True any filepaths in plugin_filepaths will be automatically removed .
61,137
def set_blacklisted_filepaths ( self , filepaths , remove_from_stored = True ) : filepaths = util . to_absolute_paths ( filepaths ) self . blacklisted_filepaths = filepaths if remove_from_stored : self . plugin_filepaths = util . remove_from_set ( self . plugin_filepaths , filepaths )
Sets internal blacklisted filepaths to filepaths . If remove_from_stored is True any filepaths in self . plugin_filepaths will be automatically removed .
61,138
def remove_blacklisted_filepaths ( self , filepaths ) : filepaths = util . to_absolute_paths ( filepaths ) black_paths = self . blacklisted_filepaths black_paths = util . remove_from_set ( black_paths , filepaths )
Removes filepaths from blacklisted filepaths
61,139
def _remove_blacklisted ( self , filepaths ) : filepaths = util . remove_from_set ( filepaths , self . blacklisted_filepaths ) return filepaths
internal helper method to remove the blacklisted filepaths from filepaths .
61,140
def _filter_filepaths ( self , filepaths ) : if self . file_filters : plugin_filepaths = set ( ) for file_filter in self . file_filters : plugin_paths = file_filter ( filepaths ) plugin_filepaths . update ( plugin_paths ) else : plugin_filepaths = filepaths return plugin_filepaths
helps iterate through all the file parsers each filter is applied individually to the same set of filepaths
61,141
def rgb ( color , default = ( 0 , 0 , 0 ) ) : c = color . lower ( ) if c [ 0 : 1 ] == '#' and len ( c ) == 7 : r , g , b = c [ 1 : 3 ] , c [ 3 : 5 ] , c [ 5 : ] r , g , b = [ int ( n , 16 ) for n in ( r , g , b ) ] return ( r , g , b ) if c . find ( ' ' ) > - 1 : c = c . replace ( ' ' , '' ) if c . find ( 'gray' ) > - 1 : c = c . replace ( 'gray' , 'grey' ) if c in x11_colors . keys ( ) : return x11_colors [ c ] return default
return rgb tuple for named color in rgb . txt or a hex color
61,142
def hexcolor ( color ) : " returns hex color given a tuple, wx.Color, or X11 named color" if isinstance ( color , six . string_types ) : if color [ 0 ] == '#' and len ( color ) == 7 : return color . lower ( ) rgb = ( 0 , 0 , 0 ) if isinstance ( color , tuple ) : rgb = color elif isinstance ( color , list ) : rgb = tuple ( color ) elif isinstance ( color , six . string_types ) : c = color . lower ( ) if c . find ( ' ' ) > - 1 : c = c . replace ( ' ' , '' ) if c . find ( 'gray' ) > - 1 : c = c . replace ( 'gray' , 'grey' ) if c in x11_colors : rgb = x11_colors [ c ] else : try : rgb = color . Red ( ) , color . Green ( ) , color . Blue ( ) except : pass col = '#%02x%02x%02x' % ( rgb ) return col . lower ( )
returns hex color given a tuple wx . Color or X11 named color
61,143
def register_custom_colormaps ( ) : if not HAS_MPL : return ( ) makemap = LinearSegmentedColormap . from_list for name , val in custom_colormap_data . items ( ) : cm1 = np . array ( val ) . transpose ( ) . astype ( 'f8' ) / 256.0 cm2 = cm1 [ : : - 1 ] nam1 = name nam2 = '%s_r' % name register_cmap ( name = nam1 , cmap = makemap ( nam1 , cm1 , 256 ) , lut = 256 ) register_cmap ( name = nam2 , cmap = makemap ( nam2 , cm2 , 256 ) , lut = 256 ) return ( 'stdgamma' , 'red' , 'green' , 'blue' , 'red_heat' , 'green_heat' , 'blue_heat' , 'magenta' , 'yellow' , 'cyan' )
registers custom color maps
61,144
def onCMapSave ( self , event = None , col = 'int' ) : file_choices = 'PNG (*.png)|*.png' ofile = 'Colormap.png' dlg = wx . FileDialog ( self , message = 'Save Colormap as...' , defaultDir = os . getcwd ( ) , defaultFile = ofile , wildcard = file_choices , style = wx . FD_SAVE | wx . FD_CHANGE_DIR ) if dlg . ShowModal ( ) == wx . ID_OK : self . cmap_panels [ 0 ] . cmap_canvas . print_figure ( dlg . GetPath ( ) , dpi = 600 )
save color table image
61,145
def plugin_valid ( self , filename ) : filename = os . path . basename ( filename ) for regex in self . regex_expressions : if regex . match ( filename ) : return True return False
Checks if the given filename is a valid plugin for this Strategy
61,146
def get_message ( self , message_id ) : r = requests . get ( 'https://outlook.office.com/api/v2.0/me/messages/' + message_id , headers = self . _headers ) check_response ( r ) return Message . _json_to_message ( self , r . json ( ) )
Gets message matching provided id .
61,147
def get_messages ( self , page = 0 ) : endpoint = 'https://outlook.office.com/api/v2.0/me/messages' if page > 0 : endpoint = endpoint + '/?%24skip=' + str ( page ) + '0' log . debug ( 'Getting messages from endpoint: {} with Headers: {}' . format ( endpoint , self . _headers ) ) r = requests . get ( endpoint , headers = self . _headers ) check_response ( r ) return Message . _json_to_messages ( self , r . json ( ) )
Get first 10 messages in account across all folders .
61,148
def get_folders ( self ) : endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' r = requests . get ( endpoint , headers = self . _headers ) if check_response ( r ) : return Folder . _json_to_folders ( self , r . json ( ) )
Returns a list of all folders for this account
61,149
def get_folder_by_id ( self , folder_id ) : endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + folder_id r = requests . get ( endpoint , headers = self . _headers ) check_response ( r ) return_folder = r . json ( ) return Folder . _json_to_folder ( self , return_folder )
Retrieve a Folder by its Outlook ID
61,150
def _get_messages_from_folder_name ( self , folder_name ) : r = requests . get ( 'https://outlook.office.com/api/v2.0/me/MailFolders/' + folder_name + '/messages' , headers = self . _headers ) check_response ( r ) return Message . _json_to_messages ( self , r . json ( ) )
Retrieves all messages from a folder specified by its name . This only works with Well Known folders such as Inbox or Drafts .
61,151
def api_representation ( self , content_type ) : payload = dict ( Subject = self . subject , Body = dict ( ContentType = content_type , Content = self . body ) ) if self . sender is not None : payload . update ( From = self . sender . api_representation ( ) ) if any ( isinstance ( item , str ) for item in self . to ) : self . to = [ Contact ( email = email ) for email in self . to ] recipients = [ contact . api_representation ( ) for contact in self . to ] payload . update ( ToRecipients = recipients ) if self . cc : if any ( isinstance ( email , str ) for email in self . cc ) : self . cc = [ Contact ( email ) for email in self . cc ] cc_recipients = [ contact . api_representation ( ) for contact in self . cc ] payload . update ( CcRecipients = cc_recipients ) if self . bcc : if any ( isinstance ( email , str ) for email in self . bcc ) : self . bcc = [ Contact ( email ) for email in self . bcc ] bcc_recipients = [ contact . api_representation ( ) for contact in self . bcc ] payload . update ( BccRecipients = bcc_recipients ) if self . _attachments : payload . update ( Attachments = [ attachment . api_representation ( ) for attachment in self . _attachments ] ) payload . update ( Importance = str ( self . importance ) ) return dict ( Message = payload )
Returns the JSON representation of this message required for making requests to the API .
61,152
def send ( self , content_type = 'HTML' ) : payload = self . api_representation ( content_type ) endpoint = 'https://outlook.office.com/api/v1.0/me/sendmail' self . _make_api_call ( 'post' , endpoint = endpoint , data = json . dumps ( payload ) )
Takes the recipients body and attachments of the Message and sends .
61,153
def forward ( self , to_recipients , forward_comment = None ) : payload = dict ( ) if forward_comment is not None : payload . update ( Comment = forward_comment ) if any ( isinstance ( recipient , str ) for recipient in to_recipients ) : to_recipients = [ Contact ( email = email ) for email in to_recipients ] to_recipients = [ contact . api_representation ( ) for contact in to_recipients ] payload . update ( ToRecipients = to_recipients ) endpoint = 'https://outlook.office.com/api/v2.0/me/messages/{}/forward' . format ( self . message_id ) self . _make_api_call ( 'post' , endpoint = endpoint , data = json . dumps ( payload ) )
Forward Message to recipients with an optional comment .
61,154
def reply ( self , reply_comment ) : payload = '{ "Comment": "' + reply_comment + '"}' endpoint = 'https://outlook.office.com/api/v2.0/me/messages/' + self . message_id + '/reply' self . _make_api_call ( 'post' , endpoint , data = payload )
Reply to the Message .
61,155
def reply_all ( self , reply_comment ) : payload = '{ "Comment": "' + reply_comment + '"}' endpoint = 'https://outlook.office.com/api/v2.0/me/messages/{}/replyall' . format ( self . message_id ) self . _make_api_call ( 'post' , endpoint , data = payload )
Replies to everyone on the email including those on the CC line .
61,156
def move_to ( self , folder ) : if isinstance ( folder , Folder ) : self . move_to ( folder . id ) else : self . _move_to ( folder )
Moves the email to the folder specified by the folder parameter .
61,157
def rgb2cmy ( self , img , whitebg = False ) : tmp = img * 1.0 if whitebg : tmp = ( 1.0 - ( img - img . min ( ) ) / ( img . max ( ) - img . min ( ) ) ) out = tmp * 0.0 out [ : , : , 0 ] = ( tmp [ : , : , 1 ] + tmp [ : , : , 2 ] ) / 2.0 out [ : , : , 1 ] = ( tmp [ : , : , 0 ] + tmp [ : , : , 2 ] ) / 2.0 out [ : , : , 2 ] = ( tmp [ : , : , 0 ] + tmp [ : , : , 1 ] ) / 2.0 return out
transforms image from RGB to CMY
61,158
def plugin_valid ( self , filepath ) : plugin_valid = False for extension in self . extensions : if filepath . endswith ( ".{}" . format ( extension ) ) : plugin_valid = True break return plugin_valid
checks to see if plugin ends with one of the approved extensions
61,159
def api_representation ( self ) : return dict ( EmailAddress = dict ( Name = self . name , Address = self . email ) )
Returns the JSON formatting required by Outlook s API for contacts
61,160
def set_focused ( self , account , is_focused ) : endpoint = 'https://outlook.office.com/api/v2.0/me/InferenceClassification/Overrides' if is_focused : classification = 'Focused' else : classification = 'Other' data = dict ( ClassifyAs = classification , SenderEmailAddress = dict ( Address = self . email ) ) r = requests . post ( endpoint , headers = account . _headers , data = json . dumps ( data ) ) result = check_response ( r ) self . focused = is_focused return result
Emails from this contact will either always be put in the Focused inbox or always put in Other based on the value of is_focused .
61,161
def image2wxbitmap ( img ) : "PIL image 2 wx bitmap" if is_wxPhoenix : wximg = wx . Image ( * img . size ) else : wximg = wx . EmptyImage ( * img . size ) wximg . SetData ( img . tobytes ( ) ) return wximg . ConvertToBitmap ( )
PIL image 2 wx bitmap
61,162
def check_response ( response ) : status_code = response . status_code if 100 < status_code < 299 : return True elif status_code == 401 or status_code == 403 : message = get_response_data ( response ) raise AuthError ( 'Access Token Error, Received ' + str ( status_code ) + ' from Outlook REST Endpoint with the message: {}' . format ( message ) ) elif status_code == 400 : message = get_response_data ( response ) raise RequestError ( 'The request made to the Outlook API was invalid. Received the following message: {}' . format ( message ) ) else : message = get_response_data ( response ) raise APIError ( 'Encountered an unknown error from the Outlook API: {}' . format ( message ) )
Checks that a response is successful raising the appropriate Exceptions otherwise .
61,163
def get_plugins ( self , filter_function = None ) : plugins = self . plugins if filter_function is not None : plugins = filter_function ( plugins ) return plugins
Gets out the plugins from the internal state . Returns a list object . If the optional filter_function is supplied applies the filter function to the arguments before returning them . Filters should be callable and take a list argument of plugins .
61,164
def _get_instance ( self , klasses ) : return [ x for x in self . plugins if isinstance ( x , klasses ) ]
internal method that gets every instance of the klasses out of the internal plugin state .
61,165
def get_instances ( self , filter_function = IPlugin ) : if isinstance ( filter_function , ( list , tuple ) ) : return self . _get_instance ( filter_function ) elif inspect . isclass ( filter_function ) : return self . _get_instance ( filter_function ) elif filter_function is None : return self . plugins else : return filter_function ( self . plugins )
Gets instances out of the internal state using the default filter supplied in filter_function . By default it is the class IPlugin .
61,166
def register_classes ( self , classes ) : classes = util . return_list ( classes ) for klass in classes : IPlugin . register ( klass )
Register classes as plugins that are not subclassed from IPlugin . classes may be a single object or an iterable .
61,167
def _instance_parser ( self , plugins ) : plugins = util . return_list ( plugins ) for instance in plugins : if inspect . isclass ( instance ) : self . _handle_class_instance ( instance ) else : self . _handle_object_instance ( instance )
internal method to parse instances of plugins .
61,168
def _handle_class_instance ( self , klass ) : if ( klass in self . blacklisted_plugins or not self . instantiate_classes or klass == IPlugin ) : return elif self . unique_instances and self . _unique_class ( klass ) : self . plugins . append ( klass ( ) ) elif not self . unique_instances : self . plugins . append ( klass ( ) )
handles class instances . If a class is blacklisted returns . If uniuqe_instances is True and the class is unique instantiates the class and adds the new object to plugins .
61,169
def _unique_class ( self , cls ) : return not any ( isinstance ( obj , cls ) for obj in self . plugins )
internal method to check if any of the plugins are instances of a given cls
61,170
def add_blacklisted_plugins ( self , plugins ) : plugins = util . return_list ( plugins ) self . blacklisted_plugins . extend ( plugins )
add blacklisted plugins . plugins may be a single object or iterable .
61,171
def set_blacklisted_plugins ( self , plugins ) : plugins = util . return_list ( plugins ) self . blacklisted_plugins = plugins
sets blacklisted plugins . plugins may be a single object or iterable .
61,172
def collect_plugins ( self , modules = None ) : if modules is None : modules = self . get_loaded_modules ( ) else : modules = util . return_list ( modules ) plugins = [ ] for module in modules : module_plugins = [ ( item [ 1 ] , item [ 0 ] ) for item in inspect . getmembers ( module ) if item [ 1 ] and item [ 0 ] != '__builtins__' ] module_plugins , names = zip ( * module_plugins ) module_plugins = self . _filter_modules ( module_plugins , names ) plugins . extend ( module_plugins ) return plugins
Collects all the plugins from modules . If modules is None collects the plugins from the loaded modules .
61,173
def set_module_plugin_filters ( self , module_plugin_filters ) : module_plugin_filters = util . return_list ( module_plugin_filters ) self . module_plugin_filters = module_plugin_filters
Sets the internal module filters to module_plugin_filters module_plugin_filters may be a single object or an iterable .
61,174
def add_module_plugin_filters ( self , module_plugin_filters ) : module_plugin_filters = util . return_list ( module_plugin_filters ) self . module_plugin_filters . extend ( module_plugin_filters )
Adds module_plugin_filters to the internal module filters . May be a single object or an iterable .
61,175
def _get_modules ( self , names ) : loaded_modules = [ ] for name in names : loaded_modules . append ( sys . modules [ name ] ) return loaded_modules
An internal method that gets the names from sys . modules and returns them as a list
61,176
def add_to_loaded_modules ( self , modules ) : modules = util . return_set ( modules ) for module in modules : if not isinstance ( module , str ) : module = module . __name__ self . loaded_modules . add ( module )
Manually add in modules to be tracked by the module manager .
61,177
def _filter_modules ( self , plugins , names ) : if self . module_plugin_filters : original_length_plugins = len ( plugins ) module_plugins = set ( ) for module_filter in self . module_plugin_filters : module_plugins . update ( module_filter ( plugins , names ) ) if len ( plugins ) < original_length_plugins : warning = self . _log . info ( warning . format ( module_filter ) ) plugins = module_plugins return plugins
Internal helper method to parse all of the plugins and names through each of the module filters
61,178
def _clean_filepath ( self , filepath ) : if ( os . path . isdir ( filepath ) and os . path . isfile ( os . path . join ( filepath , '__init__.py' ) ) ) : filepath = os . path . join ( filepath , '__init__.py' ) if ( not filepath . endswith ( '.py' ) and os . path . isfile ( filepath + '.py' ) ) : filepath += '.py' return filepath
processes the filepath by checking if it is a directory or not and adding . py if not present .
61,179
def _processed_filepath ( self , filepath ) : processed = False if filepath in self . processed_filepaths . values ( ) : processed = True return processed
checks to see if the filepath has already been processed
61,180
def _update_loaded_modules ( self ) : system_modules = sys . modules . keys ( ) for module in list ( self . loaded_modules ) : if module not in system_modules : self . processed_filepaths . pop ( module ) self . loaded_modules . remove ( module )
Updates the loaded modules by checking if they are still in sys . modules
61,181
def get_right_axes ( self ) : "create, if needed, and return right-hand y axes" if len ( self . fig . get_axes ( ) ) < 2 : ax = self . axes . twinx ( ) return self . fig . get_axes ( ) [ 1 ]
create if needed and return right - hand y axes
61,182
def onLeftUp ( self , event = None ) : if event is None : return self . cursor_mode_action ( 'leftup' , event = event ) self . canvas . draw_idle ( ) self . canvas . draw ( ) self . ForwardEvent ( event = event . guiEvent )
left button up
61,183
def ForwardEvent ( self , event = None ) : if event is not None : event . Skip ( ) if self . HasCapture ( ) : try : self . ReleaseMouse ( ) except : pass
finish wx event forward it to other wx objects
61,184
def __date_format ( self , x ) : if x < 1 : x = 1 span = self . axes . xaxis . get_view_interval ( ) tmin = max ( 1.0 , span [ 0 ] ) tmax = max ( 2.0 , span [ 1 ] ) tmin = time . mktime ( dates . num2date ( tmin ) . timetuple ( ) ) tmax = time . mktime ( dates . num2date ( tmax ) . timetuple ( ) ) nhours = ( tmax - tmin ) / 3600.0 fmt = "%m/%d" if nhours < 0.1 : fmt = "%H:%M\n%Ssec" elif nhours < 4 : fmt = "%m/%d\n%H:%M" elif nhours < 24 * 8 : fmt = "%m/%d\n%H:%M" try : return time . strftime ( fmt , dates . num2date ( x ) . timetuple ( ) ) except : return "?"
formatter for date x - data . primitive and probably needs improvement following matplotlib s date methods .
61,185
def xformatter ( self , x , pos ) : " x-axis formatter " if self . use_dates : return self . __date_format ( x ) else : return self . __format ( x , type = 'x' )
x - axis formatter
61,186
def __onKeyEvent ( self , event = None ) : if event is None : return key = event . guiEvent . GetKeyCode ( ) if ( key < wx . WXK_SPACE or key > 255 ) : return ckey = chr ( key ) mod = event . guiEvent . ControlDown ( ) if self . is_macosx : mod = event . guiEvent . MetaDown ( ) if mod : if ckey == 'C' : self . canvas . Copy_to_Clipboard ( event ) elif ckey == 'S' : self . save_figure ( event ) elif ckey == 'K' : self . configure ( event ) elif ckey == 'Z' : self . unzoom ( event ) elif ckey == 'P' : self . canvas . printer . Print ( event )
handles key events on canvas
61,187
def zoom_motion ( self , event = None ) : try : x , y = event . x , event . y except : return self . report_motion ( event = event ) if self . zoom_ini is None : return ini_x , ini_y , ini_xd , ini_yd = self . zoom_ini if event . xdata is not None : self . x_lastmove = event . xdata if event . ydata is not None : self . y_lastmove = event . ydata x0 = min ( x , ini_x ) ymax = max ( y , ini_y ) width = abs ( x - ini_x ) height = abs ( y - ini_y ) y0 = self . canvas . figure . bbox . height - ymax zdc = wx . ClientDC ( self . canvas ) zdc . SetLogicalFunction ( wx . XOR ) zdc . SetBrush ( wx . TRANSPARENT_BRUSH ) zdc . SetPen ( wx . Pen ( 'White' , 2 , wx . SOLID ) ) zdc . ResetBoundingBox ( ) if not is_wxPhoenix : zdc . BeginDrawing ( ) if self . rbbox is not None : zdc . DrawRectangle ( * self . rbbox ) self . rbbox = ( x0 , y0 , width , height ) zdc . DrawRectangle ( * self . rbbox ) if not is_wxPhoenix : zdc . EndDrawing ( )
motion event handler for zoom mode
61,188
def zoom_leftdown ( self , event = None ) : self . x_lastmove , self . y_lastmove = None , None self . zoom_ini = ( event . x , event . y , event . xdata , event . ydata ) self . report_leftdown ( event = event )
leftdown event handler for zoom mode
61,189
def lasso_leftdown ( self , event = None ) : try : self . report_leftdown ( event = event ) except : return if event . inaxes : color = 'goldenrod' cmap = getattr ( self . conf , 'cmap' , None ) if isinstance ( cmap , dict ) : cmap = cmap [ 'int' ] try : if cmap is not None : rgb = ( int ( i * 255 ) ^ 255 for i in cmap . _lut [ 0 ] [ : 3 ] ) color = '#%02x%02x%02x' % tuple ( rgb ) except : pass self . lasso = Lasso ( event . inaxes , ( event . xdata , event . ydata ) , self . lassoHandler ) self . lasso . line . set_color ( color )
leftdown event handler for lasso mode
61,190
def rename ( self , new_folder_name ) : headers = self . headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self . id payload = '{ "DisplayName": "' + new_folder_name + '"}' r = requests . patch ( endpoint , headers = headers , data = payload ) if check_response ( r ) : return_folder = r . json ( ) return self . _json_to_folder ( self . account , return_folder )
Renames the Folder to the provided name .
61,191
def get_subfolders ( self ) : headers = self . headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self . id + '/childfolders' r = requests . get ( endpoint , headers = headers ) if check_response ( r ) : return self . _json_to_folders ( self . account , r . json ( ) )
Retrieve all child Folders inside of this Folder .
61,192
def delete ( self ) : headers = self . headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self . id r = requests . delete ( endpoint , headers = headers ) check_response ( r )
Deletes this Folder .
61,193
def move_into ( self , destination_folder ) : headers = self . headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self . id + '/move' payload = '{ "DestinationId": "' + destination_folder . id + '"}' r = requests . post ( endpoint , headers = headers , data = payload ) if check_response ( r ) : return_folder = r . json ( ) return self . _json_to_folder ( self . account , return_folder )
Move the Folder into a different folder .
61,194
def create_child_folder ( self , folder_name ) : headers = self . headers endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/' + self . id + '/childfolders' payload = '{ "DisplayName": "' + folder_name + '"}' r = requests . post ( endpoint , headers = headers , data = payload ) if check_response ( r ) : return_folder = r . json ( ) return self . _json_to_folder ( self . account , return_folder )
Creates a child folder within the Folder it is called from and returns the new Folder object .
61,195
def gformat ( val , length = 11 ) : try : expon = int ( log10 ( abs ( val ) ) ) except ( OverflowError , ValueError ) : expon = 0 length = max ( length , 7 ) form = 'e' prec = length - 7 if abs ( expon ) > 99 : prec -= 1 elif ( ( expon > 0 and expon < ( prec + 4 ) ) or ( expon <= 0 and - expon < ( prec - 1 ) ) ) : form = 'f' prec += 4 if expon > 0 : prec -= expon fmt = '{0: %i.%i%s}' % ( length , prec , form ) return fmt . format ( val )
Format a number with %g - like format except that
61,196
def pack ( window , sizer , expand = 1.1 ) : "simple wxPython pack function" tsize = window . GetSize ( ) msize = window . GetMinSize ( ) window . SetSizer ( sizer ) sizer . Fit ( window ) nsize = ( 10 * int ( expand * ( max ( msize [ 0 ] , tsize [ 0 ] ) / 10 ) ) , 10 * int ( expand * ( max ( msize [ 1 ] , tsize [ 1 ] ) / 10. ) ) ) window . SetSize ( nsize )
simple wxPython pack function
61,197
def Setup ( self , event = None ) : if hasattr ( self , 'printerData' ) : data = wx . PageSetupDialogData ( ) data . SetPrintData ( self . printerData ) else : data = wx . PageSetupDialogData ( ) data . SetMarginTopLeft ( ( 15 , 15 ) ) data . SetMarginBottomRight ( ( 15 , 15 ) ) dlg = wx . PageSetupDialog ( None , data ) if dlg . ShowModal ( ) == wx . ID_OK : data = dlg . GetPageSetupData ( ) tl = data . GetMarginTopLeft ( ) br = data . GetMarginBottomRight ( ) self . printerData = wx . PrintData ( data . GetPrintData ( ) ) dlg . Destroy ( )
set up figure for printing . Using the standard wx Printer Setup Dialog .
61,198
def Preview ( self , title = None , event = None ) : if title is None : title = self . title if self . canvas is None : self . canvas = self . parent . canvas po1 = PrintoutWx ( self . parent . canvas , title = title , width = self . pwidth , margin = self . pmargin ) po2 = PrintoutWx ( self . parent . canvas , title = title , width = self . pwidth , margin = self . pmargin ) self . preview = wx . PrintPreview ( po1 , po2 , self . printerData ) if ( ( is_wxPhoenix and self . preview . IsOk ( ) ) or ( not is_wxPhoenix and self . preview . Ok ( ) ) ) : self . preview . SetZoom ( 85 ) frameInst = self . parent while not isinstance ( frameInst , wx . Frame ) : frameInst = frameInst . GetParent ( ) frame = wx . PreviewFrame ( self . preview , frameInst , "Preview" ) frame . Initialize ( ) frame . SetSize ( ( 850 , 650 ) ) frame . Centre ( wx . BOTH ) frame . Show ( True )
generate Print Preview with wx Print mechanism
61,199
def set_float ( val ) : out = None if not val in ( None , '' ) : try : out = float ( val ) except ValueError : return None if numpy . isnan ( out ) : out = default return out
utility to set a floating value useful for converting from strings