idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
1,900 | def register ( self , signal , description ) : return self . __app . signals . register ( signal , self . _plugin , description ) | Registers a new signal . Only registered signals are allowed to be send . | 29 | 15 |
1,901 | def get ( self , signal = None ) : return self . __app . signals . get ( signal , self . _plugin ) | Returns a single signal or a dictionary of signals for this plugin . | 27 | 13 |
1,902 | def get_receiver ( self , receiver = None ) : return self . __app . signals . get_receiver ( receiver , self . _plugin ) | Returns a single receiver or a dictionary of receivers for this plugin . | 33 | 13 |
1,903 | def validate ( mcs , bases , attributes ) : if bases [ 0 ] is object : return None mcs . check_model_cls ( attributes ) mcs . check_include_exclude ( attributes ) mcs . check_properties ( attributes ) | Check attributes . | 54 | 3 |
1,904 | def get_properties ( attributes ) : return [ key for key , value in six . iteritems ( attributes ) if isinstance ( value , property ) ] | Return tuple of names of defined properties . | 32 | 8 |
1,905 | def check_properties ( mcs , attributes ) : include , exclude = mcs . get_prepared_include_exclude ( attributes ) properties = mcs . get_properties ( attributes ) intersections = list ( set ( properties ) . intersection ( include if include else exclude ) ) if not intersections : return None attr_name = '__include__' i... | Check whether intersections exist . | 127 | 5 |
1,906 | def on_deleted ( self , event ) : key = 'filesystem:file_deleted' data = { 'filepath' : event . src_path , 'is_directory' : event . is_directory , 'dirpath' : os . path . dirname ( event . src_path ) } bmsg = BroadcastMessage ( key = key , data = data ) BroadcastManager . broadcast ( bmsg ) | Event Handler when a file is deleted | 89 | 7 |
1,907 | def read_auth_info ( agent_file_content ) : try : data = json . loads ( agent_file_content ) return AuthInfo ( key = bakery . PrivateKey . deserialize ( data [ 'key' ] [ 'private' ] ) , agents = list ( Agent ( url = a [ 'url' ] , username = a [ 'username' ] ) for a in data . get ( 'agents' , [ ] ) ) , ) except ( KeyErr... | Loads agent authentication information from the specified content string as read from an agents file . The returned information is suitable for passing as an argument to the AgentInteractor constructor . | 127 | 34 |
1,908 | def interact ( self , client , location , interaction_required_err ) : p = interaction_required_err . interaction_method ( 'agent' , InteractionInfo ) if p . login_url is None or p . login_url == '' : raise httpbakery . InteractionError ( 'no login-url field found in agent interaction method' ) agent = self . _find_age... | Implement Interactor . interact by obtaining obtaining a macaroon from the discharger discharging it with the local private key using the discharged macaroon as a discharge token | 342 | 36 |
1,909 | def legacy_interact ( self , client , location , visit_url ) : agent = self . _find_agent ( location ) # Shallow-copy the client so that we don't unexpectedly side-effect # it by changing the key. Another possibility might be to # set up agent authentication differently, in such a way that # we're sure that client.key ... | Implement LegacyInteractor . legacy_interact by obtaining the discharge macaroon using the client s private key | 253 | 23 |
1,910 | def expiry_time ( ns , cavs ) : prefix = ns . resolve ( STD_NAMESPACE ) time_before_cond = condition_with_prefix ( prefix , COND_TIME_BEFORE ) t = None for cav in cavs : if not cav . first_party ( ) : continue cav = cav . caveat_id_bytes . decode ( 'utf-8' ) name , rest = parse_caveat ( cav ) if name != time_before_con... | Returns the minimum time of any time - before caveats found in the given list or None if no such caveats were found . | 154 | 24 |
1,911 | def replace_all ( text , replace_dict ) : for i , j in replace_dict . items ( ) : text = text . replace ( i , j ) return text | Replace multiple strings in a text . | 37 | 8 |
1,912 | def map_or_apply ( function , param ) : try : if isinstance ( param , list ) : return [ next ( iter ( function ( i ) ) ) for i in param ] else : return next ( iter ( function ( param ) ) ) except StopIteration : return None | Map the function on param or apply it depending whether param \ is a list or an item . | 60 | 19 |
1,913 | def batch ( iterable , size ) : item = iter ( iterable ) while True : batch_iterator = islice ( item , size ) try : yield chain ( [ next ( batch_iterator ) ] , batch_iterator ) except StopIteration : return | Get items from a sequence a batch at a time . | 55 | 11 |
1,914 | def slugify ( value ) : try : unicode_type = unicode except NameError : unicode_type = str if not isinstance ( value , unicode_type ) : value = unicode_type ( value ) value = ( unicodedata . normalize ( 'NFKD' , value ) . encode ( 'ascii' , 'ignore' ) . decode ( 'ascii' ) ) value = unicode_type ( _SLUGIFY_STRIP_RE . su... | Normalizes string converts to lowercase removes non - alpha characters and converts spaces to hyphens to have nice filenames . | 140 | 25 |
1,915 | def get_plaintext_citations ( arxiv_id ) : plaintext_citations = [ ] # Get the list of bbl files for this preprint bbl_files = arxiv . get_bbl ( arxiv_id ) for bbl_file in bbl_files : # Fetch the cited DOIs for each of the bbl files plaintext_citations . extend ( bbl . get_plaintext_citations ( bbl_file ) ) return plai... | Get the citations of a given preprint in plain text . | 112 | 12 |
1,916 | def get_cited_dois ( arxiv_id ) : dois = { } # Get the list of bbl files for this preprint bbl_files = arxiv . get_bbl ( arxiv_id ) for bbl_file in bbl_files : # Fetch the cited DOIs for each of the bbl files dois . update ( bbl . get_cited_dois ( bbl_file ) ) return dois | Get the DOIs of the papers cited in a . bbl file . | 103 | 15 |
1,917 | def get_subcommand_kwargs ( mgr , name , namespace ) : subcmd = mgr . get ( name ) subcmd_kwargs = { } for opt in list ( subcmd . args . values ( ) ) + list ( subcmd . options . values ( ) ) : if hasattr ( namespace , opt . dest ) : subcmd_kwargs [ opt . dest ] = getattr ( namespace , opt . dest ) return ( subcmd , sub... | Get subcommand options from global parsed arguments . | 104 | 9 |
1,918 | def get_plaintext_citations ( file ) : # Handle path or content if os . path . isfile ( file ) : with open ( file , 'r' ) as fh : content = fh . readlines ( ) else : content = file . splitlines ( ) # Clean every line to have plaintext cleaned_citations = [ tools . clean_whitespaces ( line ) for line in content ] return... | Parse a plaintext file to get a clean list of plaintext citations . The \ file should have one citation per line . | 94 | 26 |
1,919 | def get_cited_dois ( file ) : # If file is not a pre-processed list of plaintext citations if not isinstance ( file , list ) : # It is either a path to a plaintext file or the content of a plaintext # file, we need some pre-processing to get a list of citations. plaintext_citations = get_plaintext_citations ( file ) el... | Get the DOIs of the papers cited in a plaintext file . The file should \ have one citation per line . | 515 | 24 |
1,920 | def is_valid ( isbn_id ) : return ( ( not isbnlib . notisbn ( isbn_id ) ) and ( isbnlib . get_canonical_isbn ( isbn_id ) == isbn_id or isbnlib . mask ( isbnlib . get_canonical_isbn ( isbn_id ) ) == isbn_id ) ) | Check that a given string is a valid ISBN . | 85 | 10 |
1,921 | def extract_from_text ( text ) : isbns = [ isbnlib . get_canonical_isbn ( isbn ) for isbn in isbnlib . get_isbnlike ( text ) ] return [ i for i in isbns if i is not None ] | Extract ISBNs from a text . | 62 | 8 |
1,922 | def get_bibtex ( isbn_identifier ) : # Try to find the BibTeX using associated DOIs bibtex = doi . get_bibtex ( to_doi ( isbn_identifier ) ) if bibtex is None : # In some cases, there are no DOIs for a given ISBN. In this case, try # to fetch bibtex directly from the ISBN, using a combination of # Google Books and worl... | Get a BibTeX string for the given ISBN . | 143 | 10 |
1,923 | def used_options ( self ) : for option_str in filter ( lambda c : c . startswith ( '-' ) , self . words ) : for option in list ( self . cmd . options . values ( ) ) : if option_str in option . option_strings : yield option | Return options already used in the command line | 62 | 8 |
1,924 | def available_options ( self ) : for option in list ( self . cmd . options . values ( ) ) : if ( option . is_multiple or option not in list ( self . used_options ) ) : yield option | Return options that can be used given the current cmd line | 47 | 11 |
1,925 | def used_args ( self ) : # get all arguments values from the command line values = [ ] for idx , c in enumerate ( self . words [ 1 : ] ) : if c . startswith ( '-' ) : continue option_str = self . words [ 1 : ] [ idx - 1 ] option = self . get_option ( option_str ) if option is None or not option . need_value : values . ... | Return args already used in the command line | 226 | 8 |
1,926 | def available_args ( self ) : used = list ( self . used_args ) logger . debug ( 'Found used args: %s' % used ) for arg in list ( self . cmd . args . values ( ) ) : if ( arg . is_multiple or arg not in used ) : yield arg elif ( type ( arg . nargs ) is int and arg . nargs > 1 and not arg . nargs == used . count ( arg ) )... | Return args that can be used given the current cmd line | 101 | 11 |
1,927 | def is_elem_ref ( elem_ref ) : return ( elem_ref and isinstance ( elem_ref , tuple ) and len ( elem_ref ) == 3 and ( elem_ref [ 0 ] == ElemRefObj or elem_ref [ 0 ] == ElemRefArr ) ) | Returns true if the elem_ref is an element reference | 71 | 12 |
1,928 | def get_elem ( elem_ref , default = None ) : if not is_elem_ref ( elem_ref ) : return elem_ref elif elem_ref [ 0 ] == ElemRefObj : return getattr ( elem_ref [ 1 ] , elem_ref [ 2 ] , default ) elif elem_ref [ 0 ] == ElemRefArr : return elem_ref [ 1 ] [ elem_ref [ 2 ] ] | Gets the element referenced by elem_ref or returns the elem_ref directly if its not a reference . | 106 | 24 |
1,929 | def set_elem ( elem_ref , elem ) : if elem_ref is None or elem_ref == elem or not is_elem_ref ( elem_ref ) : return elem elif elem_ref [ 0 ] == ElemRefObj : setattr ( elem_ref [ 1 ] , elem_ref [ 2 ] , elem ) return elem elif elem_ref [ 0 ] == ElemRefArr : elem_ref [ 1 ] [ elem_ref [ 2 ] ] = elem return elem | Sets element referenced by the elem_ref . Returns the elem . | 126 | 16 |
1,930 | def _preprocess ( inp ) : inp = re . sub ( r'(\b)a(\b)' , r'\g<1>one\g<2>' , inp ) inp = re . sub ( r'to the (.*) power' , r'to \g<1>' , inp ) inp = re . sub ( r'to the (.*?)(\b)' , r'to \g<1>\g<2>' , inp ) inp = re . sub ( r'log of' , r'log' , inp ) inp = re . sub ( r'(square )?root( of)?' , r'sqrt' , inp ) inp = re .... | Revise wording to match canonical and expected forms . | 680 | 10 |
1,931 | def _calculate ( numbers , symbols ) : if len ( numbers ) is 1 : return numbers [ 0 ] precedence = [ [ pow ] , [ mul , div ] , [ add , sub ] ] # Find most important operation for op_group in precedence : for i , op in enumerate ( symbols ) : if op in op_group : # Apply operation a = numbers [ i ] b = numbers [ i + 1 ] ... | Calculates a final value given a set of numbers and symbols . | 167 | 14 |
1,932 | def parseEquation ( self , inp ) : inp = MathService . _preprocess ( inp ) split = inp . split ( ' ' ) # Recursive call on unary operators for i , w in enumerate ( split ) : if w in self . __unaryOperators__ : op = self . __unaryOperators__ [ w ] # Split equation into halves eq1 = ' ' . join ( split [ : i ] ) eq2 = ' '... | Solves the equation specified by the input string . | 373 | 10 |
1,933 | def register ( self , command , description , function , params = [ ] ) : return self . app . commands . register ( command , description , function , params , self . plugin ) | Registers a new command for a plugin . | 38 | 9 |
1,934 | def get ( self , name = None ) : return self . app . commands . get ( name , self . plugin ) | Returns commands which can be filtered by name . | 25 | 9 |
1,935 | def get ( self , name = None , plugin = None ) : if plugin is not None : if name is None : command_list = { } for key in self . _commands . keys ( ) : if self . _commands [ key ] . plugin == plugin : command_list [ key ] = self . _commands [ key ] return command_list else : if name in self . _commands . keys ( ) : if s... | Returns commands which can be filtered by name or plugin . | 164 | 11 |
1,936 | def unregister ( self , command ) : if command not in self . _commands . keys ( ) : self . log . warning ( "Can not unregister command %s" % command ) else : # Click does not have any kind of a function to unregister/remove/deactivate already added commands. # So we need to delete the related objects manually from the ... | Unregisters an existing command so that this command is no longer available on the command line interface . | 143 | 20 |
1,937 | def declared_caveat ( key , value ) : if key . find ( ' ' ) >= 0 or key == '' : return error_caveat ( 'invalid caveat \'declared\' key "{}"' . format ( key ) ) return _first_party ( COND_DECLARED , key + ' ' + value ) | Returns a declared caveat asserting that the given key is set to the given value . | 73 | 16 |
1,938 | def _operation_caveat ( cond , ops ) : for op in ops : if op . find ( ' ' ) != - 1 : return error_caveat ( 'invalid operation name "{}"' . format ( op ) ) return _first_party ( cond , ' ' . join ( ops ) ) | Helper for allow_caveat and deny_caveat . | 67 | 14 |
1,939 | def to_bytes ( s ) : if isinstance ( s , six . binary_type ) : return s if isinstance ( s , six . string_types ) : return s . encode ( 'utf-8' ) raise TypeError ( 'want string or bytes, got {}' , type ( s ) ) | Return s as a bytes type using utf - 8 encoding if necessary . | 66 | 15 |
1,940 | def b64decode ( s ) : # add padding if necessary. s = to_bytes ( s ) if not s . endswith ( b'=' ) : s = s + b'=' * ( - len ( s ) % 4 ) try : if '_' or '-' in s : return base64 . urlsafe_b64decode ( s ) else : return base64 . b64decode ( s ) except ( TypeError , binascii . Error ) as e : raise ValueError ( str ( e ) ) | Base64 decodes a base64 - encoded string in URL - safe or normal format with or without padding . The argument may be string or bytes . | 117 | 30 |
1,941 | def raw_urlsafe_b64encode ( b ) : b = to_bytes ( b ) b = base64 . urlsafe_b64encode ( b ) b = b . rstrip ( b'=' ) # strip padding return b | Base64 encode using URL - safe encoding with padding removed . | 54 | 12 |
1,942 | def cookie ( url , name , value , expires = None ) : u = urlparse ( url ) domain = u . hostname if '.' not in domain and not _is_ip_addr ( domain ) : domain += ".local" port = str ( u . port ) if u . port is not None else None secure = u . scheme == 'https' if expires is not None : if expires . tzinfo is not None : rai... | Return a new Cookie using a slightly more friendly API than that provided by six . moves . http_cookiejar | 226 | 22 |
1,943 | def _login ( self ) : self . logger . debug ( "Logging into " + "{}/{}" . format ( self . _im_api_url , "j_spring_security_check" ) ) self . _im_session . headers . update ( { 'Content-Type' : 'application/x-www-form-urlencoded' , 'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML... | LOGIN CAN ONLY BE DONE BY POSTING TO A HTTP FORM . A COOKIE IS THEN USED FOR INTERACTING WITH THE API | 445 | 30 |
1,944 | def _do_get ( self , uri , * * kwargs ) : #TODO: # Add error handling. Check for HTTP status here would be much more conveinent than in each calling method scaleioapi_get_headers = { 'Content-type' : 'application/json' , 'Version' : '1.0' } self . logger . debug ( "_do_get() " + "{}/{}" . format ( self . _api_url , uri... | Convinient method for GET requests Returns http request status value from a POST request | 317 | 16 |
1,945 | def uploadFileToIM ( self , directory , filename , title ) : self . logger . debug ( "uploadFileToIM(" + "{},{},{})" . format ( directory , filename , title ) ) parameters = { 'data-filename-placement' : 'inside' , 'title' : str ( filename ) , 'filename' : str ( filename ) , 'type' : 'file' , 'name' : 'files' , 'id' : ... | Parameters as they look in the form for uploading packages to IM | 362 | 12 |
1,946 | async def dump_varint_t ( writer , type_or , pv ) : width = int_mark_to_size ( type_or ) n = ( pv << 2 ) | type_or buffer = _UINT_BUFFER for _ in range ( width ) : buffer [ 0 ] = n & 0xff await writer . awrite ( buffer ) n >>= 8 return width | Binary dump of the integer of given type | 85 | 9 |
1,947 | async def dump_varint ( writer , val ) : if val <= 63 : return await dump_varint_t ( writer , PortableRawSizeMark . BYTE , val ) elif val <= 16383 : return await dump_varint_t ( writer , PortableRawSizeMark . WORD , val ) elif val <= 1073741823 : return await dump_varint_t ( writer , PortableRawSizeMark . DWORD , val )... | Binary dump of the variable size integer | 143 | 8 |
1,948 | async def load_varint ( reader ) : buffer = _UINT_BUFFER await reader . areadinto ( buffer ) width = int_mark_to_size ( buffer [ 0 ] & PortableRawSizeMark . MASK ) result = buffer [ 0 ] shift = 8 for _ in range ( width - 1 ) : await reader . areadinto ( buffer ) result += buffer [ 0 ] << shift shift += 8 return result ... | Binary load of variable size integer serialized by dump_varint | 94 | 14 |
1,949 | async def dump_string ( writer , val ) : await dump_varint ( writer , len ( val ) ) await writer . awrite ( val ) | Binary string dump | 33 | 4 |
1,950 | async def load_string ( reader ) : ivalue = await load_varint ( reader ) fvalue = bytearray ( ivalue ) await reader . areadinto ( fvalue ) return bytes ( fvalue ) | Loads string from binary stream | 50 | 6 |
1,951 | async def dump_blob ( writer , elem , elem_type , params = None ) : elem_is_blob = isinstance ( elem , x . BlobType ) data = bytes ( getattr ( elem , x . BlobType . DATA_ATTR ) if elem_is_blob else elem ) await dump_varint ( writer , len ( elem ) ) await writer . awrite ( data ) | Dumps blob to a binary stream | 98 | 7 |
1,952 | async def container_load ( self , container_type , params = None , container = None , obj = None ) : elem_type = x . container_elem_type ( container_type , params ) elem_size = await self . get_element_size ( elem_type = elem_type , params = params ) # If container is of fixed size we know the size to load from the inp... | Loads container of elements from the reader . Supports the container ref . Returns loaded container . Blob array writer as in XMRRPC is serialized without size serialization . | 294 | 36 |
1,953 | def make_index_for ( package , index_dir , verbose = True ) : index_template = """\ <html> <head><title>{title}</title></head> <body> <h1>{title}</h1> <ul> {packages} </ul> </body> </html> """ item_template = '<li><a href="{1}">{0}</a></li>' index_filename = os . path . join ( index_dir , "index.html" ) if not os . pat... | Create an index . html for one package . | 454 | 9 |
1,954 | def make_package_index ( download_dir ) : if not os . path . isdir ( download_dir ) : raise ValueError ( "No such directory: %r" % download_dir ) pkg_rootdir = os . path . join ( download_dir , "simple" ) if os . path . isdir ( pkg_rootdir ) : shutil . rmtree ( pkg_rootdir , ignore_errors = True ) os . mkdir ( pkg_root... | Create a pypi server like file structure below download directory . | 391 | 13 |
1,955 | def _convert_to_list ( self , value , delimiters ) : if not value : return [ ] if delimiters : return [ l . strip ( ) for l in value . split ( delimiters ) ] return [ l . strip ( ) for l in value . split ( ) ] | Return a list value translating from other types if necessary . | 65 | 11 |
1,956 | def getlist ( self , section , option , raw = False , vars = None , fallback = [ ] , delimiters = ',' ) : v = self . get ( section , option , raw = raw , vars = vars , fallback = fallback ) return self . _convert_to_list ( v , delimiters = delimiters ) | A convenience method which coerces the option in the specified section to a list of strings . | 80 | 18 |
1,957 | def getfile ( self , section , option , raw = False , vars = None , fallback = "" , validate = False ) : v = self . get ( section , option , raw = raw , vars = vars , fallback = fallback ) v = self . _convert_to_path ( v ) return v if not validate or os . path . isfile ( v ) else fallback | A convenience method which coerces the option in the specified section to a file . | 87 | 16 |
1,958 | def getdir ( self , section , option , raw = False , vars = None , fallback = "" , validate = False ) : v = self . get ( section , option , raw = raw , vars = vars , fallback = fallback ) v = self . _convert_to_path ( v ) return v if not validate or os . path . isdir ( v ) else fallback | A convenience method which coerces the option in the specified section to a directory . | 87 | 16 |
1,959 | def getdirs ( self , section , option , raw = False , vars = None , fallback = [ ] ) : globs = self . getlist ( section , option , fallback = [ ] ) return [ f for g in globs for f in glob . glob ( g ) if os . path . isdir ( f ) ] | A convenience method which coerces the option in the specified section to a list of directories . | 73 | 18 |
1,960 | def register ( self , name , content , description = None ) : return self . __app . documents . register ( name , content , self . _plugin , description ) | Register a new document . | 35 | 5 |
1,961 | def unregister ( self , document ) : if document not in self . documents . keys ( ) : self . log . warning ( "Can not unregister document %s" % document ) else : del ( self . documents [ document ] ) self . __log . debug ( "Document %s got unregistered" % document ) | Unregisters an existing document so that this document is no longer available . | 68 | 15 |
1,962 | def get ( self , document = None , plugin = None ) : if plugin is not None : if document is None : documents_list = { } for key in self . documents . keys ( ) : if self . documents [ key ] . plugin == plugin : documents_list [ key ] = self . documents [ key ] return documents_list else : if document in self . documents... | Get one or more documents . | 146 | 6 |
1,963 | def initialise_by_names ( self , plugins = None ) : if plugins is None : plugins = [ ] self . _log . debug ( "Plugins Initialisation started" ) if not isinstance ( plugins , list ) : raise AttributeError ( "plugins must be a list, not %s" % type ( plugins ) ) self . _log . debug ( "Plugins to initialise: %s" % ", " . j... | Initialises given plugins but does not activate them . | 217 | 10 |
1,964 | def activate ( self , plugins = [ ] ) : self . _log . debug ( "Plugins Activation started" ) if not isinstance ( plugins , list ) : raise AttributeError ( "plugins must be a list, not %s" % type ( plugins ) ) self . _log . debug ( "Plugins to activate: %s" % ", " . join ( plugins ) ) plugins_activated = [ ] for plugin_... | Activates given plugins . | 485 | 5 |
1,965 | def deactivate ( self , plugins = [ ] ) : self . _log . debug ( "Plugins Deactivation started" ) if not isinstance ( plugins , list ) : raise AttributeError ( "plugins must be a list, not %s" % type ( plugins ) ) self . _log . debug ( "Plugins to deactivate: %s" % ", " . join ( plugins ) ) plugins_deactivated = [ ] for... | Deactivates given plugins . | 342 | 6 |
1,966 | def get ( self , name = None ) : if name is None : return self . _plugins else : if name not in self . _plugins . keys ( ) : return None else : return self . _plugins [ name ] | Returns the plugin object with the given name . Or if a name is not given the complete plugin dictionary is returned . | 47 | 23 |
1,967 | def is_active ( self , name ) : if name in self . _plugins . keys ( ) : return self . _plugins [ "name" ] . active return None | Returns True if plugin exists and is active . If plugin does not exist it returns None | 36 | 17 |
1,968 | def register ( self , classes = [ ] ) : if not isinstance ( classes , list ) : raise AttributeError ( "plugins must be a list, not %s." % type ( classes ) ) plugin_registered = [ ] for plugin_class in classes : plugin_name = plugin_class . __name__ self . register_class ( plugin_class , plugin_name ) self . _log . debu... | Registers new plugins . | 135 | 5 |
1,969 | def get ( self , name = None ) : if name is None : return self . _classes else : if name not in self . _classes . keys ( ) : return None else : return self . _classes [ name ] | Returns the plugin class object with the given name . Or if a name is not given the complete plugin dictionary is returned . | 47 | 24 |
1,970 | def write ( self ) : filters = { 'MSGUID' : lambda x : ( '{%s}' % x ) . upper ( ) , 'relslnfile' : lambda x : os . path . relpath ( x , os . path . dirname ( self . FileName ) ) } context = { 'sln' : self } return self . render ( self . __jinja_template__ , self . FileName , context , filters ) | Writes the . sln file to disk . | 99 | 10 |
1,971 | def load_annotations ( self , aname , sep = ',' ) : ann = pd . read_csv ( aname ) cell_names = np . array ( list ( self . adata . obs_names ) ) all_cell_names = np . array ( list ( self . adata_raw . obs_names ) ) if ( ann . shape [ 1 ] > 1 ) : ann = pd . read_csv ( aname , index_col = 0 , sep = sep ) if ( ann . shape ... | Loads cell annotations . | 311 | 5 |
1,972 | def dispersion_ranking_NN ( self , nnm , num_norm_avg = 50 ) : self . knn_avg ( nnm ) D_avg = self . adata . layers [ 'X_knn_avg' ] mu , var = sf . mean_variance_axis ( D_avg , axis = 0 ) dispersions = np . zeros ( var . size ) dispersions [ mu > 0 ] = var [ mu > 0 ] / mu [ mu > 0 ] self . adata . var [ 'spatial_disper... | Computes the spatial dispersion factors for each gene . | 207 | 11 |
1,973 | def plot_correlated_groups ( self , group = None , n_genes = 5 , * * kwargs ) : geneID_groups = self . adata . uns [ 'gene_groups' ] if ( group is None ) : for i in range ( len ( geneID_groups ) ) : self . show_gene_expression ( geneID_groups [ i ] [ 0 ] , * * kwargs ) else : for i in range ( n_genes ) : self . show_ge... | Plots orthogonal expression patterns . | 133 | 8 |
1,974 | def plot_correlated_genes ( self , name , n_genes = 5 , number_of_features = 1000 , * * kwargs ) : all_gene_names = np . array ( list ( self . adata . var_names ) ) if ( ( all_gene_names == name ) . sum ( ) == 0 ) : print ( "Gene not found in the filtered dataset. Note that genes " "are case sensitive." ) return sds = ... | Plots gene expression patterns correlated with the input gene . | 201 | 11 |
1,975 | def run_tsne ( self , X = None , metric = 'correlation' , * * kwargs ) : if ( X is not None ) : dt = man . TSNE ( metric = metric , * * kwargs ) . fit_transform ( X ) return dt else : dt = man . TSNE ( metric = self . distance , * * kwargs ) . fit_transform ( self . adata . obsm [ 'X_pca' ] ) tsne2d = dt self . adata .... | Wrapper for sklearn s t - SNE implementation . | 132 | 12 |
1,976 | def run_umap ( self , X = None , metric = None , * * kwargs ) : import umap as umap if metric is None : metric = self . distance if ( X is not None ) : umap_obj = umap . UMAP ( metric = metric , * * kwargs ) dt = umap_obj . fit_transform ( X ) return dt else : umap_obj = umap . UMAP ( metric = metric , * * kwargs ) uma... | Wrapper for umap - learn . | 158 | 8 |
1,977 | def scatter ( self , projection = None , c = None , cmap = 'rainbow' , linewidth = 0.0 , edgecolor = 'k' , axes = None , colorbar = True , s = 10 , * * kwargs ) : if ( not PLOTTING ) : print ( "matplotlib not installed!" ) else : if ( isinstance ( projection , str ) ) : try : dt = self . adata . obsm [ projection ] exc... | Display a scatter plot . | 615 | 5 |
1,978 | def show_gene_expression ( self , gene , avg = True , axes = None , * * kwargs ) : all_gene_names = np . array ( list ( self . adata . var_names ) ) cell_names = np . array ( list ( self . adata . obs_names ) ) all_cell_names = np . array ( list ( self . adata_raw . obs_names ) ) idx = np . where ( all_gene_names == ge... | Display a gene s expressions . | 353 | 6 |
1,979 | def louvain_clustering ( self , X = None , res = 1 , method = 'modularity' ) : if X is None : X = self . adata . uns [ 'neighbors' ] [ 'connectivities' ] save = True else : if not sp . isspmatrix_csr ( X ) : X = sp . csr_matrix ( X ) save = False import igraph as ig import louvain adjacency = sparse_knn ( X . dot ( X .... | Runs Louvain clustering using the vtraag implementation . Assumes that louvain optional dependency is installed . | 346 | 25 |
1,980 | def kmeans_clustering ( self , numc , X = None , npcs = 15 ) : from sklearn . cluster import KMeans if X is None : D_sub = self . adata . uns [ 'X_processed' ] X = ( D_sub - D_sub . mean ( 0 ) ) . dot ( self . adata . uns [ 'pca_obj' ] . components_ [ : npcs , : ] . T ) save = True else : save = False cl = KMeans ( n_c... | Performs k - means clustering . | 175 | 8 |
1,981 | def identify_marker_genes_rf ( self , labels = None , clusters = None , n_genes = 4000 ) : if ( labels is None ) : try : keys = np . array ( list ( self . adata . obs_keys ( ) ) ) lbls = self . adata . obs [ ut . search_string ( keys , '_clusters' ) [ 0 ] [ 0 ] ] . get_values ( ) except KeyError : print ( "Please gener... | Ranks marker genes for each cluster using a random forest classification approach . | 413 | 14 |
1,982 | def identify_marker_genes_corr ( self , labels = None , n_genes = 4000 ) : if ( labels is None ) : try : keys = np . array ( list ( self . adata . obs_keys ( ) ) ) lbls = self . adata . obs [ ut . search_string ( keys , '_clusters' ) [ 0 ] [ 0 ] ] . get_values ( ) except KeyError : print ( "Please generate cluster labe... | Ranking marker genes based on their respective magnitudes in the correlation dot products with cluster - specific reference expression profiles . | 461 | 23 |
1,983 | def add ( self , action = None , subject = None , * * conditions ) : self . add_rule ( Rule ( True , action , subject , * * conditions ) ) | Add ability are allowed using two arguments . | 37 | 8 |
1,984 | def addnot ( self , action = None , subject = None , * * conditions ) : self . add_rule ( Rule ( False , action , subject , * * conditions ) ) | Defines an ability which cannot be done . | 38 | 9 |
1,985 | def can ( self , action , subject , * * conditions ) : for rule in self . relevant_rules_for_match ( action , subject ) : if rule . matches_conditions ( action , subject , * * conditions ) : return rule . base_behavior return False | Check if the user has permission to perform a given action on an object | 57 | 14 |
1,986 | def relevant_rules_for_match ( self , action , subject ) : matches = [ ] for rule in self . rules : rule . expanded_actions = self . expand_actions ( rule . actions ) if rule . is_relevant ( action , subject ) : matches . append ( rule ) return self . optimize ( matches [ : : - 1 ] ) | retrive match action and subject | 74 | 6 |
1,987 | def expand_actions ( self , actions ) : r = [ ] for action in actions : r . append ( action ) if action in self . aliased_actions : r . extend ( self . aliased_actions [ action ] ) return r | Accepts an array of actions and returns an array of actions which match | 51 | 14 |
1,988 | def alias_action ( self , * args , * * kwargs ) : to = kwargs . pop ( 'to' , None ) if not to : return error_message = ( "You can't specify target ({}) as alias " "because it is real action name" . format ( to ) ) if to in list ( itertools . chain ( * self . aliased_actions . values ( ) ) ) : raise Exception ( error_me... | Alias one or more actions into another one . | 118 | 9 |
1,989 | def fetch ( table , cols = "*" , where = ( ) , group = "" , order = ( ) , limit = ( ) , * * kwargs ) : return select ( table , cols , where , group , order , limit , * * kwargs ) . fetchall ( ) | Convenience wrapper for database SELECT and fetch all . | 65 | 11 |
1,990 | def fetchone ( table , cols = "*" , where = ( ) , group = "" , order = ( ) , limit = ( ) , * * kwargs ) : return select ( table , cols , where , group , order , limit , * * kwargs ) . fetchone ( ) | Convenience wrapper for database SELECT and fetch one . | 66 | 11 |
1,991 | def insert ( table , values = ( ) , * * kwargs ) : values = dict ( values , * * kwargs ) . items ( ) sql , args = makeSQL ( "INSERT" , table , values = values ) return execute ( sql , args ) . lastrowid | Convenience wrapper for database INSERT . | 62 | 9 |
1,992 | def select ( table , cols = "*" , where = ( ) , group = "" , order = ( ) , limit = ( ) , * * kwargs ) : where = dict ( where , * * kwargs ) . items ( ) sql , args = makeSQL ( "SELECT" , table , cols , where , group , order , limit ) return execute ( sql , args ) | Convenience wrapper for database SELECT . | 85 | 8 |
1,993 | def update ( table , values , where = ( ) , * * kwargs ) : where = dict ( where , * * kwargs ) . items ( ) sql , args = makeSQL ( "UPDATE" , table , values = values , where = where ) return execute ( sql , args ) . rowcount | Convenience wrapper for database UPDATE . | 66 | 8 |
1,994 | def delete ( table , where = ( ) , * * kwargs ) : where = dict ( where , * * kwargs ) . items ( ) sql , args = makeSQL ( "DELETE" , table , where = where ) return execute ( sql , args ) . rowcount | Convenience wrapper for database DELETE . | 62 | 10 |
1,995 | def make_cursor ( path , init_statements = ( ) , _connectioncache = { } ) : connection = _connectioncache . get ( path ) if not connection : is_new = not os . path . exists ( path ) or not os . path . getsize ( path ) try : is_new and os . makedirs ( os . path . dirname ( path ) ) except OSError : pass connection = sql... | Returns a cursor to the database making new connection if not cached . | 223 | 13 |
1,996 | def continue_prompt ( message = "" ) : answer = False message = message + "\n'Yes' or 'No' to continue: " while answer not in ( 'Yes' , 'No' ) : answer = prompt ( message , eventloop = eventloop ( ) ) if answer == "Yes" : answer = True break if answer == "No" : answer = False break return answer | Prompt the user to continue or not | 83 | 8 |
1,997 | def printo ( msg , encoding = None , errors = 'replace' , std_type = 'stdout' ) : std = getattr ( sys , std_type , sys . stdout ) if encoding is None : try : encoding = std . encoding except AttributeError : encoding = None # Fallback to ascii if no encoding is found if encoding is None : encoding = 'ascii' # https://d... | Write msg on stdout . If no encoding is specified the detected encoding of stdout is used . If the encoding can t encode some chars they are replaced by ? | 163 | 33 |
1,998 | def format_tree ( tree ) : def _traverse_tree ( tree , parents = None ) : tree [ 'parents' ] = parents childs = tree . get ( 'childs' , [ ] ) nb_childs = len ( childs ) for index , child in enumerate ( childs ) : child_parents = list ( parents ) + [ index == nb_childs - 1 ] tree [ 'childs' ] [ index ] = _traverse_tree ... | Format a python tree structure | 340 | 5 |
1,999 | def parallel_map ( func , iterable , args = None , kwargs = None , workers = None ) : if args is None : args = ( ) if kwargs is None : kwargs = { } if workers is not None : pool = Pool ( workers ) else : pool = Group ( ) iterable = [ pool . spawn ( func , i , * args , * * kwargs ) for i in iterable ] pool . join ( rais... | Map func on a list using gevent greenlets . | 167 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.