signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def pop ( self ) : """Pop an entry off the stack and make its node a child of the last ."""
dfa , state , node = self . stack . pop ( ) if self . stack : self . stack [ - 1 ] [ 2 ] . children . append ( node ) else : self . root = node
def create_track ( self , href = None , media_url = None , label = None , audio_channel = None ) : """Add a new track to a bundle . Note that the total number of allowable tracks is limited . See the API documentation for details . ' href ' the relative href to the tracks list . May not be None . ' media _ ...
# Argument error checking . assert href is not None assert media_url is not None # Prepare the data we ' re going to write . data = None fields = { } fields [ 'media_url' ] = media_url if label is not None : fields [ 'label' ] = label if audio_channel is not None : fields [ 'audio_channel' ] = audio_channel if ...
def get_claims_for ( self , user_id , requested_claims ) : # type : ( str , Mapping [ str , Optional [ Mapping [ str , Union [ str , List [ str ] ] ] ] ) - > Dict [ str , Union [ str , List [ str ] ] ] """Filter the userinfo based on which claims where requested . : param user _ id : user identifier : param req...
userinfo = self . _db [ user_id ] claims = { claim : userinfo [ claim ] for claim in requested_claims if claim in userinfo } return claims
def Emulation_setEmulatedMedia ( self , media ) : """Function path : Emulation . setEmulatedMedia Domain : Emulation Method name : setEmulatedMedia Parameters : Required arguments : ' media ' ( type : string ) - > Media type to emulate . Empty string disables the override . No return value . Descripti...
assert isinstance ( media , ( str , ) ) , "Argument 'media' must be of type '['str']'. Received type: '%s'" % type ( media ) subdom_funcs = self . synchronous_command ( 'Emulation.setEmulatedMedia' , media = media ) return subdom_funcs
def concat_cols ( df1 , df2 , idx_col , df1_cols , df2_cols , df1_suffix , df2_suffix , wc_cols = [ ] , suffix_all = False ) : """Concatenates two pandas tables : param df1 : dataframe 1 : param df2 : dataframe 2 : param idx _ col : column name which will be used as a common index"""
df1 = df1 . set_index ( idx_col ) df2 = df2 . set_index ( idx_col ) if not len ( wc_cols ) == 0 : for wc in wc_cols : df1_cols = df1_cols + [ c for c in df1 . columns if wc in c ] df2_cols = df2_cols + [ c for c in df2 . columns if wc in c ] combo = pd . concat ( [ df1 . loc [ : , df1_cols ] , df2 ....
def _write_comparison_plot_table ( spid , models , options , core_results , fit_results ) : """Notes Only applies to analysis using functions from empirical in which models are also given ."""
# TODO : Clean up sorting , may not work if SAR x out of order , e . g . is_curve = 'x' in core_results [ 0 ] [ 1 ] df = core_results [ spid ] [ 1 ] df . rename ( columns = { 'y' : 'empirical' } , inplace = True ) # If distribution , need to sort values so will match sorted rank in fits if not is_curve : x = np . a...
def sasdata2dataframe ( self , table : str , libref : str = '' , dsopts : dict = None , rowsep : str = '\x01' , colsep : str = '\x02' , ** kwargs ) -> '<Pandas Data Frame object>' : """This method exports the SAS Data Set to a Pandas Data Frame , returning the Data Frame object . table - the name of the SAS Data ...
dsopts = dsopts if dsopts is not None else { } method = kwargs . pop ( 'method' , None ) if method and method . lower ( ) == 'csv' : return self . sasdata2dataframeCSV ( table , libref , dsopts , ** kwargs ) logf = '' logn = self . _logcnt ( ) logcodei = "%put E3969440A681A24088859985" + logn + ";" logcodeo = "\nE3...
def _get_baseline_string_from_file ( filename ) : # pragma : no cover """Breaking this function up for mockability ."""
try : with open ( filename ) as f : return f . read ( ) except IOError : log . error ( 'Unable to open baseline file: {}\n' 'Please create it via\n' ' `detect-secrets scan > {}`\n' . format ( filename , filename ) , ) raise
def update_pidfile ( pidfile ) : """Update pidfile . Notice : We should call this function only after we have successfully acquired a lock and never before . It exits main program if it fails to parse and / or write pidfile . Arguments : pidfile ( str ) : pidfile to update"""
try : with open ( pidfile , mode = 'r' ) as _file : pid = _file . read ( 1024 ) . rstrip ( ) try : pid = int ( pid ) except ValueError : print ( "cleaning stale pidfile with invalid data:'{}'" . format ( pid ) ) write_pid ( pidfile ) else : if running ( pid ) : # ...
def fromPandas ( cls , df ) : """Create a : class : ` ~ amplpy . DataFrame ` from a pandas DataFrame ."""
assert pd is not None if isinstance ( df , pd . Series ) : df = pd . DataFrame ( df ) else : assert isinstance ( df , pd . DataFrame ) keys = [ key if isinstance ( key , tuple ) else ( key , ) for key in df . index . tolist ( ) ] index = [ ( 'index{}' . format ( i ) , cindex ) for i , cindex in enumerate ( zip ...
def parse_json ( path ) : # type : ( str ) - > List [ FunctionInfo ] """Deserialize a JSON file containing runtime collected types . The input JSON is expected to to have a list of RawEntry items ."""
with open ( path ) as f : data = json . load ( f ) # type : List [ RawEntry ] result = [ ] def assert_type ( value , typ ) : # type : ( object , type ) - > None assert isinstance ( value , typ ) , '%s: Unexpected type %r' % ( path , type ( value ) . __name__ ) def assert_dict_item ( dictionary , key , typ )...
def get_rgbval ( self , index ) : """Return a tuple of ( R , G , B ) values in the 0 - maxc range associated mapped by the value of ` index ` ."""
assert ( index >= 0 ) and ( index <= self . maxc ) , RGBMapError ( "Index must be in range 0-%d !" % ( self . maxc ) ) index = self . sarr [ index ] . clip ( 0 , self . maxc ) return ( self . arr [ 0 ] [ index ] , self . arr [ 1 ] [ index ] , self . arr [ 2 ] [ index ] )
def combine_multiple_callers ( samples ) : """Collapse together variant calls from multiple approaches into single data item with ` variants ` ."""
by_bam = collections . OrderedDict ( ) for data in ( x [ 0 ] for x in samples ) : work_bam = tz . get_in ( ( "combine" , "work_bam" , "out" ) , data , data . get ( "align_bam" ) ) # For pre - computed VCF inputs , we don ' t have BAM files if not work_bam : work_bam = dd . get_sample_name ( data ) ...
def _Rforce ( self , R , z , phi = 0. , t = 0. ) : """NAME : Rforce PURPOSE : evaluate radial force K _ R ( R , z ) INPUT : R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT : K _ R ( R , z ) HISTORY : 2012-12-27 - Written - Bovy ( IAS )"""
if self . _new : # if R > 6 . : return self . _ kp ( R , z ) if nu . fabs ( z ) < 10. ** - 6. : y = 0.5 * self . _alpha * R return - 2. * nu . pi * y * ( special . i0 ( y ) * special . k0 ( y ) - special . i1 ( y ) * special . k1 ( y ) ) kalphamax1 = R ks1 = kalphamax1 * 0.5 * ( self . _glx ...
def publish_workflow_status ( self , workflow_uuid , status , logs = '' , message = None ) : """Publish workflow status using the configured . : param workflow _ uudid : String which represents the workflow UUID . : param status : Integer which represents the status of the workflow , this is defined in the ` ...
msg = { "workflow_uuid" : workflow_uuid , "logs" : logs , "status" : status , "message" : message } self . _publish ( msg )
def vtas2cas ( tas , h ) : """tas2cas conversion both m / s"""
p , rho , T = vatmos ( h ) qdyn = p * ( ( 1. + rho * tas * tas / ( 7. * p ) ) ** 3.5 - 1. ) cas = np . sqrt ( 7. * p0 / rho0 * ( ( qdyn / p0 + 1. ) ** ( 2. / 7. ) - 1. ) ) # cope with negative speed cas = np . where ( tas < 0 , - 1 * cas , cas ) return cas
def get_keyboard_mapping_unchecked ( conn ) : """Return an unchecked keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment . : rtype : xcb . xproto . GetKeyboardMappingCookie"""
mn , mx = get_min_max_keycode ( ) return conn . core . GetKeyboardMappingUnchecked ( mn , mx - mn + 1 )
def num_dml_affected_rows ( self ) : """Return the number of DML rows affected by the job . See : https : / / cloud . google . com / bigquery / docs / reference / rest / v2 / jobs # statistics . query . numDmlAffectedRows : rtype : int or None : returns : number of DML rows affected by the job , or None if ...
result = self . _job_statistics ( ) . get ( "numDmlAffectedRows" ) if result is not None : result = int ( result ) return result
def or_ ( a , b ) : """Combines two : any : ` Filters < Filter > ` with an " or " operation , matching any results that match any of the given filters . : param a : The first filter to consider . : type a : Filter : param b : The second filter to consider . : type b : Filter : returns : A filter that ma...
if not isinstance ( a , Filter ) or not isinstance ( b , Filter ) : raise TypeError return a . __or__ ( b )
def _initialize_global_state ( self , redis_address , redis_password = None , timeout = 20 ) : """Initialize the GlobalState object by connecting to Redis . It ' s possible that certain keys in Redis may not have been fully populated yet . In this case , we will retry this method until they have been populate...
self . redis_client = services . create_redis_client ( redis_address , redis_password ) start_time = time . time ( ) num_redis_shards = None redis_shard_addresses = [ ] while time . time ( ) - start_time < timeout : # Attempt to get the number of Redis shards . num_redis_shards = self . redis_client . get ( "NumRed...
def switch_to_plugin ( self ) : """Switch to plugin ."""
# Unmaxizime currently maximized plugin if ( self . main . last_plugin is not None and self . main . last_plugin . ismaximized and self . main . last_plugin is not self ) : self . main . maximize_dockwidget ( ) # Show plugin only if it was already visible if self . get_option ( 'visible_if_project_open' ) : if ...
def set_key ( self , key , modifiers : typing . List [ Key ] = None ) : """This is called when the user successfully finishes recording a key combination ."""
if modifiers is None : modifiers = [ ] # type : typing . List [ Key ] if key in self . KEY_MAP : key = self . KEY_MAP [ key ] self . _setKeyLabel ( key ) self . key = key self . controlButton . setChecked ( Key . CONTROL in modifiers ) self . altButton . setChecked ( Key . ALT in modifiers ) self . shiftBut...
def _expand_hydrate_ ( hydrate_pos , formula_string ) : """Handles the expansion of hydrate portions of a chemical formula , and expands out the coefficent to all elements : param hydrate _ pos : the index in the formula _ string of the · symbol : param formula _ string : the unexpanded formula string : retur...
hydrate = formula_string [ hydrate_pos + 1 : ] hydrate_string = "" multiplier = float ( re . search ( r'^[\d\.]+' , hydrate ) . group ( ) ) element_array = re . findall ( '[A-Z][^A-Z]*' , hydrate ) for e in element_array : occurance_array = re . findall ( '[0-9][^0-9]*' , e ) if len ( occurance_array ) == 0 : ...
def processDatasetBlocks ( self , url , conn , inputdataset , order_counter ) : """Utility function , that comapares blocks of a dataset at source and dst and returns an ordered list of blocks not already at dst for migration"""
ordered_dict = { } srcblks = self . getSrcBlocks ( url , dataset = inputdataset ) if len ( srcblks ) < 0 : e = "DBSMigration: No blocks in the required dataset %s found at source %s." % ( inputdataset , url ) dbsExceptionHandler ( 'dbsException-invalid-input2' , e , self . logger . exception , e ) dstblks = sel...
def do_ams_sto_put ( endpoint , body , content_length ) : '''Do a PUT request to the Azure Storage API and return JSON . Args : endpoint ( str ) : Azure Media Services Initial Endpoint . body ( str ) : Azure Media Services Content Body . content _ length ( str ) : Content _ length . Returns : HTTP respo...
headers = { "Accept" : json_acceptformat , "Accept-Charset" : charset , "x-ms-blob-type" : "BlockBlob" , "x-ms-meta-m1" : "v1" , "x-ms-meta-m2" : "v2" , "x-ms-version" : "2015-02-21" , "Content-Length" : str ( content_length ) } return requests . put ( endpoint , data = body , headers = headers )
def _create_plugin ( self , config ) : """Creates a plugin from its config . Params : config : plugin configuration as read by ait . config Returns : plugin : a Plugin Raises : ValueError : if any of the required config values are missing"""
if config is None : raise ValueError ( 'No plugin config to create plugin from.' ) name = config . pop ( 'name' , None ) if name is None : raise ( cfg . AitConfigMissing ( 'plugin name' ) ) # TODO I don ' t think we actually care about this being unique ? Left over from # previous conversations about stuff ? mo...
def replace_uri ( self , src , dest ) : """Replace a uri reference everywhere it appears in the graph with another one . It could appear as the subject , predicate , or object of a statement , so for each position loop through each statement that uses the reference in that position , remove the old statement ...
# NB : The hypothetical statement < src > < src > < src > will be removed # and re - added several times . The subject block will remove it and # add < dest > < src > < src > . The predicate block will remove that and # add < dest > < dest > < src > . The object block will then remove that # and add < dest > < dest > <...
def _process_m2m_through ( self , obj , action ) : """Process custom M2M through model actions ."""
source = getattr ( obj , self . field . rel . field . m2m_field_name ( ) ) target = getattr ( obj , self . field . rel . field . m2m_reverse_field_name ( ) ) pk_set = set ( ) if target : pk_set . add ( target . pk ) self . process_m2m ( source , pk_set , action = action , reverse = False , cache_key = obj )
def update ( self , module_name = None ) : """Update a module . If module _ name is supplied the module of that name is updated . Otherwise the module calling is updated ."""
if not module_name : return self . _module . force_update ( ) else : module_info = self . _get_module_info ( module_name ) if module_info : module_info [ "module" ] . force_update ( )
def execute ( self , command , blocking = True , exec_create_kwargs = None , exec_start_kwargs = None ) : """Execute a command in this container - - the container needs to be running . If the command fails , a ConuException is thrown . This is a blocking call by default and writes output of the command to logge...
logger . info ( "running command %s" , command ) exec_create_kwargs = exec_create_kwargs or { } exec_start_kwargs = exec_start_kwargs or { } exec_start_kwargs [ "stream" ] = True # we want stream no matter what exec_i = self . d . exec_create ( self . get_id ( ) , command , ** exec_create_kwargs ) output = self . d . e...
def guess_language ( file_name , local_file ) : """Guess lexer and language for a file . Returns a tuple of ( language _ str , lexer _ obj ) ."""
lexer = None language = get_language_from_extension ( file_name ) if language : lexer = get_lexer ( language ) else : lexer = smart_guess_lexer ( file_name , local_file ) if lexer : language = u ( lexer . name ) return language , lexer
def _get_caller_globals_and_locals ( ) : """Returns the globals and locals of the calling frame . Is there an alternative to frame hacking here ?"""
caller_frame = inspect . stack ( ) [ 2 ] myglobals = caller_frame [ 0 ] . f_globals mylocals = caller_frame [ 0 ] . f_locals return myglobals , mylocals
def from_raw_profile_info ( cls , raw_profile , profile_name , cli_vars , user_cfg = None , target_override = None , threads_override = None ) : """Create a profile from its raw profile information . ( this is an intermediate step , mostly useful for unit testing ) : param raw _ profile dict : The profile data ...
# user _ cfg is not rendered since it only contains booleans . # TODO : should it be , and the values coerced to bool ? target_name , profile_data = cls . render_profile ( raw_profile , profile_name , target_override , cli_vars ) # valid connections never include the number of threads , but it ' s # stored on a per - c...
def setParams ( self , bend_length , bend_field , drift_length , gamma ) : """set chicane parameters : param bend _ length : bend length , [ m ] : param bend _ field : bend field , [ T ] : param drift _ length : drift length , [ m ] , list : param gamma : electron energy , gamma : return : None"""
if None in ( bend_length , bend_field , drift_length , gamma ) : print ( "warning: 'bend_length', 'bend_field', 'drift_length', 'gamma' should be positive float numbers." ) self . mflag = False else : self . _setDriftList ( drift_length ) self . gamma = gamma self . bend_length = bend_length sel...
def detect_regions ( bam_in , bed_file , out_dir , prefix ) : """Detect regions using first CoRaL module"""
bed_file = _reorder_columns ( bed_file ) counts_reads_cmd = ( "coverageBed -s -counts -b {bam_in} " "-a {bed_file} | sort -k4,4 " "> {out_dir}/loci.cov" ) # with tx _ tmpdir ( ) as temp _ dir : with utils . chdir ( out_dir ) : run ( counts_reads_cmd . format ( min_trimmed_read_len = min_trimmed_read_len , max_trimm...
def _remove_extension_for_non_raw_file ( self , name ) : """Implemented as image and video files ' Cloudinary public id shouldn ' t contain file extensions , otherwise Cloudinary url would contain doubled extension - Cloudinary adds extension to url to allow file conversion to arbitrary file , like png to jpg...
file_resource_type = self . _get_resource_type ( name ) if file_resource_type is None or file_resource_type == self . RESOURCE_TYPE : return name else : extension = self . _get_file_extension ( name ) return name [ : - len ( extension ) - 1 ]
def remove_from_subscriptions ( self , subscription ) : """: calls : ` DELETE / user / subscriptions / : owner / : repo < http : / / developer . github . com / v3 / activity / watching > ` _ : param subscription : : class : ` github . Repository . Repository ` : rtype : None"""
assert isinstance ( subscription , github . Repository . Repository ) , subscription headers , data = self . _requester . requestJsonAndCheck ( "DELETE" , "/user/subscriptions/" + subscription . _identity )
def increment ( self , delta = 1 ) : """Increment counter value . Parameters value _ change : int Amount by which to add to the counter"""
check_call ( _LIB . MXProfileAdjustCounter ( self . handle , int ( delta ) ) )
def jdn_to_gdate ( jdn ) : """Convert from the Julian day to the Gregorian day . Algorithm from ' Julian and Gregorian Day Numbers ' by Peter Meyer . Return : day , month , year"""
# pylint : disable = invalid - name # The algorithm is a verbatim copy from Peter Meyer ' s article # No explanation in the article is given for the variables # Hence the exceptions for pylint and for flake8 ( E741) l = jdn + 68569 # noqa : E741 n = ( 4 * l ) // 146097 l = l - ( 146097 * n + 3 ) // 4 # noqa : E741 i = ...
def create_secret ( name , namespace = 'default' , data = None , source = None , template = None , saltenv = 'base' , ** kwargs ) : '''Creates the kubernetes secret as defined by the user . CLI Examples : : salt ' minion1 ' kubernetes . create _ secret passwords default ' { " db " : " letmein " } ' salt ' min...
if source : data = __read_and_render_yaml_file ( source , template , saltenv ) elif data is None : data = { } data = __enforce_only_strings_dict ( data ) # encode the secrets using base64 as required by kubernetes for key in data : data [ key ] = base64 . b64encode ( data [ key ] ) body = kubernetes . clien...
def get_requires ( self , ignored = tuple ( ) ) : """a map of requirements to what requires it . ignored is an optional list of globbed patterns indicating packages , classes , etc that shouldn ' t be included in the provides map"""
if self . _requires is None : self . _collect_requires_provides ( ) d = self . _requires if ignored : d = dict ( ( k , v ) for k , v in d . items ( ) if not fnmatches ( k , * ignored ) ) return d
def userBrowser ( self , request , tag ) : """Render a TDB of local users ."""
f = LocalUserBrowserFragment ( self . browser ) f . docFactory = webtheme . getLoader ( f . fragmentName ) f . setFragmentParent ( self ) return f
def is_alive ( self ) : """Test Function to check WHAT IF servers are up and running ."""
u = urllib . urlopen ( "http://wiws.cmbi.ru.nl/rest/TestEmpty/id/1crn/" ) x = xml . dom . minidom . parse ( u ) self . alive = len ( x . getElementsByTagName ( "TestEmptyResponse" ) ) return self . alive
def get_actions ( self , action_name , config_name , instances = None , map_name = None , ** kwargs ) : """Returns the entire set of actions performed for the indicated action name . : param action _ name : Action name . : type action _ name : unicode | str : param config _ name : Name ( s ) of container conf...
policy = self . get_policy ( ) action_generator = self . get_action_generator ( action_name , policy , kwargs ) for state in self . get_states ( action_name , config_name , instances = instances , map_name = map_name , ** kwargs ) : log . debug ( "Evaluating state: %s." , state ) actions = action_generator . ge...
def validateUserPars ( configObj , input_dict ) : """Compares input parameter names specified by user with those already recognized by the task . Any parameters provided by the user that does not match a known task parameter will be reported and a ValueError exception will be raised ."""
# check to see whether any input parameters are unexpected . # Any unexpected parameters provided on input should be reported and # the code should stop plist = getFullParList ( configObj ) extra_pars = [ ] for kw in input_dict : if kw not in plist : extra_pars . append ( kw ) if len ( extra_pars ) > 0 : ...
def get_song_url ( self , song_id , bit_rate = 320000 ) : """Get a song ' s download address . : params song _ id : song id < int > . : params bit _ rate : { ' MD 128k ' : 128000 , ' HD 320k ' : 320000} : return : a song ' s download address ."""
url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token=' csrf = '' params = { 'ids' : [ song_id ] , 'br' : bit_rate , 'csrf_token' : csrf } result = self . post_request ( url , params ) song_url = result [ 'data' ] [ 0 ] [ 'url' ] # download address if song_url is None : # Taylor Swift ' s song is not ava...
def is_country ( self , text ) : """Check if a piece of text is in the list of countries"""
ct_list = self . _just_cts . keys ( ) if text in ct_list : return True else : return False
def predict_from_cfg ( cls , choosers , alternatives , cfgname = None , cfg = None , alternative_ratio = 2.0 , debug = False ) : """Simulate choices for the specified choosers Parameters choosers : DataFrame A dataframe of agents doing the choosing . alternatives : DataFrame A dataframe of locations which...
logger . debug ( 'start: predict from configuration {}' . format ( cfgname ) ) if cfgname : lcm = cls . from_yaml ( str_or_buffer = cfgname ) elif cfg : lcm = cls . from_yaml ( yaml_str = cfg ) else : msg = 'predict_from_cfg requires a configuration via the cfgname or cfg arguments' logger . error ( msg...
def _ParseInfo2Record ( self , parser_mediator , file_object , record_offset , record_size ) : """Parses an INFO - 2 record . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . file _ object ( dfvfs . FileIO ) : file - like ...
record_data = self . _ReadData ( file_object , record_offset , record_size ) record_map = self . _GetDataTypeMap ( 'recycler_info2_file_entry' ) try : record = self . _ReadStructureFromByteStream ( record_data , record_offset , record_map ) except ( ValueError , errors . ParseError ) as exception : raise errors...
def mangle_form ( form ) : "Utility to monkeypatch forms into paperinputs , untested"
for field , widget in form . fields . iteritems ( ) : if type ( widget ) is forms . widgets . TextInput : form . fields [ field ] . widget = PaperTextInput ( ) form . fields [ field ] . label = '' if type ( widget ) is forms . widgets . PasswordInput : field . widget = PaperPasswordInput...
def authorized_connect_apps ( self ) : """Access the authorized _ connect _ apps : returns : twilio . rest . api . v2010 . account . authorized _ connect _ app . AuthorizedConnectAppList : rtype : twilio . rest . api . v2010 . account . authorized _ connect _ app . AuthorizedConnectAppList"""
if self . _authorized_connect_apps is None : self . _authorized_connect_apps = AuthorizedConnectAppList ( self . _version , account_sid = self . _solution [ 'sid' ] , ) return self . _authorized_connect_apps
def on_start ( self ) : """start the service"""
LOGGER . debug ( "rabbitmq.Service.on_start" ) self . connection = pika . BlockingConnection ( self . parameters ) self . channel = self . connection . channel ( ) self . channel . queue_declare ( queue = self . serviceQ , auto_delete = True ) self . channel . basic_consume ( self . on_request , self . serviceQ ) self ...
def add_ir_model_fields ( cr , columnspec ) : """Typically , new columns on ir _ model _ fields need to be added in a very early stage in the upgrade process of the base module , in raw sql as they need to be in place before any model gets initialized . Do not use for fields with additional SQL constraints , ...
for column in columnspec : query = 'ALTER TABLE ir_model_fields ADD COLUMN %s %s' % ( column ) logged_query ( cr , query , [ ] )
def get_lattice_type ( cryst ) : '''Find the symmetry of the crystal using spglib symmetry finder . Derive name of the space group and its number extracted from the result . Based on the group number identify also the lattice type and the Bravais lattice of the crystal . The lattice type numbers are ( the n...
# Table of lattice types and correcponding group numbers dividing # the ranges . See get _ lattice _ type method for precise definition . lattice_types = [ [ 3 , "Triclinic" ] , [ 16 , "Monoclinic" ] , [ 75 , "Orthorombic" ] , [ 143 , "Tetragonal" ] , [ 168 , "Trigonal" ] , [ 195 , "Hexagonal" ] , [ 231 , "Cubic" ] ] s...
def identify_assembly_points ( graph , bgtree , target_multicolor , exclude = None , verbose = False , verbose_destination = None ) : """The main granular assembling function , that IDENTIFIES assembly points , but does not perform the assembly on its own It DOES NOT change the supplied breakpoint graph in any wa...
if verbose : print ( ">>Identifying assemblies for target multicolor:" , [ e . name for e in target_multicolor . multicolors . elements ( ) ] , file = verbose_destination ) guidance = bgtree . consistent_multicolors [ : ] offset = len ( Multicolor . split_colors ( target_multicolor , guidance = guidance , account_f...
def is_authoring_node ( self , node ) : """Returns if given Node is an authoring node . : param node : Node . : type node : ProjectNode or DirectoryNode or FileNode : return : Is authoring node . : rtype : bool"""
for parent_node in foundations . walkers . nodes_walker ( node , ascendants = True ) : if parent_node is self . __default_project_node : return True return False
def execute ( self , request , session = None , method = 'post' ) : '''pyTOP . API - - TOPRequest instance'''
params = { 'app_key' : self . API_KEY , 'v' : self . API_VERSION , 'format' : self . FORMAT , # ' sign _ method ' : self . SIGN _ METHOD , 'partner_id' : self . SDK_VERSON } api_params = request . get_api_params ( ) params [ 'timestamp' ] = self . _get_timestamp ( ) params [ 'method' ] = request . get_method_name ( ) i...
def EncodeMessageList ( cls , message_list , packed_message_list ) : """Encode the MessageList into the packed _ message _ list rdfvalue ."""
# By default uncompress uncompressed_data = message_list . SerializeToString ( ) packed_message_list . message_list = uncompressed_data compressed_data = zlib . compress ( uncompressed_data ) # Only compress if it buys us something . if len ( compressed_data ) < len ( uncompressed_data ) : packed_message_list . com...
def lock_account ( self , minutes = 30 ) : """Lock user account for a period"""
period = datetime . timedelta ( minutes = minutes ) self . locked_until = datetime . datetime . utcnow ( ) + period
def get_hgnc_name ( hgnc_id ) : """Return the HGNC symbol corresponding to the given HGNC ID . Parameters hgnc _ id : str The HGNC ID to be converted . Returns hgnc _ name : str The HGNC symbol corresponding to the given HGNC ID ."""
try : hgnc_name = hgnc_names [ hgnc_id ] except KeyError : xml_tree = get_hgnc_entry ( hgnc_id ) if xml_tree is None : return None hgnc_name_tag = xml_tree . find ( "result/doc/str[@name='symbol']" ) if hgnc_name_tag is None : return None hgnc_name = hgnc_name_tag . text . strip ...
def global_del ( self , key ) : """Delete the global record for the key ."""
key = self . pack ( key ) return self . sql ( 'global_del' , key )
def _update_listing_client_kwargs ( client_kwargs , max_request_entries ) : """Updates client kwargs for listing functions . Args : client _ kwargs ( dict ) : Client arguments . max _ request _ entries ( int ) : If specified , maximum entries returned by request . Returns : dict : Updated client _ kwarg...
client_kwargs = client_kwargs . copy ( ) if max_request_entries : client_kwargs [ 'num_results' ] = max_request_entries return client_kwargs
def SetLookupHash ( self , lookup_hash ) : """Sets the hash to query . Args : lookup _ hash ( str ) : name of the hash attribute to look up . Raises : ValueError : if the lookup hash is not supported ."""
if lookup_hash not in self . SUPPORTED_HASHES : raise ValueError ( 'Unsupported lookup hash: {0!s}' . format ( lookup_hash ) ) self . lookup_hash = lookup_hash
def expand ( self , x , y , z ) : """Expands the bounding"""
if x != None : if self . minx is None or x < self . minx : self . minx = x if self . maxx is None or x > self . maxx : self . maxx = x if y != None : if self . miny is None or y < self . miny : self . miny = y if self . maxy is None or y > self . maxy : self . maxy = y if...
def select_cb ( self , viewer , event , data_x , data_y ) : """Called when the user clicks on the color bar viewer . Calculate the index of the color bar they clicked on and set that color map in the current channel viewer ."""
if not ( self . _cmxoff <= data_x < self . _cmwd ) : # need to click within the width of the bar return i = int ( data_y / ( self . _cmht + self . _cmsep ) ) if 0 <= i < len ( self . cm_names ) : name = self . cm_names [ i ] msg = "cmap => '%s'" % ( name ) self . logger . info ( msg ) channel = self...
def after_retract ( duplicate_analysis ) : """Function triggered after a ' retract ' transition for the duplicate passed in is performed . The duplicate transitions to " retracted " state and a new copy of the duplicate is created ."""
# Rename the analysis to make way for it ' s successor . # Support multiple retractions by renaming to * - 0 , * - 1 , etc parent = duplicate_analysis . aq_parent keyword = duplicate_analysis . getKeyword ( ) analyses = filter ( lambda an : an . getKeyword ( ) == keyword , parent . objectValues ( "DuplicateAnalysis" ) ...
def get_arguments ( self ) : """Gets the arguments from the command line ."""
parser = argparse . ArgumentParser ( description = 'Downloads images from given URL' ) parser . add_argument ( 'url2scrape' , nargs = 1 , help = "URL to scrape" ) parser . add_argument ( '-m' , '--max-images' , type = int , default = None , help = "Limit on number of images\n" ) parser . add_argument ( '-s' , '--save-d...
def prepare_cache_id ( self , combined_args_kw ) : "get the cacheid ( conc . string of argument self . ids in order )"
cache_id = "" . join ( self . id ( a ) for a in combined_args_kw ) return cache_id
def get_date_range_by_name ( name : str , today : datetime = None , tz = None ) -> ( datetime , datetime ) : """: param name : yesterday , last _ month : param today : Optional current datetime . Default is now ( ) . : param tz : Optional timezone . Default is UTC . : return : datetime ( begin , end )"""
if today is None : today = datetime . utcnow ( ) if name == 'last_month' : return last_month ( today , tz ) elif name == 'last_week' : return last_week ( today , tz ) elif name == 'this_month' : return this_month ( today , tz ) elif name == 'last_year' : return last_year ( today , tz ) elif name == ...
def _slice_split_info_to_instruction_dicts ( self , list_sliced_split_info ) : """Return the list of files and reading mask of the files to read ."""
instruction_dicts = [ ] for sliced_split_info in list_sliced_split_info : mask = splits_lib . slice_to_percent_mask ( sliced_split_info . slice_value ) # Compute filenames from the given split filepaths = list ( sorted ( self . _build_split_filenames ( split_info_list = [ sliced_split_info . split_info ] , ...
def generate_img_id ( profile , ext = None , label = None , tmp = False ) : """Generates img _ id ."""
if ext and not ext . startswith ( '.' ) : ext = '.' + ext if label : label = re . sub ( r'[^a-z0-9_\-]' , '' , label , flags = re . I ) label = re . sub ( r'_+' , '_' , label ) label = label [ : 60 ] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}' . format ( profile = profile , tmp = ( dju_settings ....
def avail_locations ( conn = None , call = None ) : '''Return a list of locations'''
if call == 'action' : raise SaltCloudSystemExit ( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' ) if conn is None : conn = get_conn ( ) endpoints = nova . get_entry ( conn . get_catalog ( ) , 'type' , 'compute' ) [ 'endpoints' ] ret = { } for endpoin...
def user_process ( self , input_data ) : """: param input _ data : : return : output _ data , list of next model instance . For example , if model is : class : ` ~ crawl _ zillow . model . State ` , then next model is : class : ` ~ crawl _ zillow . model . County ` ."""
url = input_data . doc . url self . logger . info ( "Crawl %s ." % url , 1 ) output_data = OutputData ( data = list ( ) ) try : html = get_html ( url , wait_time = Config . Crawler . wait_time , driver = self . _selenium_driver , ** input_data . get_html_kwargs ) # some this model ' s attributes will also avail...
def query_instances ( session , client = None , ** query ) : """Return a list of ec2 instances for the query ."""
if client is None : client = session . client ( 'ec2' ) p = client . get_paginator ( 'describe_instances' ) results = p . paginate ( ** query ) return list ( itertools . chain ( * [ r [ "Instances" ] for r in itertools . chain ( * [ pp [ 'Reservations' ] for pp in results ] ) ] ) )
def _choose_tuner ( self , algorithm_name ) : """Parameters algorithm _ name : str algorithm _ name includes " tpe " , " random _ search " and anneal " """
if algorithm_name == 'tpe' : return hp . tpe . suggest if algorithm_name == 'random_search' : return hp . rand . suggest if algorithm_name == 'anneal' : return hp . anneal . suggest raise RuntimeError ( 'Not support tuner algorithm in hyperopt.' )
def max ( x , y , context = None ) : """Return the maximum of x and y . If x and y are both NaN , return NaN . If exactly one of x and y is NaN , return the non - NaN value . If x and y are zeros of different signs , return"""
return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_max , ( BigFloat . _implicit_convert ( x ) , BigFloat . _implicit_convert ( y ) , ) , context , )
def variabletuple ( typename , variables , * args , ** kwargs ) : """Create a : func : ` ~ collections . namedtuple ` using : class : ` ~ symfit . core . argument . Variable ` ' s whoses names will be used as ` field _ names ` . The main reason for using this object is the ` _ asdict ( ) ` method : whereas a ...
def _asdict ( self ) : return OrderedDict ( zip ( variables , self ) ) field_names = [ var . name for var in variables ] named = namedtuple ( typename , field_names , * args , ** kwargs ) named . _asdict = _asdict return named
def order_by_line_nos ( objs , line_nos ) : """Orders the set of ` objs ` by ` line _ nos `"""
ordering = sorted ( range ( len ( line_nos ) ) , key = line_nos . __getitem__ ) return [ objs [ i ] for i in ordering ]
def spatiotemporal_segmentation ( points , eps , min_time ) : """Splits a set of points into multiple sets of points based on spatio - temporal stays DBSCAN is used to predict possible segmentations , furthermore we check to see if each clusters is big enough in time ( > = min _ time ) . If that ' s the cas...
# min time / sample rate dt_average = np . median ( [ point . dt for point in points ] ) min_samples = min_time / dt_average data = [ point . gen3arr ( ) for point in points ] data = StandardScaler ( ) . fit_transform ( data ) print 'min_samples: %f' % min_samples db_cluster = DBSCAN ( eps = eps , min_samples = min_sam...
def checkout ( repository , target ) : """Check out target into the current directory . Target can be a branch , review Id , or commit . : param repository : Current git repository . : param target : Review ID , commit , branch . : return : Return the most recent commit ID ( top of the git log ) ."""
# git fetch < remote > refs / changes / < review _ id > # git checkout FETCH _ HEAD repository . git . fetch ( [ next ( iter ( repository . remotes ) ) , target ] ) repository . git . checkout ( "FETCH_HEAD" ) return repository . git . rev_parse ( [ "--short" , "HEAD" ] ) . encode ( 'ascii' , 'ignore' )
def draw_panel ( self , surf ) : """Draw the unit selection or build queue ."""
left = - 12 # How far from the right border def unit_name ( unit_type ) : return self . _static_data . units . get ( unit_type , "<unknown>" ) def write ( loc , text , color = colors . yellow ) : surf . write_screen ( self . _font_large , color , loc , text ) def write_single ( unit , line ) : write ( ( lef...
def kallisto ( fastq , out_dir , cb_histogram , cb_cutoff ) : '''Convert fastqtransformed file to output format compatible with kallisto .'''
parser_re = re . compile ( '(.*):CELL_(?<CB>.*):UMI_(?P<UMI>.*)\\n(.*)\\n\\+\\n(.*)\\n' ) if fastq . endswith ( 'gz' ) : fastq_fh = gzip . GzipFile ( fileobj = open ( fastq ) ) elif fastq == "-" : fastq_fh = sys . stdin else : fastq_fh = open ( fastq ) cb_depth_set = get_cb_depth_set ( cb_histogram , cb_cut...
def mix_columns ( state ) : """Transformation in the Cipher that takes all of the columns of the State and mixes their data ( independently of one another ) to produce new columns ."""
state = state . reshape ( 4 , 4 , 8 ) return fcat ( multiply ( MA , state [ 0 ] ) , multiply ( MA , state [ 1 ] ) , multiply ( MA , state [ 2 ] ) , multiply ( MA , state [ 3 ] ) , )
def force_to_string ( unknown ) : """converts and unknown type to string for display purposes ."""
result = '' if type ( unknown ) is str : result = unknown if type ( unknown ) is int : result = str ( unknown ) if type ( unknown ) is float : result = str ( unknown ) if type ( unknown ) is dict : result = Dict2String ( unknown ) if type ( unknown ) is list : result = List2String ( unknown ) return...
def get_individuals_for_primary_organization ( self , organization ) : """Returns all Individuals that have ` organization ` as a primary org ."""
if not self . client . session_id : self . client . request_session ( ) object_query = ( "SELECT Objects() FROM Individual WHERE " "PrimaryOrganization = '{}'" . format ( organization . membersuite_account_num ) ) result = self . client . execute_object_query ( object_query ) msql_result = result [ "body" ] [ "Exec...
def _wrapped_cross_val_score ( sklearn_pipeline , features , target , cv , scoring_function , sample_weight = None , groups = None , use_dask = False ) : """Fit estimator and compute scores for a given dataset split . Parameters sklearn _ pipeline : pipeline object implementing ' fit ' The object to use to fi...
sample_weight_dict = set_sample_weight ( sklearn_pipeline . steps , sample_weight ) features , target , groups = indexable ( features , target , groups ) cv = check_cv ( cv , target , classifier = is_classifier ( sklearn_pipeline ) ) cv_iter = list ( cv . split ( features , target , groups ) ) scorer = check_scoring ( ...
def download_blobs_from_container ( block_blob_client , container_name , directory_path , prefix = None ) : """Downloads all blobs from the specified Azure Blob storage container . : param block _ blob _ client : A blob service client . : type block _ blob _ client : ` azure . storage . blob . BlockBlobService ...
_log . info ( 'Downloading all files from container [{}]...' . format ( container_name ) ) container_blobs = block_blob_client . list_blobs ( container_name , prefix = None ) _log . info ( '{} blobs are found [{}]' . format ( len ( tuple ( container_blobs ) ) , ', ' . join ( blob . name for blob in container_blobs . it...
def check ( self , user , provider , permission , ** kwargs ) : '''user - django User or UserSocialAuth instance provider - name of publisher provider permission - if backend maintains check permissions vk - binary mask in int format facebook - scope string'''
try : social_user = self . _get_social_user ( user , provider ) if not social_user : return False except SocialUserDoesNotExist : return False backend = self . get_backend ( social_user , provider , context = kwargs ) return backend . check ( permission )
def location ( name , uri , default ) : """Create new location ."""
from . models import Location location = Location ( name = name , uri = uri , default = default ) db . session . add ( location ) db . session . commit ( ) click . secho ( str ( location ) , fg = 'green' )
def _iter_modules ( modules , class_name , path , ignored_formats , args ) : """This huge function generates a hierarchy with hopefully more clear structure of modules / sections / lectures ."""
file_formats = args . file_formats lecture_filter = args . lecture_filter resource_filter = args . resource_filter section_filter = args . section_filter verbose_dirs = args . verbose_dirs combined_section_lectures_nums = args . combined_section_lectures_nums class IterModule ( object ) : def __init__ ( self , inde...
def getVolumeInformation ( self , volumeNameBuffer , volumeNameSize , volumeSerialNumber , maximumComponentLength , fileSystemFlags , fileSystemNameBuffer , fileSystemNameSize , dokanFileInfo , ) : """Get information about the volume . : param volumeNameBuffer : buffer for volume name : type volumeNameBuffer : ...
ret = self . operations ( 'getVolumeInformation' ) # populate volume name buffer ctypes . memmove ( volumeNameBuffer , ret [ 'volumeNameBuffer' ] , min ( ctypes . sizeof ( ctypes . c_wchar ) * len ( ret [ 'volumeNameBuffer' ] ) , volumeNameSize , ) , ) # populate serial number buffer serialNum = ctypes . c_ulong ( self...
def ro_rw_to_binds ( ro , rw ) : """ro and rw { localdir : binddir } dicts to docker - py ' s { localdir : { ' bind ' : binddir , ' ro ' : T / F } } binds dicts"""
out = { } if ro : for localdir , binddir in ro . iteritems ( ) : out [ localdir ] = { 'bind' : binddir , 'ro' : True } if rw : for localdir , binddir in rw . iteritems ( ) : out [ localdir ] = { 'bind' : binddir , 'ro' : False } return out
def _psutil_kill_pid ( pid ) : """http : / / stackoverflow . com / questions / 1230669 / subprocess - deleting - child - processes - in - windows"""
try : parent = Process ( pid ) for child in parent . children ( recursive = True ) : child . kill ( ) parent . kill ( ) except NoSuchProcess : return
def find_first ( pred , lst ) : """Find the first result of a list of promises ` lst ` that satisfies a predicate ` pred ` . : param pred : a function of one argument returning ` True ` or ` False ` . : param lst : a list of promises or values . : return : a promise of a value or ` None ` . This is a wrap...
if lst : return s_find_first ( pred , lst [ 0 ] , [ quote ( l ) for l in lst [ 1 : ] ] ) else : return None
def _to_predictor ( self , pred_parameter = None ) : """Convert to predictor ."""
predictor = _InnerPredictor ( booster_handle = self . handle , pred_parameter = pred_parameter ) predictor . pandas_categorical = self . pandas_categorical return predictor
def community_topic_create ( self , data , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / help _ center / topics # create - topic"
api_path = "/api/v2/community/topics.json" return self . call ( api_path , method = "POST" , data = data , ** kwargs )
def pop_kwargs ( kwargs , names_with_defaults , # type : List [ Tuple [ str , Any ] ] allow_others = False ) : """Internal utility method to extract optional arguments from kwargs . : param kwargs : : param names _ with _ defaults : : param allow _ others : if False ( default ) then an error will be raised if...
all_arguments = [ ] for name , default_ in names_with_defaults : try : val = kwargs . pop ( name ) except KeyError : val = default_ all_arguments . append ( val ) if not allow_others and len ( kwargs ) > 0 : raise ValueError ( "Unsupported arguments: %s" % kwargs ) if len ( names_with_de...
def Serialize ( self , writer ) : """Serialize object . Args : writer ( neo . IO . BinaryWriter ) :"""
self . SerializeUnsigned ( writer ) writer . WriteSerializableArray ( self . scripts )
async def json ( self , * , loads : JSONDecoder = DEFAULT_JSON_DECODER ) -> Any : """Return BODY as JSON ."""
body = await self . text ( ) return loads ( body )
def date_between ( self , start_date = '-30y' , end_date = 'today' ) : """Get a Date object based on a random date between two given dates . Accepts date strings that can be recognized by strtotime ( ) . : param start _ date Defaults to 30 years ago : param end _ date Defaults to " today " : example Date ( ...
start_date = self . _parse_date ( start_date ) end_date = self . _parse_date ( end_date ) return self . date_between_dates ( date_start = start_date , date_end = end_date )