signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def execute ( self , debug = False ) : """Execute the engine - currently simple executes all workflows ."""
if debug : # Set some default times for execution ( debugging ) start_time = datetime ( year = 2016 , month = 10 , day = 19 , hour = 12 , minute = 28 , tzinfo = UTC ) duration = timedelta ( seconds = 5 ) end_time = start_time + duration relative_interval = RelativeTimeInterval ( 0 , 0 ) time_interva...
def run ( self , data ) : """Returns : list of W , M * W ll"""
if self . normalize_data : data = cell_normalize ( data ) M , W , ll = poisson_estimate_state ( data , ** self . params ) outputs = [ ] if self . return_w : outputs . append ( W ) if self . return_m : outputs . append ( M ) if self . return_mw : outputs . append ( M . dot ( W ) ) if self . return_mds : ...
def decode_int ( v ) : """decodes and integer from serialization"""
if len ( v ) > 0 and ( v [ 0 ] == b'\x00' or v [ 0 ] == 0 ) : raise Exception ( "No leading zero bytes allowed for integers" ) return big_endian_to_int ( v )
def generate_new_cid ( upstream_cid = None ) : """Generate a new correlation id , possibly based on the given one ."""
if upstream_cid is None : return str ( uuid . uuid4 ( ) ) if getattr ( settings , 'CID_GENERATE' , False ) else None if ( getattr ( settings , 'CID_CONCATENATE_IDS' , False ) and getattr ( settings , 'CID_GENERATE' , False ) ) : return '%s, %s' % ( upstream_cid , str ( uuid . uuid4 ( ) ) ) return upstream_cid
def client_update ( self , client , reason = None , pin = None , current_pin = None , verification_speed = None , row_doubling = None , password = None , bypass_expiration = None , bypass_limit = None , bypass_spacing_minutes = None , bypass_code = None , is_disabled = None , verification_lock = None , password_lock = ...
client = self . _client_id ( client ) body = { } if reason is not None : body [ "reason" ] = reason if pin is not None : body [ "pin" ] = pin if current_pin is not None : body [ "current_pin" ] = current_pin if verification_speed is not None : body [ "verification_speed" ] = verification_speed if row_do...
def send ( self , obj_id ) : """Send email to the assigned lists : param obj _ id : int : return : dict | str"""
response = self . _client . session . post ( '{url}/{id}/send' . format ( url = self . endpoint_url , id = obj_id ) ) return self . process_response ( response )
def group ( self , items , keep_empty = False ) : """Given an iterable of instances , groups them by state using : class : ` ManagedState ` instances as dictionary keys . Returns an ` OrderedDict ` that preserves the order of states from the source : class : ` ~ coaster . utils . classes . LabeledEnum ` . : p...
cls = self . cls if self . cls is not None else type ( self . obj ) # Class of the item being managed groups = OrderedDict ( ) for mstate in self . statemanager . states_by_value . values ( ) : # Ensure we sort groups using the order of states in the source LabeledEnum . # We ' ll discard the unused states later . ...
def marginalize ( self , variables , inplace = True ) : """Marginalize the distribution with respect to the given variables . Parameters variables : list , array - like List of variables to be removed from the marginalized distribution . inplace : boolean If inplace = True it will modify the factor itself...
if len ( variables ) == 0 : raise ValueError ( "Shouldn't be calling marginalize over no variable." ) if not isinstance ( variables , ( list , tuple , np . ndarray ) ) : raise TypeError ( "variables: Expected type iterable, " "got: {var_type}" . format ( var_type = type ( variables ) ) ) for var in variables : ...
def add_moc_from_dict ( self , moc_dict , moc_options = { } ) : """load a MOC from a dict object and display it in Aladin Lite widget Arguments : moc _ dict : the dict containing the MOC cells . Key are the HEALPix orders , values are the pixel indexes , eg : { " 1 " : [ 1,2,4 ] , " 2 " : [ 12,13,14,21,23,25 ...
self . moc_dict = moc_dict self . moc_options = moc_options self . moc_from_dict_flag = not self . moc_from_dict_flag
def _compute_mean ( self , C , mag , ztor , rrup ) : """Compute mean value as in ` ` subroutine getGeom ` ` in ` ` hazgridXnga2 . f ` `"""
gc0 = 0.2418 ci = 0.3846 gch = 0.00607 g4 = 1.7818 ge = 0.554 gm = 1.414 mean = ( gc0 + ci + ztor * gch + C [ 'gc1' ] + gm * mag + C [ 'gc2' ] * ( 10 - mag ) ** 3 + C [ 'gc3' ] * np . log ( rrup + g4 * np . exp ( ge * mag ) ) ) return mean
def _clear_community_details ( community_details ) : '''Clears community details .'''
for key in [ 'acl' , 'mode' ] : _str_elem ( community_details , key ) _mode = community_details . get [ 'mode' ] = community_details . get ( 'mode' ) . lower ( ) if _mode in _COMMUNITY_MODE_MAP . keys ( ) : community_details [ 'mode' ] = _COMMUNITY_MODE_MAP . get ( _mode ) if community_details [ 'mode' ] not in...
def pyle ( argv = None ) : """Execute pyle with the specified arguments , or sys . argv if no arguments specified ."""
parser = argparse . ArgumentParser ( description = __doc__ ) parser . add_argument ( "-m" , "--modules" , dest = "modules" , action = 'append' , help = "import MODULE before evaluation. May be specified more than once." ) parser . add_argument ( "-i" , "--inplace" , dest = "inplace" , action = 'store_true' , default = ...
def suspendMember ( self , clusterId , memberId ) : """Parameters : - clusterId - memberId"""
self . send_suspendMember ( clusterId , memberId ) return self . recv_suspendMember ( )
def eigenvectors ( T , k = None , right = True , ncv = None , reversible = False , mu = None ) : r"""Compute eigenvectors of given transition matrix . Parameters T : scipy . sparse matrix Transition matrix ( stochastic matrix ) . k : int ( optional ) or array - like For integer k compute the first k eigen...
if k is None : raise ValueError ( "Number of eigenvectors required for decomposition of sparse matrix" ) else : if reversible : eigvec = eigenvectors_rev ( T , k , right = right , ncv = ncv , mu = mu ) return eigvec else : eigvec = eigenvectors_nrev ( T , k , right = right , ncv = nc...
def ignore ( self , task , * args , ** kw ) : """Thread it and forget it . For information on the arguments to this method , see work ( ) ."""
# We want to silence errors self . callback ( task , null_cb , False , * args , ** kw )
def smart_open_write ( path = None , mode = 'wb' , encoding = None ) : """Open a file for writing or return ` ` stdout ` ` . Adapted from StackOverflow user " Wolph " ( http : / / stackoverflow . com / a / 17603000 ) ."""
if path is not None : # open a file fh = io . open ( path , mode = mode , encoding = encoding ) else : # open stdout fh = io . open ( sys . stdout . fileno ( ) , mode = mode , encoding = encoding ) # fh = sys . stdout try : yield fh finally : # make sure we don ' t close stdout if fh . fileno ( ) !=...
async def _process_lines ( self , pattern : Optional [ str ] = None ) -> None : """Read line from pipe they match with pattern ."""
if pattern is not None : cmp = re . compile ( pattern ) _LOGGER . debug ( "Start working with pattern '%s'." , pattern ) # read lines while self . is_running : try : line = await self . _input . readline ( ) if not line : break line = line . decode ( ) except Exception : ...
def source_amplitude ( self , kwargs_ps , kwargs_lens ) : """returns the source amplitudes : param kwargs _ ps : : param kwargs _ lens : : return :"""
amp_list = [ ] for i , model in enumerate ( self . _point_source_list ) : amp_list . append ( model . source_amplitude ( kwargs_ps = kwargs_ps [ i ] , kwargs_lens = kwargs_lens ) ) return amp_list
def install_bootstrapped_files ( nb_path = None , server_config = True , DEBUG = False ) : """Installs javascript and exporting server extensions in Jupyter notebook . Args : nb _ path ( string ) : Path to notebook module . server _ config ( boolean ) : Install exporting server extensions . DEBUG ( boolean ...
install_path = None print ( 'Starting hide_code.js install...' ) current_dir = path . abspath ( path . dirname ( __file__ ) ) config_dirs = j_path . jupyter_config_path ( ) notebook_module_path = Utils . get_notebook_module_dir ( ) # check for config directory with a " custom " folder # TODO update this logic to check ...
def update ( self ) : """Draw the scroll bar ."""
# Sort out chars cursor = u"█" if self . _canvas . unicode_aware else "O" back = u"░" if self . _canvas . unicode_aware else "|" # Now draw . . . try : sb_pos = self . _get_pos ( ) sb_pos = min ( 1 , max ( 0 , sb_pos ) ) sb_pos = max ( int ( self . _height * sb_pos ) - 1 , 0 ) except ZeroDivisionError : ...
def _get_batch_name ( items , skip_jointcheck = False ) : """Retrieve the shared batch name for a group of items ."""
batch_names = collections . defaultdict ( int ) has_joint = any ( [ is_joint ( d ) for d in items ] ) for data in items : if has_joint and not skip_jointcheck : batches = dd . get_sample_name ( data ) else : batches = dd . get_batches ( data ) or dd . get_sample_name ( data ) if not isinstan...
def _get_read_names ( self , search_result , max_range ) : '''_ get _ read _ names - loops through hmm hits and their alignment spans to determine if they are potentially linked ( for example , if one gene in a contig hits a hmm more than once , in two different conserved regions of that gene ) and combines t...
splits = { } # Define an output dictionary to be filled spans = [ ] for result in search_result : # Create a table ( list of rows contain span , and complement information spans += list ( result . each ( [ SequenceSearchResult . QUERY_ID_FIELD , SequenceSearchResult . ALIGNMENT_DIRECTION , SequenceSearchResult . HI...
async def profile ( self ) : """| coro | Gets the user ' s profile . . . note : : This only applies to non - bot accounts . Raises Forbidden Not allowed to fetch profiles . HTTPException Fetching the profile failed . Returns : class : ` Profile ` The profile of the user ."""
state = self . _state data = await state . http . get_user_profile ( self . id ) def transform ( d ) : return state . _get_guild ( int ( d [ 'id' ] ) ) since = data . get ( 'premium_since' ) mutual_guilds = list ( filter ( None , map ( transform , data . get ( 'mutual_guilds' , [ ] ) ) ) ) return Profile ( flags = ...
def check_2d ( inp ) : """Check input to be a matrix . Converts lists of lists to np . ndarray . Also allows the input to be a scipy sparse matrix . Parameters inp : obj Input matrix Returns numpy . ndarray , scipy . sparse or None Input matrix or None Examples > > > check _ 2d ( [ [ 0 , 1 ] , [ 2...
if isinstance ( inp , list ) : return check_2d ( np . array ( inp ) ) if isinstance ( inp , ( np . ndarray , np . matrixlib . defmatrix . matrix ) ) : if inp . ndim == 2 : # input is a dense matrix return inp if sps . issparse ( inp ) : if inp . ndim == 2 : # input is a sparse matrix return ...
def summarize ( self , test_arr , vectorizable_token , sentence_list , limit = 5 ) : '''Summarize input document . Args : test _ arr : ` np . ndarray ` of observed data points . . vectorizable _ token : is - a ` VectorizableToken ` . sentence _ list : ` list ` of all sentences . limit : The number of sele...
if isinstance ( vectorizable_token , VectorizableToken ) is False : raise TypeError ( ) _ = self . inference ( test_arr ) score_arr = self . __encoder_decoder_controller . get_reconstruction_error ( ) score_arr = score_arr . reshape ( ( score_arr . shape [ 0 ] , - 1 ) ) . mean ( axis = 1 ) score_list = score_arr . ...
def exec ( self , * command_tokens , ** command_env ) : """: meth : ` . WCommandProto . exec ` implementation"""
mutated_command_tokens = self . mutate_command_tokens ( * command_tokens ) if mutated_command_tokens is not None : command = self . selector ( ) . select ( * mutated_command_tokens , ** command_env ) if command is not None : return command . exec ( * mutated_command_tokens , ** command_env ) raise Runti...
def get_list ( self , search = '' , start = 0 , limit = 0 , order_by = '' , order_by_dir = 'ASC' , published_only = False , minimal = False ) : """Get a list of items : param search : str : param start : int : param limit : int : param order _ by : str : param order _ by _ dir : str : param published _ ...
parameters = { } args = [ 'search' , 'start' , 'limit' , 'minimal' ] for arg in args : if arg in locals ( ) and locals ( ) [ arg ] : parameters [ arg ] = locals ( ) [ arg ] if order_by : parameters [ 'orderBy' ] = order_by if order_by_dir : parameters [ 'orderByDir' ] = order_by_dir if published_onl...
def get_arp_output_arp_entry_age ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_arp = ET . Element ( "get_arp" ) config = get_arp output = ET . SubElement ( get_arp , "output" ) arp_entry = ET . SubElement ( output , "arp-entry" ) ip_address_key = ET . SubElement ( arp_entry , "ip-address" ) ip_address_key . text = kwargs . pop ( 'ip_address' ) age = ET . Sub...
def _build_primitive_cell ( self ) : """primitive _ matrix : Relative axes of primitive cell to the input unit cell . Relative axes to the supercell is calculated by : supercell _ matrix ^ - 1 * primitive _ matrix Therefore primitive cell lattice is finally calculated by : ( supercell _ lattice * ( superc...
self . _primitive = self . _get_primitive_cell ( self . _supercell , self . _supercell_matrix , self . _primitive_matrix )
def __field_to_parameter_type ( self , field ) : """Converts the field variant type into a string describing the parameter . Args : field : An instance of a subclass of messages . Field . Returns : A string corresponding to the variant enum of the field , with a few exceptions . In the case of signed ints...
# We use lowercase values for types ( e . g . ' string ' instead of ' STRING ' ) . variant = field . variant if variant == messages . Variant . MESSAGE : raise TypeError ( 'A message variant can\'t be used in a parameter.' ) custom_variant_map = { messages . Variant . SINT32 : 'int32' , messages . Variant . SINT64 ...
def map ( func , data , num_workers = None ) : # type : ( callable , Iterable , Optional [ int ] ) - > Iterable """Map an iterable using multithreading > > > s = pd . Series ( range ( 120 , 0 , - 1 ) ) > > > s2 = map ( lambda i , x : x * * 3.75 , s ) > > > isinstance ( s2 , type ( s ) ) True > > > len ( s...
backend = ThreadPool ( n_workers = num_workers ) iterable = None # pd . Series didn ' t have . items ( ) until pandas 0.21, # so iteritems for older versions for method in ( 'iterrows' , 'iteritems' , 'items' ) : if hasattr ( data , method ) : iterable = getattr ( data , method ) ( ) break if iterab...
def term_to_binary ( term , compressed = False ) : """Encode Python types into Erlang terms in binary data"""
data_uncompressed = _term_to_binary ( term ) if compressed is False : return b_chr ( _TAG_VERSION ) + data_uncompressed else : if compressed is True : compressed = 6 if compressed < 0 or compressed > 9 : raise InputException ( 'compressed in [0..9]' ) data_compressed = zlib . compress ( ...
def executable_path ( conn , executable ) : """Remote validator that accepts a connection object to ensure that a certain executable is available returning its full path if so . Otherwise an exception with thorough details will be raised , informing the user that the executable was not found ."""
executable_path = conn . remote_module . which ( executable ) if not executable_path : raise ExecutableNotFound ( executable , conn . hostname ) return executable_path
def get_param_arg ( param , idx , klass , arg , attr = 'id' ) : """Return the correct value for a fabric from ` arg ` ."""
if isinstance ( arg , klass ) : return getattr ( arg , attr ) elif isinstance ( arg , ( int , str ) ) : return arg else : raise TypeError ( "%s[%d] must be int, str, or %s, not %s" % ( param , idx , klass . __name__ , type ( arg ) . __name__ ) )
def convert_date ( date ) : """Convert string to datetime object ."""
date = convert_month ( date , shorten = False ) clean_string = convert_string ( date ) return datetime . strptime ( clean_string , DATE_FMT . replace ( '-' , '' ) )
def del_export ( exports = '/etc/exports' , path = None ) : '''Remove an export CLI Example : . . code - block : : bash salt ' * ' nfs . del _ export / media / storage'''
edict = list_exports ( exports ) del edict [ path ] _write_exports ( exports , edict ) return edict
async def send_pages ( self ) : """A helper utility to send the page output from : attr : ` paginator ` to the destination ."""
destination = self . get_destination ( ) for page in self . paginator . pages : await destination . send ( page )
def create_tags ( user ) : """Create a tag ."""
values = { 'id' : utils . gen_uuid ( ) , 'created_at' : datetime . datetime . utcnow ( ) . isoformat ( ) } values . update ( schemas . tag . post ( flask . request . json ) ) with flask . g . db_conn . begin ( ) : where_clause = sql . and_ ( _TABLE . c . name == values [ 'name' ] ) query = sql . select ( [ _TAB...
def from_dict ( cls , d ) : """Convert a dictionary into an xarray . DataArray Input dict can take several forms : : d = { ' dims ' : ( ' t ' ) , ' data ' : x } d = { ' coords ' : { ' t ' : { ' dims ' : ' t ' , ' data ' : t , ' attrs ' : { ' units ' : ' s ' } } } , ' attrs ' : { ' title ' : ' air temperat...
coords = None if 'coords' in d : try : coords = OrderedDict ( [ ( k , ( v [ 'dims' ] , v [ 'data' ] , v . get ( 'attrs' ) ) ) for k , v in d [ 'coords' ] . items ( ) ] ) except KeyError as e : raise ValueError ( "cannot convert dict when coords are missing the key " "'{dims_data}'" . format ( di...
def select ( files , start , stop ) : """Helper function for handling start and stop indices"""
if start or stop : if start is None : start = 0 if stop is None : stop = len ( files ) files = files [ start : stop ] return files
def current_fact_index ( self ) : """Current fact index in the self . facts list ."""
facts_ids = [ fact . id for fact in self . facts ] return facts_ids . index ( self . current_fact . id )
def _load_from_ini_py2 ( ini ) : """py2从单个配置文件中 , 获取设置 : param : : param ini : : return :"""
logger . debug ( '使用PY2不支持自定义default_section,其默认值是:%s' % _DEFAULT_SECTION ) cf = configparser . ConfigParser ( ) cf . read ( ini ) settings = OrderedDict ( ) for k , v in cf . defaults ( ) . items ( ) : settings [ k . upper ( ) ] = convert_value ( v ) cf . _defaults = { } for section in cf . sections ( ) : sect...
def atlasdb_renew_peer ( peer_hostport , now , con = None , path = None ) : """Renew a peer ' s discovery time"""
with AtlasDBOpen ( con = con , path = path ) as dbcon : if now is None : now = time . time ( ) sql = "UPDATE peers SET discovery_time = ? WHERE peer_hostport = ?;" args = ( now , peer_hostport ) cur = dbcon . cursor ( ) res = atlasdb_query_execute ( cur , sql , args ) dbcon . commit ( ) ...
def ask_string ( message = 'Enter something.' , default = '' , title = '' ) : """Show a box in which a user can enter some text . You may optionally specify some default text , which will appear in the entry - box when it is displayed . Returns the text that the user entered , or None if he cancels the operat...
return backend_api . opendialog ( "ask_string" , dict ( message = message , default = default , title = title ) )
def _ensure_parameters ( self ) : """Attempts to load and verify the CTE node parameters . Will use default values for all missing parameters , and raise an exception if a parameter ' s value cannot be verified . This method will only perform these actions once , and set the : attr : ` _ parameters _ checked ...
if hasattr ( self , "_parameters_checked" ) : return if ( not hasattr ( self . model , "_cte_node_table" ) or self . model . _cte_node_table is None ) : setattr ( self . model , "_cte_node_table" , self . DEFAULT_TABLE_NAME ) if ( not hasattr ( self . model , "_cte_node_depth" ) or self . model . _cte_node_dept...
def build_maps ( self , losses , clp , stats = ( ) ) : """: param losses : an array of shape ( A , R , P ) : param clp : a list of C conditional loss poes : param stats : list of pairs [ ( statname , statfunc ) , . . . ] : returns : an array of loss _ maps of shape ( A , R , C , LI )"""
shp = losses . shape [ : 2 ] + ( len ( clp ) , len ( losses . dtype ) ) # ( A , R , C , LI ) array = numpy . zeros ( shp , F32 ) for lti , lt in enumerate ( losses . dtype . names ) : for a , losses_ in enumerate ( losses [ lt ] ) : for r , ls in enumerate ( losses_ ) : for c , poe in enumerate ...
def check ( self , state , * args , ** kwargs ) : """Check if this engine can be used for execution on the current state . A callback ` check _ failure ` is called upon failed checks . Note that the execution can still fail even if check ( ) returns True . You should only override this method in a subclass in o...
return self . _check ( state , * args , ** kwargs )
def prepend ( self , symbol , metadata , start_time = None ) : """Prepend a metadata entry for ` symbol ` Parameters symbol : ` str ` symbol name for the item metadata : ` dict ` to be persisted start _ time : ` datetime . datetime ` when metadata becomes effective Default : datetime . datetime . mi...
if metadata is None : return if start_time is None : start_time = dt . min old_metadata = self . find_one ( { 'symbol' : symbol } , sort = [ ( 'start_time' , pymongo . ASCENDING ) ] ) if old_metadata is not None : if old_metadata [ 'start_time' ] <= start_time : raise ValueError ( 'start_time={} is ...
def curve4_bezier ( p1 , p2 , p3 , p4 ) : """Generate the vertices for a third order Bezier curve . The vertices returned by this function can be passed to a LineVisual or ArrowVisual . Parameters p1 : array 2D coordinates of the start point p2 : array 2D coordinates of the first curve point p3 : ar...
x1 , y1 = p1 x2 , y2 = p2 x3 , y3 = p3 x4 , y4 = p4 points = [ ] _curve4_recursive_bezier ( points , x1 , y1 , x2 , y2 , x3 , y3 , x4 , y4 ) dx , dy = points [ 0 ] [ 0 ] - x1 , points [ 0 ] [ 1 ] - y1 if ( dx * dx + dy * dy ) > 1e-10 : points . insert ( 0 , ( x1 , y1 ) ) dx , dy = points [ - 1 ] [ 0 ] - x4 , points...
def bbox ( self ) : """Bounding box as minimum and maximum coordinates ."""
mn = amin ( self . coordinates , axis = 0 ) mx = amax ( self . coordinates , axis = 0 ) return concatenate ( ( mn , mx ) )
def place_object ( self , object , column = None , row = None , column_span = 1 , row_span = 1 , alignment = 1 ) : """This adds either one of our simplified objects or a QWidget to the grid at the specified position , appends the object to self . objects . alignment = 0 Fill the space . alignment = 1 Left - j...
# pick a column if column == None : column = self . _auto_column self . _auto_column += 1 # pick a row if row == None : row = self . _auto_row # create the object self . objects . append ( object ) # add the widget to the layout try : object . _widget widget = object . _widget # allows the user to s...
def rpc_get_num_names ( self , ** con_info ) : """Get the number of names that exist and are not expired Return { ' status ' : True , ' count ' : count } on success Return { ' error ' : . . . } on error"""
db = get_db_state ( self . working_dir ) num_names = db . get_num_names ( ) db . close ( ) return self . success_response ( { 'count' : num_names } )
def wait_until_element_present ( self , element , timeout = None ) : """Search element and wait until it is found : param element : PageElement or element locator as a tuple ( locator _ type , locator _ value ) to be found : param timeout : max time to wait : returns : the web element if it is present : rty...
return self . _wait_until ( self . _expected_condition_find_element , element , timeout )
def oregontrail ( channel , nick , rest ) : "It ' s edutainment !"
rest = rest . strip ( ) if rest : who = rest . strip ( ) else : who = random . choice ( [ nick , channel , 'pmxbot' ] ) action = random . choice ( phrases . otrail_actions ) if action in ( 'has' , 'has died from' ) : issue = random . choice ( phrases . otrail_issues ) text = '%s %s %s.' % ( who , action...
def collect_api_results ( input_data , url , headers , api , batch_size , kwargs ) : """Optionally split up a single request into a series of requests to ensure timely HTTP responses . Could eventually speed up the time required to receive a response by sending batches to the indico API concurrently"""
if batch_size : results = [ ] for batch in batched ( input_data , size = batch_size ) : try : result = send_request ( batch , api , url , headers , kwargs ) if isinstance ( result , list ) : results . extend ( result ) else : results . ...
def _create_sata_controllers ( sata_controllers ) : '''Returns a list of vim . vm . device . VirtualDeviceSpec objects representing SATA controllers sata _ controllers SATA properties'''
sata_ctrls = [ ] keys = range ( - 15000 , - 15050 , - 1 ) if sata_controllers : devs = [ sata [ 'adapter' ] for sata in sata_controllers ] log . trace ( 'Creating SATA controllers %s' , devs ) for sata , key in zip ( sata_controllers , keys ) : sata_ctrls . append ( _apply_sata_controller_config ( s...
def _update ( self , data ) : '''Update the line using the blob of json - parsed data directly from the API .'''
self . bullet = data [ 'bullet' ] self . level = data [ 'level' ] self . text = WikiText ( data [ 'text_raw' ] , data [ 'text_rendered' ] )
def _process_ddg2p_annotations ( self , limit ) : """The ddg2p annotations associate a gene symbol to an omim disease , along with some HPO ids and pubs . The gene symbols come from gencode , which in turn come from HGNC official gene symbols . Therefore , we use the HGNC source class to get the id / symbol m...
line_counter = 0 if self . graph is not None : graph = self . graph else : graph = self . graph # in order for this to work , we need to map the HGNC id - symbol ; hgnc = HGNC ( self . graph_type , self . are_bnodes_skolemized ) hgnc_symbol_id_map = hgnc . get_symbol_id_map ( ) myzip = ZipFile ( '/' . join ( ( ...
def export ( self , name , columns , points ) : """Write the points in Riemann ."""
for i in range ( len ( columns ) ) : if not isinstance ( points [ i ] , Number ) : continue else : data = { 'host' : self . hostname , 'service' : name + " " + columns [ i ] , 'metric' : points [ i ] } logger . debug ( data ) try : self . client . send ( data ) ...
def update_dvportgroup ( portgroup_ref , spec ) : '''Updates a distributed virtual portgroup portgroup _ ref The portgroup reference spec Portgroup spec ( vim . DVPortgroupConfigSpec )'''
pg_name = get_managed_object_name ( portgroup_ref ) log . trace ( 'Updating portgrouo %s' , pg_name ) try : task = portgroup_ref . ReconfigureDVPortgroup_Task ( spec ) except vim . fault . NoPermission as exc : log . exception ( exc ) raise salt . exceptions . VMwareApiError ( 'Not enough permissions. Requi...
def set_attribute ( self , code , value ) : """Set attribute for user"""
attr , _ = self . get_or_create ( code = code ) attr . value = value attr . save ( )
def _print ( self , method , * args , ** kwargs ) : """Output format affects integration tests . @ see : IntegrationTests . mock _ output"""
sess_method = getattr ( self . _session , method ) try : headers = kwargs [ 'headers' ] except KeyError : headers = { } tpl = '[%s] %s %s' print ( tpl % ( method , args [ 0 ] , headers ) , end = ' ' ) try : r = sess_method ( * args , ** kwargs ) except : e = sys . exc_info ( ) e_str = "%s: %s" % ( e...
def join ( self ) : """Wait for all task to finish"""
pending = set ( ) exceptions = set ( ) while len ( self . _tasks ) > 0 or len ( pending ) > 0 : while len ( self . _tasks ) > 0 and len ( pending ) < self . _concurrency : task , args , kwargs = self . _tasks . pop ( 0 ) pending . add ( task ( * args , ** kwargs ) ) ( done , pending ) = yield fr...
def to_query_parameters_dict ( parameters ) : """Converts a dictionary of parameter values into query parameters . : type parameters : Mapping [ str , Any ] : param parameters : Dictionary of query parameter values . : rtype : List [ google . cloud . bigquery . query . _ AbstractQueryParameter ] : returns :...
return [ scalar_to_query_parameter ( value , name = name ) for name , value in six . iteritems ( parameters ) ]
def control ( self , key ) : """Send a control command ."""
if not self . connection : raise exceptions . ConnectionClosed ( ) payload = json . dumps ( { "method" : "ms.remote.control" , "params" : { "Cmd" : "Click" , "DataOfCmd" : key , "Option" : "false" , "TypeOfRemote" : "SendRemoteKey" } } ) logging . info ( "Sending control command: %s" , key ) self . connection . sen...
def list_datastores ( kwargs = None , call = None ) : '''List all the datastores for this VMware environment CLI Example : . . code - block : : bash salt - cloud - f list _ datastores my - vmware - config'''
if call != 'function' : raise SaltCloudSystemExit ( 'The list_datastores function must be called with ' '-f or --function.' ) return { 'Datastores' : salt . utils . vmware . list_datastores ( _get_si ( ) ) }
def distance ( p1 , p2 ) : """Cartesian distance between two PoseStamped or PoseLists : param p1 : point 1 ( list , Pose or PoseStamped ) : param p2 : point 2 ( list , Pose or PoseStamped ) : return : cartesian distance ( float )"""
def xyz ( some_pose ) : if isinstance ( some_pose , PoseStamped ) : return some_pose . pose . position . x , some_pose . pose . position . y , some_pose . pose . position . z elif isinstance ( some_pose , Pose ) : return some_pose . position . x , some_pose . position . y , some_pose . position ...
def export_to_txt ( table , filename_or_fobj = None , encoding = None , frame_style = "ASCII" , safe_none_frame = True , * args , ** kwargs ) : """Export a ` rows . Table ` to text . This function can return the result as a string or save into a file ( via filename or file - like object ) . ` encoding ` could...
# TODO : will work only if table . fields is OrderedDict frame_style = _parse_frame_style ( frame_style ) frame = FRAMES [ frame_style . lower ( ) ] serialized_table = serialize ( table , * args , ** kwargs ) field_names = next ( serialized_table ) table_rows = list ( serialized_table ) max_sizes = _max_column_sizes ( ...
def SetupPrometheusEndpointOnPort ( port , addr = '' ) : """Exports Prometheus metrics on an HTTPServer running in its own thread . The server runs on the given port and is by default listenning on all interfaces . This HTTPServer is fully independent of Django and its stack . This offers the advantage that e...
assert os . environ . get ( 'RUN_MAIN' ) != 'true' , ( 'The thread-based exporter can\'t be safely used when django\'s ' 'autoreloader is active. Use the URL exporter, or start django ' 'with --noreload. See documentation/exports.md.' ) prometheus_client . start_http_server ( port , addr = addr )
def control_gate ( control : Qubit , gate : Gate ) -> Gate : """Return a controlled unitary gate . Given a gate acting on K qubits , return a new gate on K + 1 qubits prepended with a control bit ."""
if control in gate . qubits : raise ValueError ( 'Gate and control qubits overlap' ) qubits = [ control , * gate . qubits ] gate_tensor = join_gates ( P0 ( control ) , identity_gate ( gate . qubits ) ) . tensor + join_gates ( P1 ( control ) , gate ) . tensor controlled_gate = Gate ( qubits = qubits , tensor = gate_...
def unregister ( self , measurement_class , callback ) : """Stop notifying ` ` callback ` ` of new values of ` ` measurement _ class ` ` . If the callback wasn ' t previously registered , this method will have no effect ."""
self . callbacks [ Measurement . name_from_class ( measurement_class ) ] . remove ( callback )
def copy ( self ) : """Make a copy of the SegmentList . : return : A copy of the SegmentList instance . : rtype : angr . analyses . cfg _ fast . SegmentList"""
n = SegmentList ( ) n . _list = [ a . copy ( ) for a in self . _list ] n . _bytes_occupied = self . _bytes_occupied return n
def _init_glyph ( self , plot , mapping , properties ) : """Returns a Bokeh glyph object ."""
box = Span ( level = properties . get ( 'level' , 'glyph' ) , ** mapping ) plot . renderers . append ( box ) return None , box
def _create_sync_map ( self , sync_root ) : """If requested , check that the computed sync map is consistent . Then , add it to the Task ."""
sync_map = SyncMap ( tree = sync_root , rconf = self . rconf , logger = self . logger ) if self . rconf . safety_checks : self . log ( u"Running sanity check on computed sync map..." ) if not sync_map . leaves_are_consistent : self . _step_failure ( ValueError ( u"The computed sync map contains inconsis...
def joinStringsInList ( literalEntities , prefLanguage = "en" ) : """from a list of literals , returns the ones in prefLanguage joined up . if the desired language specification is not available , join all up"""
match = [ ] if len ( literalEntities ) == 1 : return literalEntities [ 0 ] elif len ( literalEntities ) > 1 : for x in literalEntities : if getattr ( x , 'language' ) and getattr ( x , 'language' ) == prefLanguage : match . append ( x ) if not match : # don ' t bother about language ...
def _ctypes_splice ( parameter ) : """Returns a list of variable names that define the size of each dimension ."""
params = parameter . ctypes_parameter ( ) if parameter . direction == "(inout)" and ( "allocatable" in parameter . modifiers or "pointer" in parameter . modifiers ) : return ', ' . join ( params [ 1 : - 1 ] ) else : return ', ' . join ( params [ 1 : : ] )
def index ( self , axes ) : """: param axes : The Axes instance to find the index of . : type axes : Axes : rtype : int"""
return None if axes is self . _colormap_axes else self . _axes . index ( axes )
def decorate_callable ( self , target ) : """Called as a decorator ."""
# noinspection PyUnusedLocal def absorb_mocks ( test_case , * args ) : return target ( test_case ) should_absorb = not ( self . pass_mocks or isinstance ( target , type ) ) result = absorb_mocks if should_absorb else target for patcher in self . patchers : result = patcher ( result ) return result
async def container_dump ( self , container , container_type , params = None , obj = None ) : """Dumps container of elements to the writer . : param container : : param container _ type : : param params : : param obj : : return :"""
elem_type = x . container_elem_type ( container_type , params ) obj = [ ] if not x . has_elem ( obj ) else x . get_elem ( obj ) # todo : pod container , just concat blobs / serialized content together . loading = size / elem size . . . if container is None : # todo : reconsider return NoSetSentinel ( ) # if not sel...
def H6 ( self ) : "Sum average ."
if not hasattr ( self , '_H6' ) : self . _H6 = ( ( self . rlevels2 + 2 ) * self . p_xplusy ) . sum ( 1 ) return self . _H6
def databases ( self ) : """list of databases available from eutils ( per einfo query )"""
try : return self . _databases except AttributeError : self . _databases = self . einfo ( ) . databases return self . _databases
def send_email ( self , recipients , subject , body , attachments = None ) : """Prepare and send email to the recipients : param recipients : a list of email or name , email strings : param subject : the email subject : param body : the email body : param attachments : list of email attachments : returns ...
recipient_pairs = map ( self . parse_email , recipients ) template_context = { "recipients" : "\n" . join ( map ( lambda p : formataddr ( p ) , recipient_pairs ) ) } body_template = Template ( safe_unicode ( body ) ) . safe_substitute ( ** template_context ) _preamble = "This is a multi-part message in MIME format.\n" ...
def get_bookmarks ( self , folder = 'unread' , limit = 25 , have = None ) : """Return list of user ' s bookmarks . : param str folder : Optional . Possible values are unread ( default ) , starred , archive , or a folder _ id value . : param int limit : Optional . A number between 1 and 500 , default 25. : p...
path = 'bookmarks/list' params = { 'folder_id' : folder , 'limit' : limit } if have : have_concat = ',' . join ( str ( id_ ) for id_ in have ) params [ 'have' ] = have_concat response = self . request ( path , params ) items = response [ 'data' ] bookmarks = [ ] for item in items : if item . get ( 'type' ) ...
def RegexField ( regex , default = NOTHING , required = True , repr = True , cmp = True , key = None ) : """Create new str field on a model . : param regex : regex validation string ( e . g . " [ ^ @ ] + @ [ ^ @ ] + " for email ) : param default : any string value : param bool required : whether or not the ob...
default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , string_types , validators . regex ( regex ) ) return attrib ( default = default , converter = converters . str_if_not_none , validator = validator , repr = repr , cmp = cmp , metadata = dict ( key ...
async def _load_message_field ( self , reader , msg , field ) : """Loads message field from the reader . Field is defined by the message field specification . Returns loaded value , supports field reference . : param reader : : param msg : : param field : : return :"""
fname , ftype , params = field [ 0 ] , field [ 1 ] , field [ 2 : ] await self . load_field ( reader , ftype , params , eref ( msg , fname ) )
def normalize_dict ( dictionary , ** kwargs ) : """Given an dict , normalize all of their keys using normalize function ."""
result = { } if isinstance ( dictionary , dict ) : keys = list ( dictionary . keys ( ) ) for key in keys : result [ normalizer ( key , ** kwargs ) ] = normalize_dict ( dictionary . get ( key ) , ** kwargs ) else : result = dictionary return result
def safe_chmod ( path , mode ) : """Set the permissions mode on path , but only if it differs from the current mode ."""
if stat . S_IMODE ( os . stat ( path ) . st_mode ) != mode : os . chmod ( path , mode )
def margin ( self , value ) : """Setter for * * self . _ _ margin * * attribute . : param value : Attribute value . : type value : int"""
if value is not None : assert type ( value ) is int , "'{0}' attribute: '{1}' type is not 'int'!" . format ( "margin" , value ) assert value > 0 , "'{0}' attribute: '{1}' need to be exactly positive!" . format ( "margin" , value ) self . __margin = value
def retrieve ( self , request , * args , ** kwargs ) : """To set quota limit issue a * * PUT * * request against * / api / quotas / < quota uuid > * * with limit values . Please note that if a quota is a cache of a backend quota ( e . g . ' storage ' size of an OpenStack tenant ) , it will be impossible to modi...
return super ( QuotaViewSet , self ) . retrieve ( request , * args , ** kwargs )
def format ( self ) : '''Return format dict .'''
c = n = '' if not self . both : c = ' (code only)' if self . leng : n = ' (%s)' % _nameof ( self . leng ) return _kwds ( base = self . base , item = self . item , leng = n , code = c , kind = self . kind )
def remove_datastore ( datastore , service_instance = None ) : '''Removes a datastore . If multiple datastores an error is raised . datastore Datastore name service _ instance Service instance ( vim . ServiceInstance ) of the vCenter / ESXi host . Default is None . . . code - block : : bash salt ' * '...
log . trace ( 'Removing datastore \'%s\'' , datastore ) target = _get_proxy_target ( service_instance ) datastores = salt . utils . vmware . get_datastores ( service_instance , reference = target , datastore_names = [ datastore ] ) if not datastores : raise VMwareObjectRetrievalError ( 'Datastore \'{0}\' was not fo...
def render_settingsLink ( self , ctx , data ) : """Add the URL of the settings page to the given tag . @ see L { xmantissa . webnav . settingsLink }"""
return settingsLink ( self . translator , self . pageComponents . settings , ctx . tag )
def get_minions ( ) : '''Return a list of minions'''
with _get_serv ( ret = None , commit = True ) as cur : sql = '''SELECT DISTINCT id FROM `salt_returns`''' cur . execute ( sql ) data = cur . fetchall ( ) ret = [ ] for minion in data : ret . append ( minion [ 0 ] ) return ret
def histogram ( data , bins = None , * args , ** kwargs ) : """Facade function to create 1D histograms . This proceeds in three steps : 1 ) Based on magical parameter bins , construct bins for the histogram 2 ) Calculate frequencies for the bins 3 ) Construct the histogram object itself * Guiding principl...
import numpy as np from . histogram1d import Histogram1D , calculate_frequencies from . binnings import calculate_bins adaptive = kwargs . pop ( "adaptive" , False ) dtype = kwargs . pop ( "dtype" , None ) if isinstance ( data , tuple ) and isinstance ( data [ 0 ] , str ) : # Works for groupby DataSeries return his...
def next ( self , data , final = False , to_buffer = False ) : """Add more input to the HMAC SHA1."""
if final : self . flags = pyhsm . defines . YSM_HMAC_SHA1_FINAL else : self . flags = 0x0 if to_buffer : self . flags |= pyhsm . defines . YSM_HMAC_SHA1_TO_BUFFER self . payload = _raw_pack ( self . key_handle , self . flags , data ) self . final = final return self
def function_call_prepare_action ( self , text , loc , fun ) : """Code executed after recognising a function call ( type and function name )"""
exshared . setpos ( loc , text ) if DEBUG > 0 : print ( "FUN_PREP:" , fun ) if DEBUG == 2 : self . symtab . display ( ) if DEBUG > 2 : return index = self . symtab . lookup_symbol ( fun . name , SharedData . KINDS . FUNCTION ) if index == None : raise SemanticException ( "'%s' is not a f...
def arccalibration_direct ( wv_master , ntriplets_master , ratios_master_sorted , triplets_master_sorted_list , xpos_arc , naxis1_arc , crpix1 , wv_ini_search , wv_end_search , wvmin_useful = None , wvmax_useful = None , error_xpos_arc = 1.0 , times_sigma_r = 3.0 , frac_triplets_for_sum = 0.50 , times_sigma_theil_sen =...
nlines_master = wv_master . size delta_wv = 0.20 * ( wv_master . max ( ) - wv_master . min ( ) ) if wv_ini_search is None : wv_ini_search = wv_master . min ( ) - delta_wv if wv_end_search is None : wv_end_search = wv_master . max ( ) + delta_wv nlines_arc = xpos_arc . size if nlines_arc < 5 : raise ValueErr...
def reset_generation ( self , trigger ) : """Re - arms the analog output according to current settings : param trigger : name of the trigger terminal . ` ` None ` ` value means generation begins immediately on run : type trigger : str"""
self . tone_lock . acquire ( ) npts = self . stim . size try : self . aotask = AOTaskFinite ( self . aochan , self . fs , npts , trigsrc = trigger ) self . aotask . write ( self . stim ) if self . attenuator is not None : self . attenuator . SetAtten ( self . atten ) else : # print " ERROR : att...
def assertFileSizeGreater ( self , filename , size , msg = None ) : '''Fail if ` ` filename ` ` ' s size is not greater than ` ` size ` ` as determined by the ' > ' operator . Parameters filename : str , bytes , file - like size : int , float msg : str If not provided , the : mod : ` marbles . mixins ` ...
fsize = self . _get_file_size ( filename ) self . assertGreater ( fsize , size , msg = msg )
def _archive_write_data ( archive , data ) : """Write data to archive . This will only be called with a non - empty string ."""
n = libarchive . calls . archive_write . c_archive_write_data ( archive , ctypes . cast ( ctypes . c_char_p ( data ) , ctypes . c_void_p ) , len ( data ) ) if n == 0 : message = c_archive_error_string ( archive ) raise ValueError ( "No bytes were written. Error? [%s]" % ( message ) )