signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _exec_request ( self , service , method = None , path_args = None , data = None , params = None ) : """Execute request ."""
if path_args is None : path_args = [ ] req = { 'method' : method or 'get' , 'url' : '/' . join ( str ( a ) . strip ( '/' ) for a in [ cfg . CONF . tvdb . service_url , service ] + path_args ) , 'data' : json . dumps ( data ) if data else None , 'headers' : self . headers , 'params' : params , 'verify' : cfg . CONF ...
def call ( self , parameters ) : """Call an endpoint given the parameters : param parameters : Dictionary of parameters : type parameters : dict : rtype : text"""
# DEV ! parameters = { key : str ( parameters [ key ] ) for key in parameters if parameters [ key ] is not None } if self . inventory is not None and "inv" not in parameters : parameters [ "inv" ] = self . inventory request = requests . get ( self . endpoint , params = parameters ) request . raise_for_status ( ) if...
def delete_manager ( self , instance ) : """Returns a queryset based on the related model ' s base manager ( rather than the default manager , as returned by _ _ get _ _ ) . Used by Model . delete ( ) ."""
return self . create_manager ( instance , self . rating_model . _base_manager . __class__ )
def terminate ( self , reboot = False ) : """Delete VIOM configuration from iRMC ."""
self . root . manage . manage = False self . root . mode = 'delete' self . root . init_boot = reboot self . client . set_profile ( self . root . get_json ( ) )
def _serve_numerics_alert_report_handler ( self , request ) : """A ( wrapped ) werkzeug handler for serving numerics alert report . Accepts GET requests and responds with an array of JSON - ified NumericsAlertReportRow . Each JSON - ified NumericsAlertReportRow object has the following format : ' device _ n...
if request . method != 'GET' : logger . error ( '%s requests are forbidden by the debugger plugin.' , request . method ) return wrappers . Response ( status = 405 ) report = self . _debugger_data_server . numerics_alert_report ( ) # Convert the named tuples to dictionaries so we JSON them into objects . respons...
def write ( self , text : str ) : """Prints text to the screen . Supports colors by using the color constants . To use colors , add the color before the text you want to print . : param text : The text to print ."""
# Default color is NORMAL . last_color = ( self . _DARK_CODE , 0 ) # We use splitlines with keepends in order to keep the line breaks . # Then we split by using the console width . original_lines = text . splitlines ( True ) lines = self . _split_lines ( original_lines ) if self . _width_limit else original_lines # Pri...
def str_kwargs ( self ) : """Generator that yields a dict of values corresponding to the calendar date and time for the internal JD values . Here we provide the additional ' fracday ' element needed by ' mpc ' format"""
iys , ims , ids , ihmsfs = sofa_time . jd_dtf ( self . scale . upper ( ) . encode ( 'utf8' ) , 6 , self . jd1 , self . jd2 ) # Get the str _ fmt element of the first allowed output subformat _ , _ , str_fmt = self . _select_subfmts ( self . out_subfmt ) [ 0 ] yday = None has_yday = '{yday:' in str_fmt or False for iy ,...
def get_apps ( self ) : """Get the list of installed apps and return the apps that have an emails module"""
templates = [ ] for app in settings . INSTALLED_APPS : try : app = import_module ( app + '.emails' ) templates += self . get_plugs_mail_classes ( app ) except ImportError : pass return templates
def validate_value ( self , value ) : """Validate provided record is a part of the appropriate target app for the field"""
if value not in ( None , self . _unset ) : super ( ReferenceField , self ) . validate_value ( value ) if value . app != self . target_app : raise ValidationError ( self . record , "Reference field '{}' has target app '{}', cannot reference record '{}' from app '{}'" . format ( self . name , self . targe...
def alphabet ( cl ) : """The inclusion tag that renders the admin / alphabet . html template in the admin . Accepts a ChangeList object , which is custom to the admin ."""
if not getattr ( cl . model_admin , 'alphabet_filter' , False ) : return field_name = cl . model_admin . alphabet_filter alpha_field = '%s__istartswith' % field_name alpha_lookup = cl . params . get ( alpha_field , '' ) letters_used = _get_available_letters ( field_name , cl . model . objects . all ( ) ) all_letter...
def validate ( self , str_in ) : # type : ( Text ) - > None """Validates an entry in the field . Raises ` InvalidEntryError ` iff the entry is invalid . An entry is invalid iff ( 1 ) the string does not represent a base - 10 integer ; ( 2 ) the integer is not between ` self . minimum ` and ` self . maximum ...
if self . is_missing_value ( str_in ) : return # noinspection PyCompatibility super ( ) . validate ( str_in ) try : value = int ( str_in , base = 10 ) except ValueError as e : msg = "Invalid integer. Read '{}'." . format ( str_in ) e_new = InvalidEntryError ( msg ) e_new . field_spec = self rais...
def writefile ( openedfile , newcontents ) : """Set the contents of a file ."""
openedfile . seek ( 0 ) openedfile . truncate ( ) openedfile . write ( newcontents )
def create_membership_matrix ( cluster_run ) : """For a label vector represented by cluster _ run , constructs the binary membership indicator matrix . Such matrices , when concatenated , contribute to the adjacency matrix for a hypergraph representation of an ensemble of clusterings . Parameters cluster ...
cluster_run = np . asanyarray ( cluster_run ) if reduce ( operator . mul , cluster_run . shape , 1 ) != max ( cluster_run . shape ) : raise ValueError ( "\nERROR: Cluster_Ensembles: create_membership_matrix: " "problem in dimensions of the cluster label vector " "under consideration." ) else : cluster_run = clu...
async def add ( client : Client , identity_signed_raw : str ) -> ClientResponse : """POST identity raw document : param client : Client to connect to the api : param identity _ signed _ raw : Identity raw document : return :"""
return await client . post ( MODULE + '/add' , { 'identity' : identity_signed_raw } , rtype = RESPONSE_AIOHTTP )
def _is_noop_timeperiod ( self , process_name , timeperiod ) : """method verifies if the given timeperiod for given process is valid or falls in - between grouping checkpoints : param process _ name : name of the process : param timeperiod : timeperiod to verify : return : False , if given process has no time...
time_grouping = context . process_context [ process_name ] . time_grouping if time_grouping == 1 : return False process_hierarchy = self . timetable . get_tree ( process_name ) . process_hierarchy timeperiod_dict = process_hierarchy [ process_name ] . timeperiod_dict return timeperiod_dict . _translate_timeperiod (...
def _unwatch_file ( self , filepath , trigger_event = True ) : """Removes the file from the internal watchlist if exists ."""
if filepath not in self . _watched_files : return if trigger_event : self . trigger_deleted ( filepath ) del self . _watched_files [ filepath ]
def parse_size_name ( type_name ) : """Calculate size and encoding from a type name . This method takes a C - style type string like uint8 _ t [ 10 ] and returns - the total size in bytes - the unit size of each member ( if it ' s an array ) - the scruct . { pack , unpack } format code for decoding the base...
if ' ' in type_name : raise ArgumentError ( "There should not be a space in config variable type specifier" , specifier = type_name ) variable = False count = 1 base_type = type_name if type_name [ - 1 ] == ']' : variable = True start_index = type_name . find ( '[' ) if start_index == - 1 : rais...
def linspace_pix ( self , start = None , stop = None , pixel_step = 1 , y_vs_x = True ) : """Return x , y values evaluated with a given pixel step ."""
return CCDLine . linspace_pix ( self , start = start , stop = stop , pixel_step = pixel_step , y_vs_x = y_vs_x )
def get_scaffold_objective_ids ( self ) : """Assumes that a scaffold objective id is available"""
section = self . _assessment_section item_id = self . get_my_item_id_from_section ( section ) return section . get_confused_learning_objective_ids ( item_id )
def get_max_distance_from_start ( latlon_track ) : '''Returns the radius of an entire GPS track . Used to calculate whether or not the entire sequence was just stationary video Takes a sequence of points as input'''
latlon_list = [ ] # Remove timestamps from list for idx , point in enumerate ( latlon_track ) : lat = latlon_track [ idx ] [ 1 ] lon = latlon_track [ idx ] [ 2 ] alt = latlon_track [ idx ] [ 3 ] latlon_list . append ( [ lat , lon , alt ] ) start_position = latlon_list [ 0 ] max_distance = 0 for position...
def export_fem ( self , arms = None , format = 'json' , df_kwargs = None ) : """Export the project ' s form to event mapping Parameters arms : list Limit exported form event mappings to these arm numbers format : ( ` ` ' json ' ` ` ) , ` ` ' csv ' ` ` , ` ` ' xml ' ` ` Return the form event mappings in na...
ret_format = format if format == 'df' : from pandas import read_csv ret_format = 'csv' pl = self . __basepl ( 'formEventMapping' , format = ret_format ) to_add = [ arms ] str_add = [ 'arms' ] for key , data in zip ( str_add , to_add ) : if data : pl [ key ] = ',' . join ( data ) response , _ = self ...
def get_page_count ( filename : str ) -> int : """How many pages are in a PDF ?"""
log . debug ( "Getting page count for {!r}" , filename ) require ( PDFTK , HELP_MISSING_PDFTK ) stdout , _ = run ( [ PDFTK , filename , "dump_data" ] , get_output = True ) regex = re . compile ( r"^NumberOfPages: (\d+)$" , re . MULTILINE ) m = regex . search ( stdout ) if m : return int ( m . group ( 1 ) ) raise Va...
def from_path ( cls , path ) : """Read configuration from a file on disk ."""
f = GitFile ( path , 'rb' ) try : ret = cls . from_file ( f ) ret . path = path return ret finally : f . close ( )
def unbind ( self , name ) : '''Unbind an object from the context represented by this directory . Warning : this is a dangerous operation . You may unlink an entire section of the tree and be unable to recover it . Be careful what you unbind . The name should be in the format used in paths . For example , ...
with self . _mutex : id , sep , kind = name . rpartition ( '.' ) if not id : id = kind kind = '' name = CosNaming . NameComponent ( id = str ( id ) , kind = str ( kind ) ) try : self . context . unbind ( [ name ] ) except CosNaming . NamingContext . NotFound : raise e...
def switch_toggle ( self , device ) : """Toggles the current state of the given device"""
state = self . get_state ( device ) if ( state == '1' ) : return self . switch_off ( device ) elif ( state == '0' ) : return self . switch_on ( device ) else : return state
def make_gpg_home ( appname , config_dir = None ) : """Make GPG keyring dir for a particular application . Return the path ."""
assert is_valid_appname ( appname ) config_dir = get_config_dir ( config_dir ) path = os . path . join ( config_dir , "gpgkeys" , appname ) if not os . path . exists ( path ) : os . makedirs ( path , 0700 ) else : os . chmod ( path , 0700 ) return path
def getDownloader ( self , url ) : """Get an image downloader ."""
filename = self . namer ( url , self . stripUrl ) if filename is None : filename = url . rsplit ( '/' , 1 ) [ 1 ] dirname = getDirname ( self . name ) return ComicImage ( self . name , url , self . stripUrl , dirname , filename , self . session , text = self . text )
def lonlat2xyz ( lons , lats ) : """Convert lons and lats to cartesian coordinates ."""
R = 6370997.0 x_coords = R * da . cos ( da . deg2rad ( lats ) ) * da . cos ( da . deg2rad ( lons ) ) y_coords = R * da . cos ( da . deg2rad ( lats ) ) * da . sin ( da . deg2rad ( lons ) ) z_coords = R * da . sin ( da . deg2rad ( lats ) ) return x_coords , y_coords , z_coords
def update ( self , friendly_name = values . unset , unique_name = values . unset , actions = values . unset , actions_url = values . unset ) : """Update the TaskInstance : param unicode friendly _ name : A string to describe the resource : param unicode unique _ name : An application - defined string that uniq...
return self . _proxy . update ( friendly_name = friendly_name , unique_name = unique_name , actions = actions , actions_url = actions_url , )
def resolve_image ( input , resolvers = None , fmt = 'png' , width = 300 , height = 300 , frame = False , crop = None , bgcolor = None , atomcolor = None , hcolor = None , bondcolor = None , framecolor = None , symbolfontsize = 11 , linewidth = 2 , hsymbol = 'special' , csymbol = 'special' , stereolabels = False , ster...
# Aggregate all arguments into kwargs args , _ , _ , values = inspect . getargvalues ( inspect . currentframe ( ) ) for arg in args : if values [ arg ] is not None : kwargs [ arg ] = values [ arg ] # Turn off anti - aliasing for transparent background if kwargs . get ( 'bgcolor' ) == 'transparent' : kwa...
def list_targets ( Rule , region = None , key = None , keyid = None , profile = None ) : '''Given a rule name list the targets of that rule . Returns a dictionary of interesting properties . CLI Example : . . code - block : : bash salt myminion boto _ cloudwatch _ event . list _ targets myrule'''
try : conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) targets = conn . list_targets_by_rule ( Rule = Rule ) ret = [ ] if targets and 'Targets' in targets : keys = ( 'Id' , 'Arn' , 'Input' , 'InputPath' ) for target in targets . get ( 'Targets' ) : ...
def _compute_childtab ( self , lcptab ) : """Computes the child ' up ' and ' down ' arrays in O ( n ) based on the LCP table . Abouelhoda et al . ( 2004 ) ."""
last_index = - 1 stack = [ 0 ] n = len ( lcptab ) childtab_up = np . zeros ( n , dtype = np . int ) # Zeros / - 1 ? childtab_down = np . zeros ( n , dtype = np . int ) for i in xrange ( n ) : while lcptab [ i ] < lcptab [ stack [ - 1 ] ] : last_index = stack . pop ( ) if lcptab [ i ] <= lcptab [ sta...
def to_gpu ( x , * args , ** kwargs ) : '''puts pytorch variable to gpu , if cuda is available and USE _ GPU is set to true .'''
return x . cuda ( * args , ** kwargs ) if USE_GPU else x
def last_session_date ( self ) : """Return date / time for start of last session data ."""
try : date = self . intervals [ 1 ] [ 'ts' ] except KeyError : return None date_f = datetime . strptime ( date , '%Y-%m-%dT%H:%M:%S.%fZ' ) now = time . time ( ) offset = datetime . fromtimestamp ( now ) - datetime . utcfromtimestamp ( now ) return date_f + offset
def update_agent_db_refs ( self , agent , agent_text , do_rename = True ) : """Update db _ refs of agent using the grounding map If the grounding map is missing one of the HGNC symbol or Uniprot ID , attempts to reconstruct one from the other . Parameters agent : : py : class : ` indra . statements . Agent ...
map_db_refs = deepcopy ( self . gm . get ( agent_text ) ) self . standardize_agent_db_refs ( agent , map_db_refs , do_rename )
def get_facet_values_as_list ( self , field ) : ''': param str field : Name of facet field to retrieve values from . Returns facet values as list for a given field . Example : : > > > res = solr . query ( ' SolrClient _ unittest ' , { ' facet ' : ' true ' , ' facet . field ' : ' facet _ test ' , > > > res...
facets = self . get_facets ( ) out = [ ] if field in facets . keys ( ) : for facetfield in facets [ field ] : out . append ( facets [ field ] [ facetfield ] ) return out else : raise SolrResponseError ( "No field in facet output" )
def _find_devices ( serial = None ) : """Returns a list of CrazyRadio devices currently connected to the computer"""
ret = [ ] if pyusb1 : for d in usb . core . find ( idVendor = 0x1915 , idProduct = 0x7777 , find_all = 1 , backend = pyusb_backend ) : if serial is not None and serial == d . serial_number : return d ret . append ( d ) else : busses = usb . busses ( ) for bus in busses : ...
def IndexedDB_requestDatabaseNames ( self , securityOrigin ) : """Function path : IndexedDB . requestDatabaseNames Domain : IndexedDB Method name : requestDatabaseNames Parameters : Required arguments : ' securityOrigin ' ( type : string ) - > Security origin . Returns : ' databaseNames ' ( type : arr...
assert isinstance ( securityOrigin , ( str , ) ) , "Argument 'securityOrigin' must be of type '['str']'. Received type: '%s'" % type ( securityOrigin ) subdom_funcs = self . synchronous_command ( 'IndexedDB.requestDatabaseNames' , securityOrigin = securityOrigin ) return subdom_funcs
def save_params ( self , f = None , f_params = None , f_optimizer = None , f_history = None ) : """Saves the module ' s parameters , history , and optimizer , not the whole object . To save the whole object , use pickle . ` ` f _ params ` ` and ` ` f _ optimizer ` ` uses PyTorchs ' : func : ` ~ torch . save...
# TODO : Remove warning in a future release if f is not None : warnings . warn ( "f argument was renamed to f_params and will be removed " "in the next release. To make your code future-proof it is " "recommended to explicitly specify keyword arguments' names " "instead of relying on positional order." , Deprecatio...
def public ( self ) : """True if the Slot is public ."""
return bool ( lib . EnvSlotPublicP ( self . _env , self . _cls , self . _name ) )
def get_nowait ( self ) : """Remove and return an item from the queue . Return an item if one is immediately available , else raise QueueEmpty ."""
self . _parent . _check_closing ( ) with self . _parent . _sync_mutex : if self . _parent . _qsize ( ) == 0 : raise AsyncQueueEmpty item = self . _parent . _get ( ) self . _parent . _notify_async_not_full ( threadsafe = False ) self . _parent . _notify_sync_not_full ( ) return item
def reads ( text , fmt , as_version = 4 , ** kwargs ) : """Read a notebook from a string"""
fmt = copy ( fmt ) fmt = long_form_one_format ( fmt ) ext = fmt [ 'extension' ] if ext == '.ipynb' : return nbformat . reads ( text , as_version , ** kwargs ) format_name = read_format_from_metadata ( text , ext ) or fmt . get ( 'format_name' ) if format_name : format_options = { } else : format_name , form...
def well_fields ( self , well_x = 1 , well_y = 1 ) : """All ScanFieldData elements of given well . Parameters well _ x : int well _ y : int Returns list of lxml . objectify . ObjectifiedElement All ScanFieldData elements of given well ."""
xpath = './ScanFieldArray/ScanFieldData' xpath += _xpath_attrib ( 'WellX' , well_x ) xpath += _xpath_attrib ( 'WellY' , well_y ) return self . root . findall ( xpath )
def asof_locs ( self , where , mask ) : """Find the locations ( indices ) of the labels from the index for every entry in the ` where ` argument . As in the ` asof ` function , if the label ( a particular entry in ` where ` ) is not in the index , the latest index label upto the passed label is chosen and i...
locs = self . values [ mask ] . searchsorted ( where . values , side = 'right' ) locs = np . where ( locs > 0 , locs - 1 , 0 ) result = np . arange ( len ( self ) ) [ mask ] . take ( locs ) first = mask . argmax ( ) result [ ( locs == 0 ) & ( where . values < self . values [ first ] ) ] = - 1 return result
def _gmvs_to_haz_curve ( gmvs , imls , invest_time , duration ) : """Given a set of ground motion values ( ` ` gmvs ` ` ) and intensity measure levels ( ` ` imls ` ` ) , compute hazard curve probabilities of exceedance . : param gmvs : A list of ground motion values , as floats . : param imls : A list of ...
# convert to numpy array and redimension so that it can be broadcast with # the gmvs for computing PoE values ; there is a gmv for each rupture # here is an example : imls = [ 0.03 , 0.04 , 0.05 ] , gmvs = [ 0.04750576] # = > num _ exceeding = [ 1 , 1 , 0 ] coming from 0.04750576 > [ 0.03 , 0.04 , 0.05] imls = numpy . ...
def encrypt ( s , base64 = False ) : """对称加密函数"""
e = _cipher ( ) . encrypt ( s ) return base64 and b64encode ( e ) or e
def unhook ( self , debug , pid ) : """Removes the API hook from the given process and module . @ warning : Do not call from an API hook callback . @ type debug : L { Debug } @ param debug : Debug object . @ type pid : int @ param pid : Process ID ."""
try : hook = self . __hook [ pid ] except KeyError : return label = "%s!%s" % ( self . __modName , self . __procName ) hook . unhook ( debug , pid , label ) del self . __hook [ pid ]
def add_postprocessor ( postproc ) : """Define a postprocessor to run after the function is executed , when running in console script mode . : param postproc : The callable , which will be passed the Namespace object generated by argparse and the return result of the function . The return result of the ca...
def decorator ( func ) : func = ScriptAdaptor . _wrap ( func ) func . _add_postprocessor ( postproc ) return func return decorator
def get_connection ( store_settings : dict = { } ) -> Connection : """get an objectsctore connection"""
store = store_settings if not store_settings : store = make_config_from_env ( ) os_options = { 'tenant_id' : store [ 'TENANT_ID' ] , 'region_name' : store [ 'REGION_NAME' ] , # ' endpoint _ type ' : ' internalURL ' } # when we are running in cloudvps we should use internal urls use_internal = os . getenv ( 'OBJECTS...
def stop ( self ) : """Stop the periodic runner"""
self . _cease . set ( ) time . sleep ( 0.1 ) # let the thread closing correctly . self . _isRunning = False
def edit_message_reply_markup ( self , chat_id , message_id , reply_markup , ** options ) : """Edit a reply markup of message in a chat : param int chat _ id : ID of the chat the message to edit is in : param int message _ id : ID of the message to edit : param str reply _ markup : New inline keyboard markup ...
return self . api_call ( "editMessageReplyMarkup" , chat_id = chat_id , message_id = message_id , reply_markup = reply_markup , ** options )
def plot_rebit_prior ( prior , rebit_axes = REBIT_AXES , n_samples = 2000 , true_state = None , true_size = 250 , force_mean = None , legend = True , mean_color_index = 2 ) : """Plots rebit states drawn from a given prior . : param qinfer . tomography . DensityOperatorDistribution prior : Distribution over rebi...
pallette = plt . rcParams [ 'axes.color_cycle' ] plot_rebit_modelparams ( prior . sample ( n_samples ) , c = pallette [ 0 ] , label = 'Prior' , rebit_axes = rebit_axes ) if true_state is not None : plot_rebit_modelparams ( true_state , c = pallette [ 1 ] , label = 'True' , marker = '*' , s = true_size , rebit_axes ...
def archive ( self , prepend = None , overwrite = no , quiet = yes ) : """Create backup copies of the WCS keywords with the given prepended string . If backup keywords are already present , only update them if ' overwrite ' is set to ' yes ' , otherwise , do warn the user and do nothing . Set the WCSDATE at...
# Verify that existing backup values are not overwritten accidentally . if len ( list ( self . backup . keys ( ) ) ) > 0 and overwrite == no : if not quiet : print ( 'WARNING: Backup WCS keywords already exist! No backup made.' ) print ( ' The values can only be overridden if overwrite=yes.'...
def removeClassBreak ( self , label ) : """removes a classification break value to the renderer"""
for v in self . _classBreakInfos : if v [ 'label' ] == label : self . _classBreakInfos . remove ( v ) return True del v return False
def check_validity_for_dict ( keys , dict ) : """> > > dict = { ' a ' : 0 , ' b ' : 1 , ' c ' : 2} > > > keys = [ ' a ' , ' d ' , ' e ' ] > > > check _ validity _ for _ dict ( keys , dict ) = = False True > > > keys = [ ' a ' , ' b ' , ' c ' ] > > > check _ validity _ for _ dict ( keys , dict ) = = False ...
for key in keys : if key not in dict or dict [ key ] is '' or dict [ key ] is None : return False return True
def make_inc ( incs ) : """Make include directory for link . exe ."""
inc_args = [ [ '/I' , inc ] for inc in incs ] return list ( chain . from_iterable ( inc_args ) )
def create_examples ( candidate_dialog_paths , examples_num , creator_function ) : """Creates a list of training examples from a list of dialogs and function that transforms a dialog to an example . : param candidate _ dialog _ paths : : param creator _ function : : return :"""
i = 0 examples = [ ] unique_dialogs_num = len ( candidate_dialog_paths ) while i < examples_num : context_dialog = candidate_dialog_paths [ i % unique_dialogs_num ] # counter for tracking progress if i % 1000 == 0 : print str ( i ) i += 1 examples . append ( creator_function ( context_dialog...
def favicon ( request ) : """It returns favicon ' s location"""
favicon = u"{}tree/images/favicon.ico" . format ( settings . STATIC_URL ) try : from seo . models import MetaSite site = MetaSite . objects . get ( default = True ) return HttpResponseRedirect ( site . favicon . url ) except : return HttpResponseRedirect ( favicon )
def clean_extra ( self ) : """Clean extra files / directories specified by get _ extra _ paths ( )"""
extra_paths = self . get_extra_paths ( ) for path in extra_paths : if not os . path . exists ( path ) : continue if os . path . isdir ( path ) : self . _clean_directory ( path ) else : self . _clean_file ( path )
def get_my_choices_users ( ) : """Retrieves a list of all users in the system for the user management page"""
user_list = User . objects . order_by ( 'date_joined' ) user_tuple = [ ] counter = 1 for user in user_list : user_tuple . append ( ( counter , user ) ) counter = counter + 1 return user_tuple
def gen_sdiv ( src1 , src2 , dst ) : """Return a SDIV instruction ."""
assert src1 . size == src2 . size return ReilBuilder . build ( ReilMnemonic . SDIV , src1 , src2 , dst )
def gen_all ( self ) : """Generator of all borders"""
borderfuncs = [ self . get_b , self . get_r , self . get_t , self . get_l , self . get_tl , self . get_tr , self . get_rt , self . get_rb , self . get_br , self . get_bl , self . get_lb , self . get_lt , ] for borderfunc in borderfuncs : yield borderfunc ( )
def add_abstract ( self , abstract , source = None ) : """Add abstract . : param abstract : abstract for the current document . : type abstract : string : param source : source for the given abstract . : type source : string"""
self . _append_to ( 'abstracts' , self . _sourced_dict ( source , value = abstract . strip ( ) , ) )
def killCells ( self , percent = 0.05 ) : """Changes the percentage of cells that are now considered dead . The first time you call this method a permutation list is set up . Calls change the number of cells considered dead ."""
if self . zombiePermutation is None : self . zombiePermutation = numpy . random . permutation ( self . numberOfCells ( ) ) self . numDead = int ( round ( percent * self . numberOfCells ( ) ) ) if self . numDead > 0 : self . deadCells = set ( self . zombiePermutation [ 0 : self . numDead ] ) else : self . de...
def _add_new_repo ( repo , properties ) : '''Add a new repo entry'''
repostr = '# ' if not properties . get ( 'enabled' ) else '' repostr += 'src/gz ' if properties . get ( 'compressed' ) else 'src ' if ' ' in repo : repostr += '"' + repo + '" ' else : repostr += repo + ' ' repostr += properties . get ( 'uri' ) repostr = _set_trusted_option_if_needed ( repostr , properties . get...
def Q ( self , value ) : """Process uncertainty"""
self . _Q = value self . _Q1_2 = cholesky ( self . _Q , lower = True )
def asdensity ( self ) -> 'Density' : """Convert a pure state to a density matrix"""
matrix = bk . outer ( self . tensor , bk . conj ( self . tensor ) ) return Density ( matrix , self . qubits , self . _memory )
def update_bios_data_by_patch ( self , data ) : """Update bios data by patch : param data : default bios config data"""
bios_settings_data = { 'Attributes' : data } self . _conn . patch ( self . path , data = bios_settings_data )
def getLabel ( self ) : """Returns symbolic path to this MIB variable . Meaning a sequence of symbolic identifications for each of parent MIB objects in MIB tree . Returns tuple sequence of names of nodes in a MIB tree from the top of the tree towards this MIB variable . Raises SmiError If MIB var...
if self . _state & self . ST_CLEAN : return self . _label else : raise SmiError ( '%s object not fully initialized' % self . __class__ . __name__ )
def hash_stream ( self , url ) : # type : ( str ) - > str """Stream file from url and hash it using MD5 . Must call setup method first . Args : url ( str ) : URL to download Returns : str : MD5 hash of file"""
md5hash = hashlib . md5 ( ) try : for chunk in self . response . iter_content ( chunk_size = 10240 ) : if chunk : # filter out keep - alive new chunks md5hash . update ( chunk ) return md5hash . hexdigest ( ) except Exception as e : raisefrom ( DownloadError , 'Download of %s failed in r...
def read ( datapath , qt_app = None , dataplus_format = True , gui = False , start = 0 , stop = None , step = 1 , convert_to_gray = True , series_number = None , dicom_expected = None , ** kwargs ) : """Simple read function . Internally calls DataReader . Get3DData ( )"""
dr = DataReader ( ) return dr . Get3DData ( datapath = datapath , qt_app = qt_app , dataplus_format = dataplus_format , gui = gui , start = start , stop = stop , step = step , convert_to_gray = convert_to_gray , series_number = series_number , use_economic_dtype = True , dicom_expected = dicom_expected , ** kwargs )
def track_update ( self ) : """Update the lastest updated date in the database ."""
metadata = self . info ( ) metadata . updated_at = dt . datetime . now ( ) self . commit ( )
def get ( equity ) : """Retrieve all current options chains for given equity . . . versionchanged : : 0.5.0 Eliminate special exception handling . Parameters equity : str Equity for which to retrieve options data . Returns optdata : : class : ` ~ pynance . opt . core . Options ` All options data for...
_optmeta = pdr . data . Options ( equity , 'yahoo' ) _optdata = _optmeta . get_all_data ( ) return Options ( _optdata )
async def commission ( self , * , enable_ssh : bool = None , skip_networking : bool = None , skip_storage : bool = None , commissioning_scripts : typing . Sequence [ str ] = None , testing_scripts : typing . Sequence [ str ] = None , wait : bool = False , wait_interval : int = 5 ) : """Commission this machine . :...
params = { "system_id" : self . system_id } if enable_ssh is not None : params [ "enable_ssh" ] = enable_ssh if skip_networking is not None : params [ "skip_networking" ] = skip_networking if skip_storage is not None : params [ "skip_storage" ] = skip_storage if ( commissioning_scripts is not None and len (...
def get_raw_data ( self , section , scale = False ) : """Get the template or complement raw data . : param section : Either template , complement , or both . : param scale : Scale the raw data to pA . : return : The raw data for the section . If section = both then it returns a tuple with both sections . Re...
results = self . get_results ( ) datasets = [ None , None ] if section == 'both' : sections = [ 'template' , 'complement' ] else : sections = [ section ] for n , this_section in enumerate ( sections ) : if not results [ 'has_{}' . format ( this_section ) ] : continue start = results [ 'first_sam...
def _escape_sequence ( self , char ) : """Handle characters seen when in an escape sequence . Most non - vt52 commands start with a left - bracket after the escape and then a stream of parameters and a command ."""
num = ord ( char ) if char == "[" : self . state = "escape-lb" elif char == "(" : self . state = "charset-g0" elif char == ")" : self . state = "charset-g1" elif num in self . escape : self . dispatch ( self . escape [ num ] ) self . state = "stream" elif self . fail_on_unknown_esc : raise Strea...
def Cmatrix ( x , y , sx , sy , theta ) : """Construct a correlation matrix corresponding to the data . The matrix assumes a gaussian correlation function . Parameters x , y : array - like locations at which to evaluate the correlation matirx sx , sy : float major / minor axes of the gaussian correlatio...
C = np . vstack ( [ elliptical_gaussian ( x , y , 1 , i , j , sx , sy , theta ) for i , j in zip ( x , y ) ] ) return C
def registry_hostname ( registry ) : """Strip a reference to a registry to just the hostname : port"""
if registry . startswith ( 'http:' ) or registry . startswith ( 'https:' ) : return urlparse ( registry ) . netloc else : return registry
def make_figure_uhs ( extractors , what ) : """$ oq plot ' uhs ? kind = mean & site _ id = 0'"""
import matplotlib . pyplot as plt fig = plt . figure ( ) got = { } # ( calc _ id , kind ) - > curves for i , ex in enumerate ( extractors ) : uhs = ex . get ( what ) for kind in uhs . kind : got [ ex . calc_id , kind ] = uhs [ kind ] oq = ex . oqparam n_poes = len ( oq . poes ) periods = [ imt . period ...
def write ( self , string ) : """Print provided string to the output ."""
self . _output += self . _options . indentation_character * self . _indentation + string + '\n'
def elcm_profile_create ( irmc_info , param_path ) : """send an eLCM request to create profile To create a profile , a new session is spawned with status ' running ' . When profile is created completely , the session ends . : param irmc _ info : node info : param param _ path : path of profile : returns :...
# Send POST request to the server # NOTE : This task may take time , so set a timeout _irmc_info = dict ( irmc_info ) _irmc_info [ 'irmc_client_timeout' ] = PROFILE_CREATE_TIMEOUT resp = elcm_request ( _irmc_info , method = 'POST' , path = URL_PATH_PROFILE_MGMT + 'get' , params = { 'PARAM_PATH' : param_path } ) if resp...
def contains ( self , name : str ) -> List [ str ] : """Return a list of all keywords containing the given string . > > > from hydpy . core . devicetools import Keywords > > > keywords = Keywords ( ' first _ keyword ' , ' second _ keyword ' , . . . ' keyword _ 3 ' , ' keyword _ 4 ' , . . . ' keyboard ' ) ...
return sorted ( keyword for keyword in self if name in keyword )
def open ( cls , filename , crs = None ) : """Creates a FileCollection from a file in disk . Parameters filename : str Path of the file to read . crs : CRS overrides the crs of the collection , this funtion will not reprojects"""
with fiona . Env ( ) : with fiona . open ( filename , 'r' ) as source : original_crs = CRS ( source . crs ) schema = source . schema length = len ( source ) crs = crs or original_crs ret_val = cls ( filename , crs , schema , length ) return ret_val
def release ( self , path , fh ) : "Run after a read or write operation has finished . This is where we upload on writes"
# print " release ! inpath : " , path in self . _ _ newfiles . keys ( ) # if the path exists in self . _ _ newfiles . keys ( ) , we have a new version to upload try : f = self . __newfiles [ path ] # make a local shortcut to Stringio object f . seek ( 0 , os . SEEK_END ) if f . tell ( ) > 0 : # file has...
def _make_request ( self , conn , method , url , timeout = _Default , ** httplib_request_kw ) : """Perform a request on a given urllib connection object taken from our pool . : param conn : a connection from one of our connection pools : param timeout : Socket timeout in seconds for the request . This can...
self . num_requests += 1 timeout_obj = self . _get_timeout ( timeout ) timeout_obj . start_connect ( ) conn . timeout = timeout_obj . connect_timeout # Trigger any extra validation we need to do . try : self . _validate_conn ( conn ) except ( SocketTimeout , BaseSSLError ) as e : # Py2 raises this as a BaseSSLError...
def add ( self , key , value ) : # type : ( Hashable , Any ) - > None """Adds a new value for the key . : param key : the key for the value . : param value : the value to add ."""
dict . setdefault ( self , key , [ ] ) . append ( value )
def set_property ( self , key , value ) : """Update only one property in the dict"""
self . properties [ key ] = value self . sync_properties ( )
def check_cups_allowed ( func ) : """Check if CUPS is allowd by token"""
@ wraps ( func ) def decorator ( * args , ** kwargs ) : cups = kwargs . get ( 'cups' ) if ( cups and current_user . is_authenticated ( ) and not current_user . allowed ( cups , 'cups' ) ) : return current_app . login_manager . unauthorized ( ) return func ( * args , ** kwargs ) return decorator
def is_article ( self , response , url ) : """Tests if the given response is an article by calling and checking the heuristics set in config . cfg and sitelist . json : param obj response : The response of the site . : param str url : The base _ url ( needed to get the site - specific config from the JSON -...
site = self . __sites_object [ url ] heuristics = self . __get_enabled_heuristics ( url ) self . log . info ( "Checking site: %s" , response . url ) statement = self . __get_condition ( url ) self . log . debug ( "Condition (original): %s" , statement ) for heuristic , condition in heuristics . items ( ) : heuristi...
def read_short ( self ) : """Read an unsigned 16 - bit integer"""
self . bitcount = self . bits = 0 return unpack ( '>H' , self . input . read ( 2 ) ) [ 0 ]
def parse ( self , response ) : """Checks any given response on being an article and if positiv , passes the response to the pipeline . : param obj response : The scrapy response"""
if not self . helper . parse_crawler . content_type ( response ) : return for request in self . helper . parse_crawler . recursive_requests ( response , self , self . ignore_regex , self . ignore_file_extensions ) : yield request yield self . helper . parse_crawler . pass_to_pipeline_if_article ( response , sel...
def add_healthcheck_expect ( self , id_ambiente , expect_string , match_list ) : """Insere um novo healthckeck _ expect e retorna o seu identificador . : param expect _ string : expect _ string . : param id _ ambiente : Identificador do ambiente lógico . : param match _ list : match list . : return : Dicio...
healthcheck_map = dict ( ) healthcheck_map [ 'id_ambiente' ] = id_ambiente healthcheck_map [ 'expect_string' ] = expect_string healthcheck_map [ 'match_list' ] = match_list url = 'healthcheckexpect/add/' code , xml = self . submit ( { 'healthcheck' : healthcheck_map } , 'POST' , url ) return self . response ( code , xm...
def map ( h2 : Histogram2D , ax : Axes , * , show_zero : bool = True , show_values : bool = False , show_colorbar : bool = True , x = None , y = None , ** kwargs ) : """Coloured - rectangle plot of 2D histogram . Parameters show _ zero : Whether to show coloured box for bins with 0 frequency ( otherwise backgro...
# Detect transformation transformed = False if x is not None or y is not None : if not x : x = lambda x , y : x if not y : y = lambda x , y : y transformed = True value_format = kwargs . pop ( "value_format" , lambda x : str ( x ) ) # TODO : Implement correctly the text _ kwargs if isinstanc...
def auth_required_same_user ( * args , ** kwargs ) : """Decorator for requiring an authenticated user to be the same as the user in the URL parameters . By default the user url parameter name to lookup is ` ` id ` ` , but this can be customized by passing an argument : : @ auth _ require _ same _ user ( ' use...
auth_kwargs = { } user_id_parameter_name = 'id' if not ( args and callable ( args [ 0 ] ) ) : auth_kwargs = kwargs if args and isinstance ( args [ 0 ] , str ) : user_id_parameter_name = args [ 0 ] def wrapper ( fn ) : @ wraps ( fn ) @ auth_required ( ** auth_kwargs ) def decorated ( * args ,...
def _generate_struct_type ( self , struct_type , indent_spaces , extra_parameters ) : """Generates a TypeScript interface for a stone struct ."""
namespace = struct_type . namespace if struct_type . doc : self . _emit_tsdoc_header ( struct_type . doc ) parent_type = struct_type . parent_type extends_line = ' extends %s' % fmt_type_name ( parent_type , namespace ) if parent_type else '' self . emit ( 'export interface %s%s {' % ( fmt_type_name ( struct_type ,...
def replace_name ( file_path , new_name ) : '''Change the file name in a path but keep the extension'''
if not file_path : raise Exception ( "File path cannot be empty" ) elif not new_name : raise Exception ( "New name cannot be empty" ) dirname = os . path . dirname ( file_path ) ext = os . path . splitext ( os . path . basename ( file_path ) ) [ 1 ] return os . path . join ( dirname , new_name + ext )
def cmd ( send , msg , args ) : """Handles quotes . Syntax : { command } < number | nick > , ! quote - - add < quote > - - nick < nick > ( - - approve ) , ! quote - - list , ! quote - - delete < number > , ! quote - - edit < number > < quote > - - nick < nick > ! quote - - search ( - - offset < num > ) < number...
session = args [ 'db' ] parser = arguments . ArgParser ( args [ 'config' ] ) parser . add_argument ( '--approve' , action = 'store_true' ) parser . add_argument ( '--nick' , nargs = '?' ) parser . add_argument ( '--offset' , nargs = '?' , type = int , default = 0 ) parser . add_argument ( 'quote' , nargs = '*' ) group ...
def switch_on ( self ) : """Open the valve ."""
success = self . set_status ( CONST . STATUS_ON_INT ) if success : self . _json_state [ 'status' ] = CONST . STATUS_OPEN return success
def delete ( self , block , name ) : """Reset the value of the field named ` name ` to the default"""
self . _kvs . delete ( self . _key ( block , name ) )
def interpolate_delta_t ( delta_t_table , tt ) : """Return interpolated Delta T values for the times in ` tt ` . The 2xN table should provide TT values as element 0 and corresponding Delta T values for element 1 . For times outside the range of the table , a long - term formula is used instead ."""
tt_array , delta_t_array = delta_t_table delta_t = _to_array ( interp ( tt , tt_array , delta_t_array , nan , nan ) ) missing = isnan ( delta_t ) if missing . any ( ) : # Test if we are dealing with an array and proceed appropriately if missing . shape : tt = tt [ missing ] delta_t [ missing ] = del...