idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
33,600 | def create ( self , title , description = None , document_ids = None ) : params = { 'title' : title , } if description : params [ 'description' ] = description params = urllib . parse . urlencode ( params , doseq = True ) if document_ids : params += "" . join ( [ '&document_ids[]=%s' % id for id in document_ids ] ) res... | Creates a new project . |
33,601 | def get_or_create_by_title ( self , title ) : try : obj = self . get_by_title ( title ) created = False except DoesNotExistError : obj = self . create ( title = title ) created = True return obj , created | Fetch a title if it exists . Create it if it doesn t . |
33,602 | def get_location ( self ) : image_string = self . __dict__ [ 'location' ] [ 'image' ] image_ints = list ( map ( int , image_string . split ( "," ) ) ) return Location ( * image_ints ) | Return the location as a good |
33,603 | def put ( self ) : params = dict ( title = self . title or '' , source = self . source or '' , description = self . description or '' , related_article = self . resources . related_article or '' , published_url = self . resources . published_url or '' , access = self . access , data = self . data , ) self . _connection... | Save changes made to the object to DocumentCloud . |
33,604 | def _lazy_load ( self ) : obj = self . _connection . documents . get ( id = self . id ) self . __dict__ [ 'contributor' ] = obj . contributor self . __dict__ [ 'contributor_organization' ] = obj . contributor_organization self . __dict__ [ 'data' ] = obj . data self . __dict__ [ 'annotations' ] = obj . __dict__ [ 'anno... | Fetch metadata if it was overlooked during the object s creation . |
33,605 | def set_data ( self , data ) : if not isinstance ( data , type ( { } ) ) : raise TypeError ( "This attribute must be a dictionary." ) self . __dict__ [ 'data' ] = DocumentDataDict ( data ) | Update the data attribute making sure it s a dictionary . |
33,606 | def get_data ( self ) : try : return DocumentDataDict ( self . __dict__ [ 'data' ] ) except KeyError : self . _lazy_load ( ) return DocumentDataDict ( self . __dict__ [ 'data' ] ) | Fetch the data field if it does not exist . |
33,607 | def get_annotations ( self ) : try : obj_list = self . __dict__ [ 'annotations' ] return [ Annotation ( i ) for i in obj_list ] except KeyError : self . _lazy_load ( ) obj_list = self . __dict__ [ 'annotations' ] return [ Annotation ( i ) for i in obj_list ] | Fetch the annotations field if it does not exist . |
33,608 | def get_sections ( self ) : try : obj_list = self . __dict__ [ 'sections' ] return [ Section ( i ) for i in obj_list ] except KeyError : self . _lazy_load ( ) obj_list = self . __dict__ [ 'sections' ] return [ Section ( i ) for i in obj_list ] | Fetch the sections field if it does not exist . |
33,609 | def get_entities ( self ) : try : return self . __dict__ [ 'entities' ] except KeyError : entities = self . _connection . fetch ( "documents/%s/entities.json" % self . id ) . get ( "entities" ) obj_list = [ ] for type , entity_list in list ( entities . items ( ) ) : for entity in entity_list : entity [ 'type' ] = type ... | Fetch the entities extracted from this document by OpenCalais . |
33,610 | def get_page_text_url ( self , page ) : template = self . resources . page . get ( 'text' ) url = template . replace ( "{page}" , str ( page ) ) return url | Returns the URL for the full text of a particular page in the document . |
33,611 | def get_page_text ( self , page ) : url = self . get_page_text_url ( page ) return self . _get_url ( url ) | Downloads and returns the full text of a particular page in the document . |
33,612 | def get_small_image_url ( self , page = 1 ) : template = self . resources . page . get ( 'image' ) return template . replace ( "{page}" , str ( page ) ) . replace ( "{size}" , "small" ) | Returns the URL for the small sized image of a single page . |
33,613 | def get_thumbnail_image_url ( self , page = 1 ) : template = self . resources . page . get ( 'image' ) return template . replace ( "{page}" , str ( page ) ) . replace ( "{size}" , "thumbnail" ) | Returns the URL for the thumbnail sized image of a single page . |
33,614 | def get_normal_image_url ( self , page = 1 ) : template = self . resources . page . get ( 'image' ) return template . replace ( "{page}" , str ( page ) ) . replace ( "{size}" , "normal" ) | Returns the URL for the normal sized image of a single page . |
33,615 | def get_large_image_url ( self , page = 1 ) : template = self . resources . page . get ( 'image' ) return template . replace ( "{page}" , str ( page ) ) . replace ( "{size}" , "large" ) | Returns the URL for the large sized image of a single page . |
33,616 | def get_small_image ( self , page = 1 ) : url = self . get_small_image_url ( page = page ) return self . _get_url ( url ) | Downloads and returns the small sized image of a single page . |
33,617 | def get_thumbnail_image ( self , page = 1 ) : url = self . get_thumbnail_image_url ( page = page ) return self . _get_url ( url ) | Downloads and returns the thumbnail sized image of a single page . |
33,618 | def get_normal_image ( self , page = 1 ) : url = self . get_normal_image_url ( page = page ) return self . _get_url ( url ) | Downloads and returns the normal sized image of a single page . |
33,619 | def get_large_image ( self , page = 1 ) : url = self . get_large_image_url ( page = page ) return self . _get_url ( url ) | Downloads and returns the large sized image of a single page . |
33,620 | def put ( self ) : params = dict ( title = self . title or '' , description = self . description or '' , document_ids = [ str ( i . id ) for i in self . document_list ] ) self . _connection . put ( 'projects/%s.json' % self . id , params ) | Save changes made to the object to documentcloud . org |
33,621 | def get_document_list ( self ) : try : return self . __dict__ [ 'document_list' ] except KeyError : obj_list = DocumentSet ( [ self . _connection . documents . get ( i ) for i in self . document_ids ] ) self . __dict__ [ 'document_list' ] = obj_list return obj_list | Retrieves all documents included in this project . |
33,622 | def get_document ( self , id ) : obj_list = self . document_list matches = [ i for i in obj_list if str ( i . id ) == str ( id ) ] if not matches : raise DoesNotExistError ( "The resource you've requested does not \exist or is unavailable without the proper credentials." ) return matches [ 0 ] | Retrieves a particular document from this project . |
33,623 | def draw ( self , text1 = None , text2 = None , copyright = True , image = IMAGE_DEFAULT , rotate = 30 , opacity = 0.08 , compress = 0 , flatten = False , add = False ) : im_path = os . path . join ( IMAGE_DIRECTORY , image ) if os . path . isfile ( im_path ) : image = im_path if self . use_receipt : self . receipt . a... | Draw watermark PDF file . |
33,624 | def add ( self , document = None , watermark = None , underneath = False , output = None , suffix = 'watermarked' , method = 'pdfrw' ) : if self . use_receipt : self . receipt . add ( 'WM Placement' , 'Overlay' ) if not watermark : watermark = self . watermark if not document : document = self . document self . documen... | Add a watermark file to an existing PDF document . |
33,625 | def encrypt ( self , user_pw = '' , owner_pw = None , encrypt_128 = True , allow_printing = True , allow_commenting = False , document = None ) : document = self . document if document is None else document if self . use_receipt : self . receipt . add ( 'User pw' , user_pw ) self . receipt . add ( 'Owner pw' , owner_pw... | Encrypt a PDF document to add passwords and restrict permissions . |
33,626 | def credentials_required ( method_func ) : def _checkcredentials ( self , * args , ** kwargs ) : if self . username and self . password : return method_func ( self , * args , ** kwargs ) else : raise CredentialsMissingError ( "This is a private method. \You must provide a username and password when you initialize the \... | Decorator for methods that checks that the client has credentials . |
33,627 | def retry ( ExceptionToCheck , tries = 3 , delay = 2 , backoff = 2 ) : def deco_retry ( f ) : def f_retry ( * args , ** kwargs ) : mtries , mdelay = tries , delay try_one_last_time = True while mtries > 1 : try : return f ( * args , ** kwargs ) try_one_last_time = False break except ExceptionToCheck : six . print_ ( "R... | Retry decorator published by Saltry Crane . |
33,628 | def text_width ( string , font_name , font_size ) : return stringWidth ( string , fontName = font_name , fontSize = font_size ) | Determine with width in pixels of string . |
33,629 | def center_str ( txt , font_name , font_size , offset = 0 ) : return - ( text_width ( txt , font_name , font_size ) / 2.0 ) + offset | Center a string on the x axis of a reportslab canvas |
33,630 | def split_str ( string ) : split = string . split ( ' ' ) return ' ' . join ( split [ : len ( split ) // 2 ] ) , ' ' . join ( split [ len ( split ) // 2 : ] ) | Split string in half to return two strings |
33,631 | def _draw_image ( self , ci ) : img = img_adjust ( ci . image , ci . opacity , tempdir = self . dir ) self . can . drawImage ( img , x = ci . x , y = ci . y , width = ci . w , height = ci . h , mask = ci . mask , preserveAspectRatio = ci . preserve_aspect_ratio , anchorAtXY = True ) | Draw image object to reportlabs canvas . |
33,632 | def _draw_string ( self , cs ) : if self . can . _fontname != cs . font : self . can . setFont ( cs . font , cs . size ) elif self . can . _fontsize != cs . size : self . can . setFontSize ( cs . size ) self . can . setFillColor ( cs . color , cs . opacity ) if cs . y_centered and cs . x_centered : if text_width ( cs .... | Draw string object to reportlabs canvas . |
33,633 | def _get_pdf_list ( self , input_pdfs ) : if isinstance ( input_pdfs , list ) : return [ pdf for pdf in input_pdfs if self . validate ( pdf ) ] elif os . path . isdir ( input_pdfs ) : return [ os . path . join ( input_pdfs , pdf ) for pdf in os . listdir ( input_pdfs ) if self . validate ( pdf ) ] | Generate list of PDF documents . |
33,634 | def merge ( self , pdf_files , output ) : if self . method is 'pypdf3' : return self . pypdf3 ( pdf_files , output ) else : return self . pdfrw ( pdf_files , output ) | Merge list of PDF files to a single PDF file . |
33,635 | def set_destination ( source , suffix , filename = False , ext = None ) : source_dirname = os . path . dirname ( source ) if not source_dirname . endswith ( 'temp' ) : directory = os . path . join ( source_dirname , 'temp' ) else : directory = source_dirname if not os . path . isdir ( directory ) : os . mkdir ( directo... | Create new pdf filename for temp files |
33,636 | def getsize ( o_file ) : startpos = o_file . tell ( ) o_file . seek ( 0 ) o_file . seek ( 0 , SEEK_END ) size = o_file . tell ( ) o_file . seek ( startpos ) return size | get the size either by seeeking to the end . |
33,637 | def window ( self ) : platform = system ( ) if platform is 'Windows' : layout_tab_1 = [ ] layout_tab_1 . extend ( header ( 'PDF Watermark Utility' ) ) layout_tab_1 . extend ( self . input_source ( ) ) layout_tab_1 . extend ( self . input_text ( ) ) layout_tab_1 . extend ( self . input_encryption ( ) ) layout_tab_1 . ex... | GUI window for Watermark parameters input . |
33,638 | def pdf2img ( file_name , output = None , tempdir = None , ext = 'png' , progress_bar = None ) : return PDF2IMG ( file_name = file_name , output = output , tempdir = tempdir , ext = ext , progress_bar = progress_bar ) . save ( ) | Wrapper function for PDF2IMG class |
33,639 | def _get_page_data ( self , pno , zoom = 0 ) : dlist = self . dlist_tab [ pno ] if not dlist : self . dlist_tab [ pno ] = self . doc [ pno ] . getDisplayList ( ) dlist = self . dlist_tab [ pno ] r = dlist . rect mp = r . tl + ( r . br - r . tl ) * 0.5 mt = r . tl + ( r . tr - r . tl ) * 0.5 ml = r . tl + ( r . bl - r .... | Return a PNG image for a document page number . If zoom is other than 0 one of the 4 page quadrants are zoomed - in instead and the corresponding clip returned . |
33,640 | def text_extract ( path , password = None ) : pdf = Info ( path , password ) . pdf return [ pdf . getPage ( i ) . extractText ( ) for i in range ( pdf . getNumPages ( ) ) ] | Extract text from a PDF file |
33,641 | def open_window ( path ) : if 'pathlib' in modules : try : call ( [ "open" , "-R" , str ( Path ( str ( path ) ) ) ] ) except FileNotFoundError : Popen ( r'explorer /select,' + str ( Path ( str ( path ) ) ) ) else : print ( 'pathlib module must be installed to execute open_window function' ) | Open path in finder or explorer window |
33,642 | def secure ( pdf , user_pw , owner_pw , restrict_permission = True , pdftk = get_pdftk_path ( ) , output = None ) : if pdftk : with open ( pdf , 'rb' ) as f : reader = PdfFileReader ( f ) if reader . isEncrypted : print ( 'PDF is already encrypted' ) return pdf if not output : output = add_suffix ( pdf , 'secured' ) pd... | Encrypt a PDF file and restrict permissions to print only . |
33,643 | def add ( self , document , watermark ) : output_filename = self . output_filename def pypdf3 ( ) : document_reader = PdfFileReader ( document ) output_file = PdfFileWriter ( ) page_count = document_reader . getNumPages ( ) watermark_reader = PdfFileReader ( watermark ) wtrmrk_page = watermark_reader . getPage ( 0 ) wt... | Add watermark to PDF by merging original PDF and watermark file . |
33,644 | def img_opacity ( image , opacity ) : assert 0 <= opacity <= 1 , 'Opacity must be a float between 0 and 1' assert os . path . isfile ( image ) , 'Image is not a file' im = Image . open ( image ) if im . mode != 'RGBA' : im = im . convert ( 'RGBA' ) else : im = im . copy ( ) alpha = im . split ( ) [ 3 ] alpha = ImageEnh... | Reduce the opacity of a PNG image . |
33,645 | def _image_loop ( self ) : if self . progress_bar and 'tqdm' in self . progress_bar . lower ( ) : return tqdm ( self . imgs , desc = 'Saving PNGs as flat PDFs' , total = len ( self . imgs ) , unit = 'PDFs' ) else : return self . imgs | Retrieve an iterable of images either with or without a progress bar . |
33,646 | def _convert ( self , image , output = None ) : with Image . open ( image ) as im : width , height = im . size co = CanvasObjects ( ) co . add ( CanvasImg ( image , 1.0 , w = width , h = height ) ) return WatermarkDraw ( co , tempdir = self . tempdir , pagesize = ( width , height ) ) . write ( output ) | Private method for converting a single PNG image to a PDF . |
33,647 | def convert ( self , image , output = None ) : return self . _convert ( image , image . replace ( Path ( image ) . suffix , '.pdf' ) if not output else output ) | Convert an image to a PDF . |
33,648 | def add ( image_path , file_name = None ) : if file_name is not None : dst_path = os . path . join ( IMG_DIR , str ( Path ( file_name ) . stem + Path ( image_path ) . suffix ) ) else : dst_path = IMG_DIR if os . path . isfile ( image_path ) : shutil . copy2 ( image_path , dst_path ) | Add an image to the GUI img library . |
33,649 | def remove ( image ) : path = os . path . join ( IMG_DIR , image ) if os . path . isfile ( path ) : os . remove ( path ) | Remove an image to the GUI img library . |
33,650 | def pluginkit_beforerequest ( ) : authMethod = current_app . config . get ( "PLUGINKIT_AUTHMETHOD" ) authResult = dict ( msg = None , code = 1 , method = authMethod ) def authTipmsg ( authResult , code = 403 ) : return "%s Authentication failed [%s]: %s [%s]" % ( code , authResult [ "method" ] , authResult [ "msg" ] , ... | blueprint access auth |
33,651 | def __scanPlugins ( self ) : self . logger . info ( "Initialization Plugins Start, local plugins path: %s, third party plugins: %s" % ( self . plugins_abspath , self . plugin_packages ) ) if self . plugin_packages and isinstance ( self . plugin_packages , ( list , tuple ) ) : for package_name in self . plugin_packages ... | Scanning local plugin directories and third - party plugin packages . |
33,652 | def __getPluginInfo ( self , plugin , package_abspath , package_name ) : if not isValidSemver ( plugin . __version__ ) : raise VersionError ( "The plugin version does not conform to the standard named %s" % package_name ) try : url = plugin . __url__ except AttributeError : url = None try : license = plugin . __license... | Organize plugin information . |
33,653 | def get_plugin_info ( self , plugin_name ) : if plugin_name : for i in self . get_all_plugins : if i [ "plugin_name" ] == plugin_name : return i | Get plugin information |
33,654 | def get_all_tep ( self ) : teps = { } for p in self . get_enabled_plugins : for e , v in p [ "plugin_tep" ] . items ( ) : tep = teps . get ( e , dict ( ) ) tepHF = tep . get ( "HTMLFile" , [ ] ) tepHS = tep . get ( "HTMLString" , [ ] ) tepHF += [ s for f , s in v . items ( ) if f == "HTMLFile" ] tepHS += [ s for f , s ... | Template extension point |
33,655 | def get_all_hep ( self ) : return dict ( before_request_hook = [ plugin [ "plugin_hep" ] [ "before_request_hook" ] for plugin in self . get_enabled_plugins if plugin [ "plugin_hep" ] . get ( "before_request_hook" ) ] , before_request_top_hook = [ plugin [ "plugin_hep" ] [ "before_request_top_hook" ] for plugin in self ... | Hook extension point . |
33,656 | def push_dcp ( self , event , callback , position = "right" ) : if event and isinstance ( event , string_types ) and callable ( callback ) and position in ( "left" , "right" ) : if event in self . _dcp_funcs : if position == "right" : self . _dcp_funcs [ event ] . append ( callback ) else : self . _dcp_funcs [ event ] ... | Connect a dcp push a function . |
33,657 | def push_func ( self , cuin , callback ) : if cuin and isinstance ( cuin , string_types ) and callable ( callback ) : if cuin in self . _dfp_funcs : raise DFPError ( "The cuin already exists" ) else : self . _dfp_funcs [ cuin ] = callback else : if not callable ( callback ) : raise NotCallableError ( "The cuin %s canno... | Push a function for dfp . |
33,658 | def finalize_options ( self ) : if self . test : print ( "V%s will publish to the test.pypi.org" % version ) elif self . release : print ( "V%s will publish to the pypi.org" % version ) | Post - process options . |
33,659 | def signatureJWT ( self , message ) : return hmac . new ( key = self . secretkey , msg = message , digestmod = hashlib . sha256 ) . hexdigest ( ) | Python generate HMAC - SHA - 256 from string |
33,660 | def __isValidTGZ ( self , suffix ) : if suffix and isinstance ( suffix , string_types ) : if suffix . endswith ( ".tar.gz" ) or suffix . endswith ( ".tgz" ) : return True return False | To determine whether the suffix . tar . gz or . tgz format |
33,661 | def __isValidZIP ( self , suffix ) : if suffix and isinstance ( suffix , string_types ) : if suffix . endswith ( ".zip" ) : return True return False | Determine if the suffix is . zip format |
33,662 | def __isValidFilename ( self , filename ) : if filename and isinstance ( filename , string_types ) : if re . match ( r'^[\w\d\_\-\.]+$' , filename , re . I ) : if self . __isValidTGZ ( filename ) or self . __isValidZIP ( filename ) : return True return False | Determine whether filename is valid |
33,663 | def __getFilename ( self , data , scene = 1 ) : try : filename = None if scene == 1 : plugin_filename = [ i for i in parse_qs ( urlsplit ( data ) . query ) . get ( "plugin_filename" ) or [ ] if i ] if plugin_filename and len ( plugin_filename ) == 1 : filename = plugin_filename [ 0 ] elif scene == 2 : filename = basena... | To get the data from different scenarios in the filename scene value see remote_download in 1 2 3 4 |
33,664 | def __getFilenameSuffix ( self , filename ) : if filename and isinstance ( filename , string_types ) : if self . __isValidTGZ ( filename ) : return ".tar.gz" elif filename . endswith ( ".zip" ) : return ".zip" | Gets the filename suffix |
33,665 | def __unpack_tgz ( self , filename ) : if isinstance ( filename , string_types ) and self . __isValidTGZ ( filename ) and tarfile . is_tarfile ( filename ) : with tarfile . open ( filename , mode = 'r:gz' ) as t : for name in t . getnames ( ) : t . extract ( name , self . plugin_abspath ) else : raise TarError ( "Inval... | Unpack the tar . gz tgz compressed file format |
33,666 | def __unpack_zip ( self , filename ) : if isinstance ( filename , string_types ) and self . __isValidZIP ( filename ) and zipfile . is_zipfile ( filename ) : with zipfile . ZipFile ( filename ) as z : for name in z . namelist ( ) : z . extract ( name , self . plugin_abspath ) else : raise ZipError ( "Invalid Plugin Com... | Unpack the zip compressed file format |
33,667 | def _local_upload ( self , filepath , remove = False ) : if os . path . isfile ( filepath ) : filename = os . path . basename ( os . path . abspath ( filepath ) ) if filename and self . __isValidFilename ( filename ) : suffix = self . __getFilenameSuffix ( filename ) try : self . __unpack_tgz ( os . path . abspath ( fi... | Local plugin package processing |
33,668 | def sortedSemver ( versions , sort = "asc" ) : if versions and isinstance ( versions , ( list , tuple ) ) : if PY2 : return sorted ( versions , cmp = semver . compare , reverse = True if sort . upper ( ) == "DESC" else False ) else : from functools import cmp_to_key return sorted ( versions , key = cmp_to_key ( semver ... | Semantically sort the list of version Numbers |
33,669 | def set ( self , key , value ) : db = self . open ( ) try : db [ key ] = value finally : db . close ( ) | Set persistent data with shelve . |
33,670 | def set ( self , key , value ) : if self . _db : self . _db . hset ( self . index , key , value ) | set key data |
33,671 | def flatten_list ( items , seqtypes = ( list , tuple ) , in_place = True ) : if not in_place : items = items [ : ] for i , _ in enumerate ( items ) : while i < len ( items ) and isinstance ( items [ i ] , seqtypes ) : items [ i : i + 1 ] = items [ i ] return items | Flatten an irregular sequence . |
33,672 | def intersperse ( lis , value ) : out = [ value ] * ( len ( lis ) * 2 - 1 ) out [ 0 : : 2 ] = lis return out | Put value between each existing item in list . |
33,673 | def get_index ( lis , argument ) : if isinstance ( argument , int ) : if - len ( lis ) <= argument < len ( lis ) : return argument else : raise IndexError ( "index {0} incompatible with length {1}" . format ( argument , len ( lis ) ) ) else : return lis . index ( argument ) | Find the index of an item given either the item or index as an argument . |
33,674 | def _title ( fig , title , subtitle = "" , * , margin = 1 , fontsize = 20 , subfontsize = 18 ) : fig . suptitle ( title , fontsize = fontsize ) height = fig . get_figheight ( ) distance = margin / 2. ratio = 1 - distance / height fig . text ( 0.5 , ratio , subtitle , fontsize = subfontsize , ha = "center" , va = "top" ... | Add a title to a figure . |
33,675 | def add_sideplot ( ax , along , pad = 0. , * , grid = True , zero_line = True , arrs_to_bin = None , normalize_bin = True , ymin = 0 , ymax = 1.1 , height = 0.75 , c = "C0" ) : if hasattr ( ax , "WrightTools_sideplot_divider" ) : divider = ax . WrightTools_sideplot_divider else : divider = make_axes_locatable ( ax ) se... | Add a sideplot to an axis . Sideplots share their corresponding axis . |
33,676 | def corner_text ( text , distance = 0.075 , * , ax = None , corner = "UL" , factor = 200 , bbox = True , fontsize = 18 , background_alpha = 1 , edgecolor = None ) : if ax is None : ax = plt . gca ( ) [ h_scaled , v_scaled ] , [ va , ha ] = get_scaled_bounds ( ax , corner , distance = distance , factor = factor ) if edg... | Place some text in the corner of the figure . |
33,677 | def create_figure ( * , width = "single" , nrows = 1 , cols = [ 1 ] , margin = 1. , hspace = 0.25 , wspace = 0.25 , cbar_width = 0.25 , aspects = [ ] , default_aspect = 1 ) : if width == "double" : figure_width = 14. elif width == "single" : figure_width = 6.5 elif width == "dissertation" : figure_width = 13. else : fi... | Re - parameterization of matplotlib figure creation tools exposing convenient variables . |
33,678 | def diagonal_line ( xi = None , yi = None , * , ax = None , c = None , ls = None , lw = None , zorder = 3 ) : if ax is None : ax = plt . gca ( ) if xi is None : xi = ax . get_xlim ( ) if yi is None : yi = ax . get_ylim ( ) if c is None : c = matplotlib . rcParams [ "grid.color" ] if ls is None : ls = matplotlib . rcPar... | Plot a diagonal line . |
33,679 | def get_scaled_bounds ( ax , position , * , distance = 0.1 , factor = 200 ) : x0 , y0 , width , height = ax . bbox . bounds width_scaled = width / factor height_scaled = height / factor if position == "UL" : v_scaled = distance / width_scaled h_scaled = 1 - ( distance / height_scaled ) va = "top" ha = "left" elif posit... | Get scaled bounds . |
33,680 | def pcolor_helper ( xi , yi , zi = None ) : xi = xi . copy ( ) yi = yi . copy ( ) if xi . ndim == 1 : xi . shape = ( xi . size , 1 ) if yi . ndim == 1 : yi . shape = ( 1 , yi . size ) shape = wt_kit . joint_shape ( xi , yi ) def full ( arr ) : for i in range ( arr . ndim ) : if arr . shape [ i ] == 1 : arr = np . repea... | Prepare a set of arrays for plotting using pcolor . |
33,681 | def plot_colorbar ( cax = None , cmap = "default" , ticks = None , clim = None , vlim = None , label = None , tick_fontsize = 14 , label_fontsize = 18 , decimals = None , orientation = "vertical" , ticklocation = "auto" , extend = "neither" , extendfrac = None , extendrect = False , ) : if cax is None : cax = plt . gca... | Easily add a colormap to an axis . |
33,682 | def plot_margins ( * , fig = None , inches = 1. , centers = True , edges = True ) : if fig is None : fig = plt . gcf ( ) size = fig . get_size_inches ( ) trans_vert = inches / size [ 0 ] left = matplotlib . lines . Line2D ( [ trans_vert , trans_vert ] , [ 0 , 1 ] , transform = fig . transFigure , figure = fig ) right =... | Add lines onto a figure indicating the margins centers and edges . |
33,683 | def plot_gridlines ( ax = None , c = "grey" , lw = 1 , diagonal = False , zorder = 2 , makegrid = True ) : if ax is None : ax = plt . gca ( ) ax . grid ( ) ls = ":" dashes = ( lw / 2 , lw ) lines = ax . xaxis . get_gridlines ( ) + ax . yaxis . get_gridlines ( ) for line in lines . copy ( ) : line . set_linestyle ( ":" ... | Plot dotted gridlines onto an axis . |
33,684 | def savefig ( path , fig = None , close = True , * , dpi = 300 ) : if fig is None : fig = plt . gcf ( ) path = os . path . abspath ( path ) plt . savefig ( path , dpi = dpi , transparent = False , pad_inches = 1 , facecolor = "none" ) if close : plt . close ( fig ) return path | Save a figure . |
33,685 | def set_ax_labels ( ax = None , xlabel = None , ylabel = None , xticks = None , yticks = None , label_fontsize = 18 ) : if ax is None : ax = plt . gca ( ) if xlabel is not None : ax . set_xlabel ( xlabel , fontsize = label_fontsize ) if xticks is not None : if isinstance ( xticks , bool ) : plt . setp ( ax . get_xtickl... | Set all axis labels properties easily . |
33,686 | def set_ax_spines ( ax = None , * , c = "k" , lw = 3 , zorder = 10 ) : if ax is None : ax = plt . gca ( ) for key in [ "bottom" , "top" , "right" , "left" ] : ax . spines [ key ] . set_color ( c ) ax . spines [ key ] . set_linewidth ( lw ) ax . spines [ key ] . zorder = zorder | Easily set the properties of all four axis spines . |
33,687 | def set_fig_labels ( fig = None , xlabel = None , ylabel = None , xticks = None , yticks = None , title = None , row = - 1 , col = 0 , label_fontsize = 18 , title_fontsize = 20 , ) : if fig is None : fig = plt . gcf ( ) numRows = fig . axes [ 0 ] . numRows if isinstance ( row , int ) : row %= numRows row = slice ( 0 , ... | Set all axis labels of a figure simultaniously . |
33,688 | def subplots_adjust ( fig = None , inches = 1 ) : if fig is None : fig = plt . gcf ( ) size = fig . get_size_inches ( ) vert = inches / size [ 0 ] horz = inches / size [ 1 ] fig . subplots_adjust ( vert , horz , 1 - vert , 1 - horz ) | Enforce margin to be equal around figure starting at subplots . |
33,689 | def stitch_to_animation ( images , outpath = None , * , duration = 0.5 , palettesize = 256 , verbose = True ) : if outpath is None : outpath = os . path . splitext ( images [ 0 ] ) [ 0 ] + ".gif" t = wt_kit . Timer ( verbose = False ) with t , imageio . get_writer ( outpath , mode = "I" , duration = duration , palettes... | Stitch a series of images into an animation . |
33,690 | def item_names ( self ) : if "item_names" not in self . attrs . keys ( ) : self . attrs [ "item_names" ] = np . array ( [ ] , dtype = "S" ) return tuple ( n . decode ( ) for n in self . attrs [ "item_names" ] ) | Item names . |
33,691 | def natural_name ( self ) : try : assert self . _natural_name is not None except ( AssertionError , AttributeError ) : self . _natural_name = self . attrs [ "name" ] finally : return self . _natural_name | Natural name . |
33,692 | def natural_name ( self , value ) : if value is None : value = "" if hasattr ( self , "_natural_name" ) and self . name != "/" : keys = [ k for k in self . _instances . keys ( ) if k . startswith ( self . fullpath ) ] dskeys = [ k for k in Dataset . _instances . keys ( ) if k . startswith ( self . fullpath ) ] self . p... | Set natural name . |
33,693 | def close ( self ) : from . collection import Collection from . data . _data import Channel , Data , Variable path = os . path . abspath ( self . filepath ) + "::" for key in list ( Group . _instances . keys ( ) ) : if key . startswith ( path ) : Group . _instances . pop ( key , None ) if self . fid . valid > 0 : try :... | Close the file that contains the Group . |
33,694 | def copy ( self , parent = None , name = None , verbose = True ) : if name is None : name = self . natural_name if parent is None : from . _open import open as wt_open new = Group ( ) new . attrs . update ( self . attrs ) new . natural_name = name for k , v in self . items ( ) : super ( ) . copy ( v , new , name = v . ... | Create a copy under parent . |
33,695 | def save ( self , filepath = None , overwrite = False , verbose = True ) : if filepath is None : filepath = pathlib . Path ( "." ) / self . natural_name else : filepath = pathlib . Path ( filepath ) filepath = filepath . with_suffix ( ".wt5" ) filepath = filepath . absolute ( ) . expanduser ( ) if filepath . exists ( )... | Save as root of a new file . |
33,696 | def from_JASCO ( filepath , name = None , parent = None , verbose = True ) -> Data : filestr = os . fspath ( filepath ) filepath = pathlib . Path ( filepath ) if not ".txt" in filepath . suffixes : wt_exceptions . WrongFileTypeWarning . warn ( filepath , ".txt" ) if not name : name = filepath . name . split ( "." ) [ 0... | Create a data object from JASCO UV - Vis spectrometers . |
33,697 | def make_cubehelix ( name = "WrightTools" , gamma = 0.5 , s = 0.25 , r = - 1 , h = 1.3 , reverse = False , darkest = 0.7 ) : rr = .213 / .30 rg = .715 / .99 rb = .072 / .11 def get_color_function ( p0 , p1 ) : def color ( x ) : xg = darkest * x ** gamma lum = 1 - xg if reverse : lum = lum [ : : - 1 ] a = lum . copy ( )... | Define cubehelix type colorbars . |
33,698 | def make_colormap ( seq , name = "CustomMap" , plot = False ) : seq = [ ( None , ) * 3 , 0.0 ] + list ( seq ) + [ 1.0 , ( None , ) * 3 ] cdict = { "red" : [ ] , "green" : [ ] , "blue" : [ ] } for i , item in enumerate ( seq ) : if isinstance ( item , float ) : r1 , g1 , b1 = seq [ i - 1 ] r2 , g2 , b2 = seq [ i + 1 ] c... | Generate a LinearSegmentedColormap . |
33,699 | def plot_colormap_components ( cmap ) : from . _helpers import set_ax_labels plt . figure ( figsize = [ 8 , 4 ] ) gs = grd . GridSpec ( 3 , 1 , height_ratios = [ 1 , 10 , 1 ] , hspace = 0.05 ) ax = plt . subplot ( gs [ 0 ] ) gradient = np . linspace ( 0 , 1 , 256 ) gradient = np . vstack ( ( gradient , gradient ) ) ax ... | Plot the components of a given colormap . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.