idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
10,700
def on_presence ( self , session , presence ) : from_jid = presence . getFrom ( ) is_member = self . is_member ( from_jid . getStripped ( ) ) if is_member : member = self . get_member ( from_jid . getStripped ( ) ) else : member = None logger . info ( 'presence: from=%s is_member=%s type=%s' % ( from_jid , is_member , ...
Handles presence stanzas
10,701
def on_message ( self , con , event ) : msg_type = event . getType ( ) nick = event . getFrom ( ) . getResource ( ) from_jid = event . getFrom ( ) . getStripped ( ) body = event . getBody ( ) if msg_type == 'chat' and body is None : return logger . debug ( 'msg_type[%s] from[%s] nick[%s] body[%s]' % ( msg_type , from_j...
Handles messge stanzas
10,702
def activate ( self ) : d = dir ( self ) self . plugins = [ ] for key in d : if key . startswith ( "shell_activate_" ) : if self . echo : Console . ok ( "Shell Activate: {0}" . format ( key ) ) self . plugins . append ( key ) for key in d : if key . startswith ( "activate_" ) : if self . echo : Console . ok ( "Activate...
method to activate all activation methods in the shell and its plugins .
10,703
def do_help ( self , arg ) : if arg : try : func = getattr ( self , 'help_' + arg ) except AttributeError : try : doc = getattr ( self , 'do_' + arg ) . __doc__ if doc : self . stdout . write ( "%s\n" % str ( doc ) ) return except AttributeError : pass self . stdout . write ( "%s\n" % str ( self . nohelp % ( arg , ) ) ...
List available commands with help or detailed help with help cmd .
10,704
def _fetch_channels ( self ) : json = requests . get ( self . _channels_url ) . json ( ) self . _channels = { c [ 'channel' ] [ 'code' ] : c [ 'channel' ] [ 'name' ] for c in json [ 'channels' ] }
Retrieve Ziggo channel information .
10,705
def send_keys ( self , keys ) : try : sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) sock . settimeout ( self . _timeout ) sock . connect ( ( self . _ip , self . _port [ 'cmd' ] ) ) version_info = sock . recv ( 15 ) sock . send ( version_info ) sock . recv ( 2 ) sock . send ( bytes . fromhex ( '01' ...
Send keys to the device .
10,706
def make_echoicefield ( echoices , * args , klass_name = None , ** kwargs ) : assert issubclass ( echoices , EChoice ) value_type = echoices . __getvaluetype__ ( ) if value_type is str : cls_ = models . CharField elif value_type is int : cls_ = models . IntegerField elif value_type is float : cls_ = models . FloatField...
Construct a subclass of a derived models . Field specific to the type of the EChoice values .
10,707
def make_dummy ( instance , relations = { } , datetime_default = dt . strptime ( '1901-01-01' , '%Y-%m-%d' ) , varchar_default = "" , integer_default = 0 , numeric_default = 0.0 , * args , ** kwargs ) : init_data = { 'DATETIME' : datetime_default , 'VARCHAR' : varchar_default , 'INTEGER' : integer_default , 'NUMERIC(50...
Make an instance to look like an empty dummy .
10,708
def set_up_network ( self , genes : List [ Gene ] , gene_filter : bool = False , disease_associations : Optional [ Dict ] = None ) -> None : if gene_filter : self . filter_genes ( [ gene . entrez_id for gene in genes ] ) self . _add_vertex_attributes ( genes , disease_associations ) self . print_summary ( "Graph of all...
Set up the network .
10,709
def filter_genes ( self , relevant_entrez : list ) -> None : logger . info ( "In filter_genes()" ) irrelevant_genes = self . graph . vs . select ( name_notin = relevant_entrez ) self . graph . delete_vertices ( irrelevant_genes )
Filter out the genes that are not in list relevant_entrez .
10,710
def _add_vertex_attributes ( self , genes : List [ Gene ] , disease_associations : Optional [ dict ] = None ) -> None : self . _set_default_vertex_attributes ( ) self . _add_vertex_attributes_by_genes ( genes ) up_regulated = self . get_upregulated_genes ( ) down_regulated = self . get_downregulated_genes ( ) self . gr...
Add attributes to vertices .
10,711
def _set_default_vertex_attributes ( self ) -> None : self . graph . vs [ "l2fc" ] = 0 self . graph . vs [ "padj" ] = 0.5 self . graph . vs [ "symbol" ] = self . graph . vs [ "name" ] self . graph . vs [ "diff_expressed" ] = False self . graph . vs [ "up_regulated" ] = False self . graph . vs [ "down_regulated" ] = Fal...
Assign default values on attributes to all vertices .
10,712
def _add_vertex_attributes_by_genes ( self , genes : List [ Gene ] ) -> None : for gene in genes : try : vertex = self . graph . vs . find ( name = str ( gene . entrez_id ) ) . index self . graph . vs [ vertex ] [ 'l2fc' ] = gene . log2_fold_change self . graph . vs [ vertex ] [ 'symbol' ] = gene . symbol self . graph ...
Assign values to attributes on vertices .
10,713
def _add_disease_associations ( self , disease_associations : dict ) -> None : if disease_associations is not None : for target_id , disease_id_list in disease_associations . items ( ) : if target_id in self . graph . vs [ "name" ] : self . graph . vs . find ( name = target_id ) [ "associated_diseases" ] = disease_id_l...
Add disease association annotation to the network .
10,714
def get_upregulated_genes ( self ) -> VertexSeq : up_regulated = self . graph . vs . select ( self . _is_upregulated_gene ) logger . info ( f"No. of up-regulated genes after laying on network: {len(up_regulated)}" ) return up_regulated
Get genes that are up - regulated .
10,715
def get_downregulated_genes ( self ) -> VertexSeq : down_regulated = self . graph . vs . select ( self . _is_downregulated_gene ) logger . info ( f"No. of down-regulated genes after laying on network: {len(down_regulated)}" ) return down_regulated
Get genes that are down - regulated .
10,716
def print_summary ( self , heading : str ) -> None : logger . info ( heading ) logger . info ( "Number of nodes: {}" . format ( len ( self . graph . vs ) ) ) logger . info ( "Number of edges: {}" . format ( len ( self . graph . es ) ) )
Print the summary of a graph .
10,717
def get_differentially_expressed_genes ( self , diff_type : str ) -> VertexSeq : if diff_type == "up" : diff_expr = self . graph . vs . select ( up_regulated_eq = True ) elif diff_type == "down" : diff_expr = self . graph . vs . select ( down_regulated_eq = True ) else : diff_expr = self . graph . vs . select ( diff_ex...
Get the differentially expressed genes based on diff_type .
10,718
def write_adj_list ( self , path : str ) -> None : adj_list = self . get_adjlist ( ) with open ( path , mode = "w" ) as file : for i , line in enumerate ( adj_list ) : print ( i , * line , file = file )
Write the network as an adjacency list to a file .
10,719
def get_attribute_from_indices ( self , indices : list , attribute_name : str ) : return list ( np . array ( self . graph . vs [ attribute_name ] ) [ indices ] )
Get attribute values for the requested indices .
10,720
def read_headers ( rfile , hdict = None ) : if hdict is None : hdict = { } while True : line = rfile . readline ( ) if not line : raise ValueError ( "Illegal end of headers." ) if line == CRLF : break if not line . endswith ( CRLF ) : raise ValueError ( "HTTP requires CRLF terminators" ) if line [ 0 ] in ' \t' : v = li...
Read headers from the given stream into the given header dict . If hdict is None a new header dict is created . Returns the populated header dict . Headers which are repeated are folded together using a comma if their specification so dictates . This function raises ValueError when the read bytes violate the HTTP spec ...
10,721
def parse_request ( self ) : self . rfile = SizeCheckWrapper ( self . conn . rfile , self . server . max_request_header_size ) try : self . read_request_line ( ) except MaxSizeExceeded : self . simple_response ( "414 Request-URI Too Long" , "The Request-URI sent with the request exceeds the maximum " "allowed bytes." )...
Parse the next HTTP request start - line and message - headers .
10,722
def send_headers ( self ) : hkeys = [ key . lower ( ) for key , value in self . outheaders ] status = int ( self . status [ : 3 ] ) if status == 413 : self . close_connection = True elif "content-length" not in hkeys : if status < 200 or status in ( 204 , 205 , 304 ) : pass else : if ( self . response_protocol == 'HTTP...
Assert process and send the HTTP response message - headers . You must set self . status and self . outheaders before calling this .
10,723
def start ( self ) : for i in range ( self . min ) : self . _threads . append ( WorkerThread ( self . server ) ) for worker in self . _threads : worker . setName ( "CP Server " + worker . getName ( ) ) worker . start ( ) for worker in self . _threads : while not worker . ready : time . sleep ( .1 )
Start the pool of threads .
10,724
def fields ( self ) : return ( self . locus , self . offset_start , self . offset_end , self . alignment_key )
Fields that should be considered for our notion of object equality .
10,725
def bases ( self ) : sequence = self . alignment . query_sequence assert self . offset_end <= len ( sequence ) , "End offset=%d > sequence length=%d. CIGAR=%s. SEQUENCE=%s" % ( self . offset_end , len ( sequence ) , self . alignment . cigarstring , sequence ) return sequence [ self . offset_start : self . offset_end ]
The sequenced bases in the alignment that align to this locus in the genome as a string .
10,726
def min_base_quality ( self ) : try : return min ( self . base_qualities ) except ValueError : assert self . offset_start == self . offset_end adjacent_qualities = [ self . alignment . query_qualities [ offset ] for offset in [ self . offset_start - 1 , self . offset_start ] if 0 <= offset < len ( self . alignment . qu...
The minimum of the base qualities . In the case of a deletion in which case there are no bases in this PileupElement the minimum is taken over the sequenced bases immediately before and after the deletion .
10,727
def from_pysam_alignment ( locus , pileup_read ) : assert not pileup_read . is_refskip , ( "Can't create a PileupElement in a refskip (typically an intronic " "gap in an RNA alignment)" ) offset_start = None offset_end = len ( pileup_read . alignment . query_sequence ) for ( offset , position ) in pileup_read . alignme...
Factory function to create a new PileupElement from a pysam PileupRead .
10,728
def safe_request ( url , method = None , params = None , data = None , json = None , headers = None , allow_redirects = False , timeout = 30 , verify_ssl = True , ) : session = requests . Session ( ) kwargs = { } if json : kwargs [ 'json' ] = json if not headers : headers = { } headers . setdefault ( 'Content-Type' , '...
A slightly safer version of request .
10,729
def remote ( func ) : @ functools . wraps ( func ) def wrapper ( self , * args , ** kwargs ) : if self . mode == 'server' : return func ( self , * args , ** kwargs ) if not self . conn : self . connect ( ) self . conn . send ( 'CALL' , func . __name__ , args , kwargs ) cmd , payload = self . conn . recv ( ) if cmd == '...
Decorator to mark a function as invoking a remote procedure call . When invoked in server mode the function will be called ; when invoked in client mode an RPC will be initiated .
10,730
def send ( self , cmd , * payload ) : if not self . _sock : raise ConnectionClosed ( "Connection closed" ) msg = json . dumps ( dict ( cmd = cmd , payload = payload ) ) + '\n' try : self . _sock . sendall ( msg ) except socket . error : e_type , e_value , e_tb = sys . exc_info ( ) self . close ( ) raise e_type , e_valu...
Send a command message to the other end .
10,731
def _recvbuf_pop ( self ) : msg = self . _recvbuf . pop ( 0 ) if isinstance ( msg , Exception ) : raise msg return msg [ 'cmd' ] , msg [ 'payload' ]
Internal helper to pop a message off the receive buffer . If the message is an Exception that exception will be raised ; otherwise a tuple of command and payload will be returned .
10,732
def ping ( self ) : if not self . conn : self . connect ( ) self . conn . send ( 'PING' , time . time ( ) ) cmd , payload = self . conn . recv ( ) recv_ts = time . time ( ) if cmd != 'PONG' : raise Exception ( "Invalid response from server" ) return recv_ts - payload [ 0 ]
Ping the server . Returns the time interval in seconds required for the server to respond to the PING message .
10,733
def listen ( self ) : if self . mode and self . mode != 'server' : raise ValueError ( "%s is not in server mode" % self . __class__ . __name__ ) self . mode = 'server' serv = _create_server ( self . host , self . port ) err_thresh = 0 while True : try : sock , addr = serv . accept ( ) except Exception as exc : err_thre...
Listen for clients . This method causes the SimpleRPC object to switch to server mode . One thread will be created for each client .
10,734
def serve ( self , conn , addr , auth = False ) : try : while True : try : cmd , payload = conn . recv ( ) except ValueError as exc : conn . send ( 'ERR' , "Failed to parse command: %s" % str ( exc ) ) if not auth : return continue LOG . debug ( "Received command %r from %s port %s; payload: %r" % ( cmd , addr [ 0 ] , ...
Handle a single client .
10,735
def get_limits ( self ) : if not self . remote_limits : self . remote_limits = RemoteLimitData ( self . remote ) return self . remote_limits
Retrieve the LimitData object the middleware will use for getting the limits . This implementation returns a RemoteLimitData instance that can access the LimitData stored in the RemoteControlDaemon process .
10,736
def waitUpTo ( self , timeoutSeconds , pollInterval = DEFAULT_POLL_INTERVAL ) : i = 0 numWaits = timeoutSeconds / float ( pollInterval ) ret = self . poll ( ) if ret is None : while i < numWaits : time . sleep ( pollInterval ) ret = self . poll ( ) if ret is not None : break i += 1 return ret
Popen . waitUpTo - Wait up to a certain number of seconds for the process to end .
10,737
def waitOrTerminate ( self , timeoutSeconds , pollInterval = DEFAULT_POLL_INTERVAL , terminateToKillSeconds = SUBPROCESS2_DEFAULT_TERMINATE_TO_KILL_SECONDS ) : returnCode = self . waitUpTo ( timeoutSeconds , pollInterval ) actionTaken = SUBPROCESS2_PROCESS_COMPLETED if returnCode is None : if terminateToKillSeconds is ...
waitOrTerminate - Wait up to a certain number of seconds for the process to end .
10,738
def runInBackground ( self , pollInterval = .1 , encoding = False ) : from . BackgroundTask import BackgroundTaskThread taskInfo = BackgroundTaskInfo ( encoding ) thread = BackgroundTaskThread ( self , taskInfo , pollInterval , encoding ) thread . start ( ) return taskInfo
runInBackground - Create a background thread which will manage this process automatically read from streams and perform any cleanups
10,739
def setClients ( self , * args , ** kwargs ) : requests = 0 if 'fullDetails' in kwargs : fullDetails = kwargs [ 'fullDetails' ] kwargs . pop ( 'fullDetails' ) else : fullDetails = True clients = [ ] for m in self [ 'groupMembers' ] : try : client = self . mambuclientclass ( entid = m [ 'clientKey' ] , fullDetails = ful...
Adds the clients for this group to a clients field .
10,740
def setActivities ( self , * args , ** kwargs ) : def activityDate ( activity ) : try : return activity [ 'activity' ] [ 'timestamp' ] except KeyError as kerr : return None try : activities = self . mambuactivitiesclass ( groupId = self [ 'encodedKey' ] , * args , ** kwargs ) except AttributeError as ae : from . mambua...
Adds the activities for this group to a activities field .
10,741
def set_sensitivity ( self , sensitivity = DEFAULT_SENSITIVITY ) : if sensitivity < 31 : self . _mtreg = 31 elif sensitivity > 254 : self . _mtreg = 254 else : self . _mtreg = sensitivity self . _power_on ( ) self . _set_mode ( 0x40 | ( self . _mtreg >> 5 ) ) self . _set_mode ( 0x60 | ( self . _mtreg & 0x1f ) ) self . ...
Set the sensitivity value .
10,742
def _get_result ( self ) -> float : try : data = self . _bus . read_word_data ( self . _i2c_add , self . _mode ) self . _ok = True except OSError as exc : self . log_error ( "Bad reading in bus: %s" , exc ) self . _ok = False return - 1 count = data >> 8 | ( data & 0xff ) << 8 mode2coeff = 2 if self . _high_res else 1 ...
Return current measurement result in lx .
10,743
def _wait_for_result ( self ) : basetime = 0.018 if self . _low_res else 0.128 sleep ( basetime * ( self . _mtreg / 69.0 ) + self . _delay )
Wait for the sensor to be ready for measurement .
10,744
def update ( self ) : if not self . _continuous_sampling or self . _light_level < 0 or self . _operation_mode != self . _mode : self . _reset ( ) self . _set_mode ( self . _operation_mode ) self . _wait_for_result ( ) self . _light_level = self . _get_result ( ) if not self . _continuous_sampling : self . _power_down (...
Update the measured light level in lux .
10,745
def get_token ( user , secret , timestamp = None ) : timestamp = int ( timestamp or time ( ) ) secret = to_bytes ( secret ) key = '|' . join ( [ hashlib . sha1 ( secret ) . hexdigest ( ) , str ( user . id ) , get_hash_extract ( user . password ) , str ( getattr ( user , 'last_sign_in' , 0 ) ) , str ( timestamp ) , ] ) ...
Make a timestamped one - time - use token that can be used to identifying the user .
10,746
def __get_user ( self ) : storage = object . __getattribute__ ( self , '_LazyUser__storage' ) user = getattr ( self . __auth , 'get_user' ) ( ) setattr ( storage , self . __user_name , user ) return user
Return the real user object .
10,747
def _expand_filename ( self , line ) : newline = line path = os . getcwd ( ) if newline . startswith ( "." ) : newline = newline . replace ( "." , path , 1 ) newline = os . path . expanduser ( newline ) return newline
expands the filename if there is a . as leading path
10,748
def setCustomField ( mambuentity , customfield = "" , * args , ** kwargs ) : from . import mambuuser from . import mambuclient try : customFieldValue = mambuentity [ customfield ] datatype = [ l [ 'customField' ] [ 'dataType' ] for l in mambuentity [ mambuentity . customFieldName ] if ( l [ 'name' ] == customfield or l...
Modifies the customField field for the given object with something related to the value of the given field .
10,749
def serializeFields ( data ) : if isinstance ( data , MambuStruct ) : return data . serializeStruct ( ) try : it = iter ( data ) except TypeError as terr : return unicode ( data ) if type ( it ) == type ( iter ( [ ] ) ) : l = [ ] for e in it : l . append ( MambuStruct . serializeFields ( e ) ) return l elif type ( it )...
Turns every attribute of the Mambu object in to a string representation .
10,750
def init ( self , attrs = { } , * args , ** kwargs ) : self . attrs = attrs self . preprocess ( ) self . convertDict2Attrs ( * args , ** kwargs ) self . postprocess ( ) try : for meth in kwargs [ 'methods' ] : try : getattr ( self , meth ) ( ) except Exception : pass except Exception : pass try : for propname , propval...
Default initialization from a dictionary responded by Mambu
10,751
def connect ( self , * args , ** kwargs ) : from copy import deepcopy if args : self . __args = deepcopy ( args ) if kwargs : for k , v in kwargs . items ( ) : self . __kwargs [ k ] = deepcopy ( v ) jsresp = { } if not self . __urlfunc : return offset = self . __offset window = True jsresp = { } while window : if not s...
Connect to Mambu make the request to the REST API .
10,752
def convertDict2Attrs ( self , * args , ** kwargs ) : constantFields = [ 'id' , 'groupName' , 'name' , 'homePhone' , 'mobilePhone1' , 'phoneNumber' , 'postcode' , 'emailAddress' ] def convierte ( data ) : try : it = iter ( data ) if type ( it ) == type ( iter ( { } ) ) : d = { } for k in it : if k in constantFields : d...
Each element on the atttrs attribute gest converted to a proper python object depending on type .
10,753
def util_dateFormat ( self , field , formato = None ) : if not formato : try : formato = self . __formatoFecha except AttributeError : formato = "%Y-%m-%dT%H:%M:%S+0000" return datetime . strptime ( datetime . strptime ( field , "%Y-%m-%dT%H:%M:%S+0000" ) . strftime ( formato ) , formato )
Converts a datetime field to a datetime using some specified format .
10,754
def create ( self , data , * args , ** kwargs ) : if self . create . __func__ . __module__ != self . __module__ : raise Exception ( "Child method not implemented" ) self . _MambuStruct__method = "POST" self . _MambuStruct__data = data self . connect ( * args , ** kwargs ) self . _MambuStruct__method = "GET" self . _Mam...
Creates an entity in Mambu
10,755
def make ( self , cmd_args , db_args ) : with NamedTemporaryFile ( delete = True ) as f : format_file = f . name + '.bcp-format' format_args = cmd_args + [ 'format' , NULL_FILE , '-c' , '-f' , format_file , '-t,' ] + db_args _run_cmd ( format_args ) self . load ( format_file ) return format_file
Runs bcp FORMAT command to create a format file that will assist in creating the bulk data file
10,756
def load ( self , filename = None ) : fields = [ ] with open ( filename , 'r' ) as f : format_data = f . read ( ) . strip ( ) lines = format_data . split ( '\n' ) self . _sql_version = lines . pop ( 0 ) self . _num_fields = int ( lines . pop ( 0 ) ) for line in lines : line = re . sub ( ' +' , ' ' , line . strip ( ) ) ...
Reads a non - XML bcp FORMAT file and parses it into fields list used for creating bulk data file
10,757
def retrieve_content ( self ) : path = self . _construct_path_to_source_content ( ) res = self . _http . get ( path ) self . _populated_fields [ 'content' ] = res [ 'content' ] return res [ 'content' ]
Retrieve the content of a resource .
10,758
def _update ( self , ** kwargs ) : if 'content' in kwargs : content = kwargs . pop ( 'content' ) path = self . _construct_path_to_source_content ( ) self . _http . put ( path , json . dumps ( { 'content' : content } ) ) super ( Resource , self ) . _update ( ** kwargs )
Use separate URL for updating the source file .
10,759
def all ( ) : dir ( ) cmd3 ( ) banner ( "CLEAN PREVIOUS CLOUDMESH INSTALLS" ) r = int ( local ( "pip freeze |fgrep cloudmesh | wc -l" , capture = True ) ) while r > 0 : local ( 'echo "y\n" | pip uninstall cloudmesh' ) r = int ( local ( "pip freeze |fgrep cloudmesh | wc -l" , capture = True ) )
clean the dis and uninstall cloudmesh
10,760
def find ( cls , text ) : if isinstance ( cls . pattern , string_types ) : cls . pattern = re . compile ( cls . pattern ) return cls . pattern . finditer ( text )
This method should return an iterable containing matches of this element .
10,761
def main ( ) : parser = argparse . ArgumentParser ( description = 'Monitor your crons with cronitor.io & sentry.io' , epilog = 'https://github.com/youversion/crony' , prog = 'crony' ) parser . add_argument ( '-c' , '--cronitor' , action = 'store' , help = 'Cronitor link identifier. This can be found in your Cronitor un...
Entry point for running crony .
10,762
def cronitor ( self ) : url = f'https://cronitor.link/{self.opts.cronitor}/{{}}' try : run_url = url . format ( 'run' ) self . logger . debug ( f'Pinging {run_url}' ) requests . get ( run_url , timeout = self . opts . timeout ) except requests . exceptions . RequestException as e : self . logger . exception ( e ) outpu...
Wrap run with requests to cronitor .
10,763
def load_config ( self , custom_config ) : self . config = configparser . ConfigParser ( ) if custom_config : self . config . read ( custom_config ) return f'Loading config from file {custom_config}.' home = os . path . expanduser ( '~{}' . format ( getpass . getuser ( ) ) ) home_conf_file = os . path . join ( home , '...
Attempt to load config from file .
10,764
def log ( self , output , exit_status ) : if exit_status != 0 : self . logger . error ( f'Error running command! Exit status: {exit_status}, {output}' ) return exit_status
Log given CompletedProcess and return exit status code .
10,765
def run ( self ) : self . logger . debug ( f'Running command: {self.cmd}' ) def execute ( cmd ) : output = "" popen = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , universal_newlines = True , shell = True ) for stdout_line in iter ( popen . stdout . readline , "" ) : stdout_line...
Run command and report errors to Sentry .
10,766
def setup_dir ( self ) : cd = self . opts . cd or self . config [ 'crony' ] . get ( 'directory' ) if cd : self . logger . debug ( f'Adding cd to {cd}' ) self . cmd = f'cd {cd} && {self.cmd}'
Change directory for script if necessary .
10,767
def setup_logging ( self ) : date_format = '%Y-%m-%dT%H:%M:%S' log_format = '%(asctime)s %(levelname)s: %(message)s' if self . opts . verbose : lvl = logging . DEBUG else : lvl = logging . INFO logging . getLogger ( 'requests' ) . setLevel ( 'WARNING' ) self . logger . setLevel ( lvl ) stdout = logging . StreamHandler ...
Setup python logging handler .
10,768
def setup_path ( self ) : path = self . opts . path or self . config [ 'crony' ] . get ( 'path' ) if path : self . logger . debug ( f'Adding {path} to PATH environment variable' ) self . cmd = f'export PATH={path}:$PATH && {self.cmd}'
Setup PATH env var if necessary .
10,769
def setup_venv ( self ) : venv = self . opts . venv if not venv : venv = os . environ . get ( 'CRONY_VENV' ) if not venv and self . config [ 'crony' ] : venv = self . config [ 'crony' ] . get ( 'venv' ) if venv : if not venv . endswith ( 'activate' ) : add_path = os . path . join ( 'bin' , 'activate' ) self . logger . ...
Setup virtualenv if necessary .
10,770
def get_repos ( path ) : p = str ( path ) ret = [ ] if not os . path . exists ( p ) : return ret for d in os . listdir ( p ) : pd = os . path . join ( p , d ) if os . path . exists ( pd ) and is_repo ( pd ) : ret . append ( Local ( pd ) ) return ret
Returns list of found branches .
10,771
def get_repo_parent ( path ) : if is_repo ( path ) : return Local ( path ) elif not os . path . isdir ( path ) : _rel = '' while path and path != '/' : if is_repo ( path ) : return Local ( path ) else : _rel = os . path . join ( os . path . basename ( path ) , _rel ) path = os . path . dirname ( path ) return path
Returns parent repo or input path if none found .
10,772
def setVersion ( self , version ) : try : sha = self . versions ( version ) . commit . sha self . git . reset ( "--hard" , sha ) except Exception , e : raise RepoError ( e )
Checkout a version of the repo .
10,773
def _commits ( self , head = 'HEAD' ) : pending_commits = [ head ] history = [ ] while pending_commits != [ ] : head = pending_commits . pop ( 0 ) try : commit = self [ head ] except KeyError : raise KeyError ( head ) if type ( commit ) != Commit : raise TypeError ( commit ) if commit in history : continue i = 0 for kn...
Returns a list of the commits reachable from head .
10,774
def versions ( self , version = None ) : try : versions = [ Version ( self , c ) for c in self . _commits ( ) ] except Exception , e : log . debug ( 'No versions exist' ) return [ ] if version is not None and versions : try : versions = versions [ version ] except IndexError : raise VersionError ( 'Version %s does not ...
List of Versions of this repository .
10,775
def setDescription ( self , desc = 'No description' ) : try : self . _put_named_file ( 'description' , desc ) except Exception , e : raise RepoError ( e )
sets repository description
10,776
def new ( self , path , desc = None , bare = True ) : if os . path . exists ( path ) : raise RepoError ( 'Path already exists: %s' % path ) try : os . mkdir ( path ) if bare : Repo . init_bare ( path ) else : Repo . init ( path ) repo = Local ( path ) if desc : repo . setDescription ( desc ) version = repo . addVersion...
Create a new bare repo . Local instance .
10,777
def branch ( self , name , desc = None ) : return Local . new ( path = os . path . join ( self . path , name ) , desc = desc , bare = True )
Create a branch of this repo at name .
10,778
def addItem ( self , item , message = None ) : if message is None : message = 'Adding item %s' % item . path try : v = Version . new ( repo = self ) v . addItem ( item ) v . save ( message ) except VersionError , e : raise RepoError ( e )
add a new Item class object
10,779
def items ( self , path = None , version = None ) : if version is None : version = - 1 items = { } for item in self . versions ( version ) . items ( ) : items [ item . path ] = item parent = self . parent while parent : for item in parent . items ( path = path ) : if item . path not in items . keys ( ) : items [ item ....
Returns a list of items .
10,780
async def set_reply_markup ( msg : Dict , request : 'Request' , stack : 'Stack' ) -> None : from bernard . platforms . telegram . layers import InlineKeyboard , ReplyKeyboard , ReplyKeyboardRemove try : keyboard = stack . get_layer ( InlineKeyboard ) except KeyError : pass else : msg [ 'reply_markup' ] = await keyboard...
Add the reply markup to a message from the layers
10,781
def split_locale ( locale : Text ) -> Tuple [ Text , Optional [ Text ] ] : items = re . split ( r'[_\-]' , locale . lower ( ) , 1 ) try : return items [ 0 ] , items [ 1 ] except IndexError : return items [ 0 ] , None
Decompose the locale into a normalized tuple .
10,782
def compare_locales ( a , b ) : if a is None or b is None : if a == b : return 2 else : return 0 a = split_locale ( a ) b = split_locale ( b ) if a == b : return 2 elif a [ 0 ] == b [ 0 ] : return 1 else : return 0
Compares two locales to find the level of compatibility
10,783
def list_locales ( self ) -> List [ Optional [ Text ] ] : locales = list ( self . dict . keys ( ) ) if not locales : locales . append ( None ) return locales
Returns the list of available locales . The first locale is the default locale to be used . If no locales are known then None will be the first item .
10,784
def choose_locale ( self , locale : Text ) -> Text : if locale not in self . _choice_cache : locales = self . list_locales ( ) best_choice = locales [ 0 ] best_level = 0 for candidate in locales : cmp = compare_locales ( locale , candidate ) if cmp > best_level : best_choice = candidate best_level = cmp self . _choice_...
Returns the best matching locale in what is available .
10,785
def update ( self , new_data : Dict [ Text , Dict [ Text , Text ] ] ) : for locale , data in new_data . items ( ) : if locale not in self . dict : self . dict [ locale ] = { } self . dict [ locale ] . update ( data )
Receive an update from a loader .
10,786
async def _make_url ( self , url : Text , request : 'Request' ) -> Text : if self . sign_webview : return await request . sign_url ( url ) return url
Signs the URL if needed
10,787
def is_sharable ( self ) : if self . buttons : return ( all ( b . is_sharable ( ) for b in self . buttons ) and self . default_action and self . default_action . is_sharable ( ) )
Make sure that nothing inside blocks sharing .
10,788
def check_bounds_variables ( self , dataset ) : recommended_ctx = TestCtx ( BaseCheck . MEDIUM , 'Recommended variables to describe grid boundaries' ) bounds_map = { 'lat_bounds' : { 'units' : 'degrees_north' , 'comment' : 'latitude values at the north and south bounds of each pixel.' } , 'lon_bounds' : { 'units' : 'de...
Checks the grid boundary variables .
10,789
def geocode ( self , string , bounds = None , region = None , language = None , sensor = False ) : if isinstance ( string , unicode ) : string = string . encode ( 'utf-8' ) params = { 'address' : self . format_string % string , 'sensor' : str ( sensor ) . lower ( ) } if bounds : params [ 'bounds' ] = bounds if region :...
Geocode an address . Pls refer to the Google Maps Web API for the details of the parameters
10,790
def reverse ( self , point , language = None , sensor = False ) : params = { 'latlng' : point , 'sensor' : str ( sensor ) . lower ( ) } if language : params [ 'language' ] = language if not self . premier : url = self . get_url ( params ) else : url = self . get_signed_url ( params ) return self . GetService_url ( url ...
Reverse geocode a point . Pls refer to the Google Maps Web API for the details of the parameters
10,791
def GetDirections ( self , origin , destination , sensor = False , mode = None , waypoints = None , alternatives = None , avoid = None , language = None , units = None , region = None , departure_time = None , arrival_time = None ) : params = { 'origin' : origin , 'destination' : destination , 'sensor' : str ( sensor )...
Get Directions Service Pls refer to the Google Maps Web API for the details of the remained parameters
10,792
def get ( self ) : self . _cast = type ( [ ] ) source_value = os . getenv ( self . env_name ) if source_value is None : os . environ [ self . env_name ] = json . dumps ( self . default ) return self . default try : val = json . loads ( source_value ) except JSONDecodeError as e : click . secho ( str ( e ) , err = True ...
convert json env variable if set to list
10,793
def parse_ppi_graph ( path : str , min_edge_weight : float = 0.0 ) -> Graph : logger . info ( "In parse_ppi_graph()" ) graph = igraph . read ( os . path . expanduser ( path ) , format = "ncol" , directed = False , names = True ) graph . delete_edges ( graph . es . select ( weight_lt = min_edge_weight ) ) graph . delete...
Build an undirected graph of gene interactions from edgelist file .
10,794
def parse_excel ( file_path : str , entrez_id_header , log_fold_change_header , adjusted_p_value_header , entrez_delimiter , base_mean_header = None ) -> List [ Gene ] : logger . info ( "In parse_excel()" ) df = pd . read_excel ( file_path ) return handle_dataframe ( df , entrez_id_name = entrez_id_header , log2_fold_c...
Read an excel file on differential expression values as Gene objects .
10,795
def parse_csv ( file_path : str , entrez_id_header , log_fold_change_header , adjusted_p_value_header , entrez_delimiter , base_mean_header = None , sep = "," ) -> List [ Gene ] : logger . info ( "In parse_csv()" ) df = pd . read_csv ( file_path , sep = sep ) return handle_dataframe ( df , entrez_id_name = entrez_id_he...
Read a csv file on differential expression values as Gene objects .
10,796
def handle_dataframe ( df : pd . DataFrame , entrez_id_name , log2_fold_change_name , adjusted_p_value_name , entrez_delimiter , base_mean = None , ) -> List [ Gene ] : logger . info ( "In _handle_df()" ) if base_mean is not None and base_mean in df . columns : df = df [ pd . notnull ( df [ base_mean ] ) ] df = df [ pd...
Convert data frame on differential expression values as Gene objects .
10,797
def parse_gene_list ( path : str , graph : Graph , anno_type : str = "name" ) -> list : genes = pd . read_csv ( path , header = None ) [ 0 ] . tolist ( ) genes = [ str ( int ( gene ) ) for gene in genes ] ind = [ ] if anno_type == "name" : ind = graph . vs . select ( name_in = genes ) . indices elif anno_type == "symbo...
Parse a list of genes and return them if they are in the network .
10,798
def parse_disease_ids ( path : str ) : if os . path . isdir ( path ) or not os . path . exists ( path ) : logger . info ( "Couldn't find the disease identifiers file. Returning empty list." ) return [ ] df = pd . read_csv ( path , names = [ "ID" ] ) return set ( df [ "ID" ] . tolist ( ) )
Parse the disease identifier file .
10,799
def parse_disease_associations ( path : str , excluded_disease_ids : set ) : if os . path . isdir ( path ) or not os . path . exists ( path ) : logger . info ( "Couldn't find the disease associations file. Returning empty list." ) return { } disease_associations = defaultdict ( list ) with open ( path ) as input_file :...
Parse the disease - drug target associations file .