idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
1,900 | def entrypoint ( section , option ) : try : return entrypoints ( section ) [ option ] except KeyError : raise KeyError ( 'Cannot resolve type "{}" to a recognised vsgen "{}" type.' . format ( option , section ) ) | Returns the the entry point object given a section option pair . |
1,901 | def infer_declared ( ms , namespace = None ) : conditions = [ ] for m in ms : for cav in m . caveats : if cav . location is None or cav . location == '' : conditions . append ( cav . caveat_id_bytes . decode ( 'utf-8' ) ) return infer_declared_from_conditions ( conditions , namespace ) | Retrieves any declared information from the given macaroons and returns it as a key - value map . Information is declared with a first party caveat as created by declared_caveat . |
1,902 | def infer_declared_from_conditions ( conds , namespace = None ) : conflicts = [ ] if namespace is None : namespace = Namespace ( ) prefix = namespace . resolve ( STD_NAMESPACE ) if prefix is None : prefix = '' declared_cond = prefix + COND_DECLARED info = { } for cond in conds : try : name , rest = parse_caveat ( cond ... | like infer_declared except that it is passed a set of first party caveat conditions as a list of string rather than a set of macaroons . |
1,903 | def _pre_activate_injection ( self ) : if not self . app . plugins . classes . exist ( self . __class__ . __name__ ) : self . app . plugins . classes . register ( [ self . __class__ ] ) self . _load_needed_plugins ( ) self . app . signals . send ( "plugin_activate_pre" , self ) | Injects functions before the activation routine of child classes gets called |
1,904 | 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 . |
1,905 | 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 . |
1,906 | 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 . |
1,907 | 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 . |
1,908 | def get_properties ( attributes ) : return [ key for key , value in six . iteritems ( attributes ) if isinstance ( value , property ) ] | Return tuple of names of defined properties . |
1,909 | 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 . |
1,910 | 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 |
1,911 | 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 . |
1,912 | 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 |
1,913 | def legacy_interact ( self , client , location , visit_url ) : agent = self . _find_agent ( location ) client = copy . copy ( client ) client . key = self . _auth_info . key resp = client . request ( method = 'POST' , url = visit_url , json = { 'username' : agent . username , 'public_key' : str ( self . _auth_info . ke... | Implement LegacyInteractor . legacy_interact by obtaining the discharge macaroon using the client s private key |
1,914 | 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 . |
1,915 | 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 . |
1,916 | 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 . |
1,917 | 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 . |
1,918 | 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 . |
1,919 | def get_plaintext_citations ( arxiv_id ) : plaintext_citations = [ ] bbl_files = arxiv . get_bbl ( arxiv_id ) for bbl_file in bbl_files : plaintext_citations . extend ( bbl . get_plaintext_citations ( bbl_file ) ) return plaintext_citations | Get the citations of a given preprint in plain text . |
1,920 | def get_cited_dois ( arxiv_id ) : dois = { } bbl_files = arxiv . get_bbl ( arxiv_id ) for bbl_file in bbl_files : dois . update ( bbl . get_cited_dois ( bbl_file ) ) return dois | Get the DOIs of the papers cited in a . bbl file . |
1,921 | 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 . |
1,922 | def get_plaintext_citations ( file ) : if os . path . isfile ( file ) : with open ( file , 'r' ) as fh : content = fh . readlines ( ) else : content = file . splitlines ( ) cleaned_citations = [ tools . clean_whitespaces ( line ) for line in content ] return cleaned_citations | Parse a plaintext file to get a clean list of plaintext citations . The \ file should have one citation per line . |
1,923 | def get_cited_dois ( file ) : if not isinstance ( file , list ) : plaintext_citations = get_plaintext_citations ( file ) else : plaintext_citations = file dois = { } crossref_queue = [ ] for citation in plaintext_citations [ : ] : matched_dois = doi . extract_from_text ( citation ) if len ( matched_dois ) > 0 : dois [ ... | Get the DOIs of the papers cited in a plaintext file . The file should \ have one citation per line . |
1,924 | 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 . |
1,925 | 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 . |
1,926 | def get_bibtex ( isbn_identifier ) : bibtex = doi . get_bibtex ( to_doi ( isbn_identifier ) ) if bibtex is None : bibtex = isbnlib . registry . bibformatters [ 'bibtex' ] ( isbnlib . meta ( isbn_identifier , 'default' ) ) return bibtex | Get a BibTeX string for the given ISBN . |
1,927 | 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 |
1,928 | 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 |
1,929 | def used_args ( self ) : 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 . append ( ( c , c == self . document . get_word_be... | Return args already used in the command line |
1,930 | 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 |
1,931 | 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 |
1,932 | 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 . |
1,933 | 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 . |
1,934 | 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 . |
1,935 | def _calculate ( numbers , symbols ) : if len ( numbers ) is 1 : return numbers [ 0 ] precedence = [ [ pow ] , [ mul , div ] , [ add , sub ] ] for op_group in precedence : for i , op in enumerate ( symbols ) : if op in op_group : a = numbers [ i ] b = numbers [ i + 1 ] result = MathService . _applyBinary ( a , b , op )... | Calculates a final value given a set of numbers and symbols . |
1,936 | def parseEquation ( self , inp ) : inp = MathService . _preprocess ( inp ) split = inp . split ( ' ' ) for i , w in enumerate ( split ) : if w in self . __unaryOperators__ : op = self . __unaryOperators__ [ w ] eq1 = ' ' . join ( split [ : i ] ) eq2 = ' ' . join ( split [ i + 1 : ] ) result = MathService . _applyUnary ... | Solves the equation specified by the input string . |
1,937 | 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 . |
1,938 | def get ( self , name = None ) : return self . app . commands . get ( name , self . plugin ) | Returns commands which can be filtered by name . |
1,939 | 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 . |
1,940 | def unregister ( self , command ) : if command not in self . _commands . keys ( ) : self . log . warning ( "Can not unregister command %s" % command ) else : del ( self . _click_root_command . commands [ command ] ) del ( self . _commands [ command ] ) self . log . debug ( "Command %s got unregistered" % command ) | Unregisters an existing command so that this command is no longer available on the command line interface . |
1,941 | 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 . |
1,942 | 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 . |
1,943 | 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 . |
1,944 | def b64decode ( s ) : 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 . |
1,945 | def raw_urlsafe_b64encode ( b ) : b = to_bytes ( b ) b = base64 . urlsafe_b64encode ( b ) b = b . rstrip ( b'=' ) return b | Base64 encode using URL - safe encoding with padding removed . |
1,946 | 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 |
1,947 | 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 |
1,948 | def _do_get ( self , uri , ** kwargs ) : scaleioapi_get_headers = { 'Content-type' : 'application/json' , 'Version' : '1.0' } self . logger . debug ( "_do_get() " + "{}/{}" . format ( self . _api_url , uri ) ) if kwargs : for key , value in kwargs . iteritems ( ) : if key == 'headers' : scaleio_get_headersvalue = value... | Convinient method for GET requests Returns http request status value from a POST request |
1,949 | 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 |
1,950 | 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 |
1,951 | 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 |
1,952 | 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 |
1,953 | async def dump_string ( writer , val ) : await dump_varint ( writer , len ( val ) ) await writer . awrite ( val ) | Binary string dump |
1,954 | 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 |
1,955 | 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 |
1,956 | 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 ) data_left = len ( self . iobj . buffer ) c_len = container_type . SIZ... | 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 . |
1,957 | def make_index_for ( package , index_dir , verbose = True ) : index_template = item_template = '<li><a href="{1}">{0}</a></li>' index_filename = os . path . join ( index_dir , "index.html" ) if not os . path . isdir ( index_dir ) : os . makedirs ( index_dir ) parts = [ ] for pkg_filename in package . files : pkg_name =... | Create an index . html for one package . |
1,958 | 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 . |
1,959 | 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 . |
1,960 | 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 . |
1,961 | 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 . |
1,962 | 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 . |
1,963 | 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 . |
1,964 | def register ( self , name , content , description = None ) : return self . __app . documents . register ( name , content , self . _plugin , description ) | Register a new document . |
1,965 | 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 . |
1,966 | 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 . |
1,967 | 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 . |
1,968 | 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 . |
1,969 | 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 . |
1,970 | 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 . |
1,971 | 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 |
1,972 | 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 . |
1,973 | 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 . |
1,974 | 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 . |
1,975 | 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 . |
1,976 | 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 . |
1,977 | 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_gene... | Plots orthogonal expression patterns . |
1,978 | 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 = s... | Plots gene expression patterns correlated with the input gene . |
1,979 | 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 . ob... | Wrapper for sklearn s t - SNE implementation . |
1,980 | 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 ) umap2d... | Wrapper for umap - learn . |
1,981 | 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 ] exce... | Display a scatter plot . |
1,982 | 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 == gen... | Display a gene s expressions . |
1,983 | 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 . |
1,984 | 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 . |
1,985 | 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 . |
1,986 | 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 . |
1,987 | def add ( self , action = None , subject = None , ** conditions ) : self . add_rule ( Rule ( True , action , subject , ** conditions ) ) | Add ability are allowed using two arguments . |
1,988 | def addnot ( self , action = None , subject = None , ** conditions ) : self . add_rule ( Rule ( False , action , subject , ** conditions ) ) | Defines an ability which cannot be done . |
1,989 | 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 |
1,990 | 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 |
1,991 | 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 |
1,992 | 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_mes... | Alias one or more actions into another one . |
1,993 | 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 . |
1,994 | 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 . |
1,995 | 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 . |
1,996 | 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 . |
1,997 | 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 . |
1,998 | 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 . |
1,999 | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.