signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _kill_process_type ( self , process_type , allow_graceful = False , check_alive = True , wait = False ) : """Kill a process of a given type . If the process type is PROCESS _ TYPE _ REDIS _ SERVER , then we will kill all of the Redis servers . If the process was started in valgrind , then we will raise an...
process_infos = self . all_processes [ process_type ] if process_type != ray_constants . PROCESS_TYPE_REDIS_SERVER : assert len ( process_infos ) == 1 for process_info in process_infos : process = process_info . process # Handle the case where the process has already exited . if process . poll ( ) is no...
def _prepare_conn_args ( self , kwargs ) : '''Set connection arguments for remote or local connection .'''
kwargs [ 'connect_over_uds' ] = True kwargs [ 'timeout' ] = kwargs . get ( 'timeout' , 60 ) kwargs [ 'cookie' ] = kwargs . get ( 'cookie' , 'admin' ) if self . _use_remote_connection ( kwargs ) : kwargs [ 'transport' ] = kwargs . get ( 'transport' , 'https' ) if kwargs [ 'transport' ] == 'https' : kwarg...
def start ( self ) : """Overrides default start behaviour by raising ConnectionError instead of custom requests _ mock . exceptions . NoMockAddress ."""
if self . _http_last_send is not None : raise RuntimeError ( 'HttpMock has already been started' ) # 1 ) save request . Session . send in self . _ last _ send # 2 ) replace request . Session . send with MockerCore send function super ( HttpMock , self ) . start ( ) # 3 ) save MockerCore send function in self . _ ht...
def reformat_input ( self , ** kwargs ) : """Reformat input data"""
reformatted_input = { } needed_formats = [ ] for task_cls in self . tasks : needed_formats . append ( task_cls . data_format ) self . needed_formats = list ( set ( needed_formats ) ) for output_format in self . needed_formats : reformatted_input . update ( { output_format : { 'data' : self . reformat_file ( sel...
def doit ( self , classes = None , recursive = True , ** kwargs ) : """Write out commutator Write out the commutator according to its definition $ [ \ Op { A } , \ Op { B } ] = \ Op { A } \ Op { B } - \ Op { A } \ Op { B } $ . See : meth : ` . Expression . doit ` ."""
return super ( ) . doit ( classes , recursive , ** kwargs )
def _make_local_question_images ( self , question_dict ) : """Process all mardown image links in question _ dict : - download them to local files under exerciseimages /"""
question_dict = question_dict . copy ( ) dest_path = 'exerciseimages/' if not os . path . exists ( dest_path ) : os . mkdir ( dest_path ) # helper method def _process_string ( string ) : image_regex = re . compile ( MARKDOWN_IMAGE_REGEX , flags = re . IGNORECASE ) contentstorage_prefix = '${☣ CONTENTSTORAGE...
def sim_model ( self , tmax , X0 , noiseDyn = 0 , restart = 0 ) : """Simulate the model ."""
self . noiseDyn = noiseDyn X = np . zeros ( ( tmax , self . dim ) ) X [ 0 ] = X0 + noiseDyn * np . random . randn ( self . dim ) # run simulation for t in range ( 1 , tmax ) : if self . modelType == 'hill' : Xdiff = self . Xdiff_hill ( X [ t - 1 ] ) elif self . modelType == 'var' : Xdiff = self ...
def load_empty ( cls , path : PathOrStr , fn : PathOrStr ) : "Load the state in ` fn ` to create an empty ` LabelList ` for inference ."
return cls . load_state ( path , pickle . load ( open ( Path ( path ) / fn , 'rb' ) ) )
def externalize ( taskclass_or_taskobject ) : """Returns an externalized version of a Task . You may both pass an instantiated task object or a task class . Some examples : . . code - block : : python class RequiringTask ( luigi . Task ) : def requires ( self ) : task _ object = self . clone ( MyTask ) ...
# Seems like with python < 3.3 copy . copy can ' t copy classes # and objects with specified metaclass http : / / bugs . python . org / issue11480 compatible_copy = copy . copy if six . PY3 else copy . deepcopy copied_value = compatible_copy ( taskclass_or_taskobject ) if copied_value is taskclass_or_taskobject : # Ass...
def register_listener ( self , listener , reading = False ) : """Add a callback function that is called when sensor value is updated . The callback footprint is received _ timestamp , timestamp , status , value . Parameters listener : function Callback signature : if reading listener ( katcp _ sensor , re...
listener_id = hashable_identity ( listener ) self . _listeners [ listener_id ] = ( listener , reading ) logger . debug ( 'Register listener for {}' . format ( self . name ) )
def info ( cwd , targets = None , user = None , username = None , password = None , fmt = 'str' ) : '''Display the Subversion information from the checkout . cwd The path to the Subversion repository targets : None files , directories , and URLs to pass to the command as arguments svn uses ' . ' by defaul...
opts = list ( ) if fmt == 'xml' : opts . append ( '--xml' ) if targets : opts += salt . utils . args . shlex_split ( targets ) infos = _run_svn ( 'info' , cwd , user , username , password , opts ) if fmt in ( 'str' , 'xml' ) : return infos info_list = [ ] for infosplit in infos . split ( '\n\n' ) : info...
def process_command_thread ( self , request ) : """Worker thread to process a command ."""
command , data = request if multi_thread_enabled ( ) : try : self . process_command ( command , data ) except Exception as e : _logger . exception ( str ( e ) ) raise else : pass
def cartesian_to_spherical_azimuthal ( x , y ) : """Calculates the azimuthal angle in spherical coordinates from Cartesian coordinates . The azimuthal angle is in [ 0,2 * pi ] . Parameters x : { numpy . array , float } X - coordinate . y : { numpy . array , float } Y - coordinate . Returns phi : { n...
y = float ( y ) if isinstance ( y , int ) else y phi = numpy . arctan2 ( y , x ) return phi % ( 2 * numpy . pi )
def _example_rt_data ( quote_ctx ) : """获取分时数据 , 输出 时间 , 数据状态 , 开盘多少分钟 , 目前价 , 昨收价 , 平均价 , 成交量 , 成交额"""
stock_code_list = [ "US.AAPL" , "HK.00700" ] ret_status , ret_data = quote_ctx . subscribe ( stock_code_list , ft . SubType . RT_DATA ) if ret_status != ft . RET_OK : print ( ret_data ) exit ( ) for stk_code in stock_code_list : ret_status , ret_data = quote_ctx . get_rt_data ( stk_code ) if ret_status ...
def Get ( self ) : """Fetch hunt ' s data and return proper Hunt object ."""
args = hunt_pb2 . ApiGetHuntArgs ( hunt_id = self . hunt_id ) data = self . _context . SendRequest ( "GetHunt" , args ) return Hunt ( data = data , context = self . _context )
def setup ( self , host , flow_id , reason , grr_server_url , grr_username , grr_password , approvers = None , verify = True ) : """Initializes a GRR flow collector . Args : host : hostname of machine . flow _ id : ID of GRR flow to retrieve . reason : justification for GRR access . grr _ server _ url : G...
super ( GRRFlowCollector , self ) . setup ( reason , grr_server_url , grr_username , grr_password , approvers = approvers , verify = verify ) self . flow_id = flow_id self . host = host
def sedfile ( fpath , regexpr , repl , force = False , verbose = True , veryverbose = False ) : """Executes sed on a specific file Args : fpath ( str ) : file path string regexpr ( str ) : repl ( str ) : force ( bool ) : ( default = False ) verbose ( bool ) : verbosity flag ( default = True ) veryverb...
# TODO : move to util _ edit path , name = split ( fpath ) new_file_lines = [ ] if veryverbose : print ( '[sedfile] fpath=%r' % fpath ) print ( '[sedfile] regexpr=%r' % regexpr ) print ( '[sedfile] repl=%r' % repl ) print ( '[sedfile] force=%r' % force ) import utool as ut file_lines = ut . readfrom ( f...
def size ( a , b = 0 , nargout = 1 ) : """> > > size ( zeros ( 3,3 ) ) + 1 matlabarray ( [ [ 4 , 4 ] ] )"""
s = np . asarray ( a ) . shape if s is ( ) : return 1 if b else ( 1 , ) * nargout # a is not a scalar try : if b : return s [ b - 1 ] else : return matlabarray ( s ) if nargout <= 1 else s except IndexError : return 1
def save_file ( path , data , readable = False ) : """Save to file : param path : File path to save : type path : str | unicode : param data : Data to save : type data : None | int | float | str | unicode | list | dict : param readable : Format file to be human readable ( default : False ) : type readab...
if not path : IOError ( "No path specified to save" ) try : with io . open ( path , "w" , encoding = "utf-8" ) as f : if path . endswith ( ".json" ) : save_json_file ( f , data , pretty = readable , compact = ( not readable ) , sort = True ) elif path . endswith ( ".yaml" ) or path ....
def setKeyboardTransformAbsolute ( self , eTrackingOrigin ) : """Set the position of the keyboard in world space"""
fn = self . function_table . setKeyboardTransformAbsolute pmatTrackingOriginToKeyboardTransform = HmdMatrix34_t ( ) fn ( eTrackingOrigin , byref ( pmatTrackingOriginToKeyboardTransform ) ) return pmatTrackingOriginToKeyboardTransform
def compile_model ( self , input_model_config , output_model_config , role , job_name , stop_condition , tags ) : """Create an Amazon SageMaker Neo compilation job . Args : input _ model _ config ( dict ) : the trained model and the Amazon S3 location where it is stored . output _ model _ config ( dict ) : Id...
compilation_job_request = { 'InputConfig' : input_model_config , 'OutputConfig' : output_model_config , 'RoleArn' : role , 'StoppingCondition' : stop_condition , 'CompilationJobName' : job_name } if tags is not None : compilation_job_request [ 'Tags' ] = tags LOGGER . info ( 'Creating compilation-job with name: {}'...
def _list_collections ( self , sock_info , slave_okay , session , read_preference , ** kwargs ) : """Internal listCollections helper ."""
coll = self . get_collection ( "$cmd" , read_preference = read_preference ) if sock_info . max_wire_version > 2 : cmd = SON ( [ ( "listCollections" , 1 ) , ( "cursor" , { } ) ] ) cmd . update ( kwargs ) with self . __client . _tmp_session ( session , close = False ) as tmp_session : cursor = self . ...
def add_fig_kwargs ( func ) : """Decorator that adds keyword arguments for functions returning matplotlib figures . The function should return either a matplotlib figure or None to signal some sort of error / unexpected event . See doc string below for the list of supported options ."""
from functools import wraps @ wraps ( func ) def wrapper ( * args , ** kwargs ) : # pop the kwds used by the decorator . title = kwargs . pop ( "title" , None ) size_kwargs = kwargs . pop ( "size_kwargs" , None ) show = kwargs . pop ( "show" , True ) savefig = kwargs . pop ( "savefig" , None ) tight...
def validate_request ( self , data : Any , * additional : AnyMapping , merged_class : Type [ dict ] = dict ) -> Any : r"""Validate request data against request schema from module . : param data : Request data . : param \ * additional : Additional data dicts to be merged with base request data . : param merg...
request_schema = getattr ( self . module , 'request' , None ) if request_schema is None : logger . error ( 'Request schema should be defined' , extra = { 'schema_module' : self . module , 'schema_module_attrs' : dir ( self . module ) } ) raise self . make_error ( 'Request schema should be defined' ) # Merge bas...
def askForFolder ( parent , msg = None ) : '''Asks for a folder , opening the corresponding dialog with the last path that was selected when this same function was invoked from the calling method : param parent : The parent window : param msg : The message to use for the dialog title'''
msg = msg or 'Select folder' caller = _callerName ( ) . split ( "." ) name = "/" . join ( [ LAST_PATH , caller [ - 1 ] ] ) namespace = caller [ 0 ] path = pluginSetting ( name , namespace ) folder = QtWidgets . QFileDialog . getExistingDirectory ( parent , msg , path ) if folder : setPluginSetting ( name , folder ,...
def top_k_accuracy ( input : Tensor , targs : Tensor , k : int = 5 ) -> Rank0Tensor : "Computes the Top - k accuracy ( target is in the top k predictions ) ."
input = input . topk ( k = k , dim = - 1 ) [ 1 ] targs = targs . unsqueeze ( dim = - 1 ) . expand_as ( input ) return ( input == targs ) . max ( dim = - 1 ) [ 0 ] . float ( ) . mean ( )
def read_from_bpch ( filename , file_position , shape , dtype , endian , use_mmap = False ) : """Read a chunk of data from a bpch output file . Parameters filename : str Path to file on disk containing the data file _ position : int Position ( bytes ) where desired data chunk begins shape : tuple of int...
offset = file_position + 4 if use_mmap : d = np . memmap ( filename , dtype = dtype , mode = 'r' , shape = shape , offset = offset , order = 'F' ) else : with FortranFile ( filename , 'rb' , endian ) as ff : ff . seek ( file_position ) d = np . array ( ff . readline ( '*f' ) ) d = d . re...
def column ( table_name , column_name = None , cache = False , cache_scope = _CS_FOREVER ) : """Decorates functions that return a Series . Decorator version of ` add _ column ` . Series index must match the named table . Column name defaults to name of function . The function ' s argument names and keyword ar...
def decorator ( func ) : if column_name : name = column_name else : name = func . __name__ add_column ( table_name , name , func , cache = cache , cache_scope = cache_scope ) return func return decorator
def bsp_find_node ( node : tcod . bsp . BSP , cx : int , cy : int ) -> Optional [ tcod . bsp . BSP ] : """. . deprecated : : 2.0 Use : any : ` BSP . find _ node ` instead ."""
return node . find_node ( cx , cy )
def setup_config ( epab_version : str ) : """Set up elib _ config package : param epab _ version : installed version of EPAB as as string"""
logger = logging . getLogger ( 'EPAB' ) logger . debug ( 'setting up config' ) elib_config . ELIBConfig . setup ( app_name = 'EPAB' , app_version = epab_version , config_file_path = 'pyproject.toml' , config_sep_str = '__' , root_path = [ 'tool' , 'epab' ] ) elib_config . write_example_config ( 'pyproject.toml.example'...
def sampleLOS ( self , los , n = 1 , deg = True , maxd = None , nsigma = None , targetSurfmass = True , targetSigma2 = True ) : """NAME : sampleLOS PURPOSE : sample along a given LOS INPUT : los - line of sight ( in deg , unless deg = False ; can be Quantity ) n = number of desired samples deg = los i...
if _APY_LOADED and isinstance ( los , units . Quantity ) : l = los . to ( units . rad ) . value elif deg : l = los * _DEGTORAD else : l = los out = [ ] # sample distances ds = self . sampledSurfacemassLOS ( l , n = n , maxd = maxd , target = targetSurfmass , use_physical = False ) for ii in range ( int ( n ...
def _get_translations_multi_paths ( ) : """Return the correct gettext translations that should be used for this request . This will never fail and return a dummy translation object if used outside of the request or if a translation cannot be found ."""
ctx = _request_ctx_stack . top if ctx is None : return None translations = getattr ( ctx , "babel_translations" , None ) if translations is None : babel_ext = ctx . app . extensions [ "babel" ] translations = None trs = None # reverse order : thus the application catalog is loaded last , so that ...
def _get_login_manager ( self , app : FlaskUnchained , anonymous_user : AnonymousUser , ) -> LoginManager : """Get an initialized instance of Flask Login ' s : class : ` ~ flask _ login . LoginManager ` ."""
login_manager = LoginManager ( ) login_manager . anonymous_user = anonymous_user or AnonymousUser login_manager . localize_callback = _ login_manager . request_loader ( self . _request_loader ) login_manager . user_loader ( lambda * a , ** kw : self . security_utils_service . user_loader ( * a , ** kw ) ) login_manager...
def _xml_for_episode_index ( self , ep_ind ) : """Helper method to retrieve the corresponding model xml string for the passed episode index ."""
# read the model xml , using the metadata stored in the attribute for this episode model_file = self . demo_file [ "data/{}" . format ( ep_ind ) ] . attrs [ "model_file" ] model_path = os . path . join ( self . demo_path , "models" , model_file ) with open ( model_path , "r" ) as model_f : model_xml = model_f . rea...
def write_gff_file ( self , outfile , force_rerun = False ) : """Write a GFF file for the protein features , ` ` features ` ` will now load directly from this file . Args : outfile ( str ) : Path to new FASTA file to be written to force _ rerun ( bool ) : If an existing file should be overwritten"""
if ssbio . utils . force_rerun ( outfile = outfile , flag = force_rerun ) : with open ( outfile , "w" ) as out_handle : GFF . write ( [ self ] , out_handle ) self . feature_path = outfile
def node_theta ( nodelist , node ) : """Maps node to Angle . : param nodelist : Nodelist from the graph . : type nodelist : list . : param node : The node of interest . Must be in the nodelist . : returns : theta - - the angle of the node in radians ."""
assert len ( nodelist ) > 0 , "nodelist must be a list of items." assert node in nodelist , "node must be inside nodelist." i = nodelist . index ( node ) theta = - np . pi + i * 2 * np . pi / len ( nodelist ) return theta
def handle_request ( request , validator_map , ** kwargs ) : """Validate the request against the swagger spec and return a dict with all parameter values available in the request , casted to the expected python type . : param request : a : class : ` PyramidSwaggerRequest ` to validate : param validator _ ma...
request_data = { } validation_pairs = [ ] for validator , values in [ ( validator_map . query , request . query ) , ( validator_map . path , request . path ) , ( validator_map . form , request . form ) , ( validator_map . headers , request . headers ) , ] : values = cast_params ( validator . schema , values ) v...
def p_nonblocking_substitution ( self , p ) : 'nonblocking _ substitution : delays lvalue LE delays rvalue SEMICOLON'
p [ 0 ] = NonblockingSubstitution ( p [ 2 ] , p [ 5 ] , p [ 1 ] , p [ 4 ] , lineno = p . lineno ( 2 ) ) p . set_lineno ( 0 , p . lineno ( 2 ) )
def emit ( self , event , * event_args ) : """Call the registered listeners for ` ` event ` ` . The listeners will be called with any extra arguments passed to : meth : ` emit ` first , and then the extra arguments passed to : meth : ` on `"""
listeners = self . _listeners [ event ] [ : ] for listener in listeners : args = list ( event_args ) + list ( listener . user_args ) result = listener . callback ( * args ) if result is False : self . off ( event , listener . callback )
def add_cert ( self , cert ) : """Explicitely adds certificate to set of trusted in the store @ param cert - X509 object to add"""
if not isinstance ( cert , X509 ) : raise TypeError ( "cert should be X509" ) libcrypto . X509_STORE_add_cert ( self . store , cert . cert )
def make_params ( self ) : """Create all Variables to be returned later by get _ params . By default this is a no - op . Models that need their fprop to be called for their params to be created can set ` needs _ dummy _ fprop = True ` in the constructor ."""
if self . needs_dummy_fprop : if hasattr ( self , "_dummy_input" ) : return self . _dummy_input = self . make_input_placeholder ( ) self . fprop ( self . _dummy_input )
def add_result ( self , source , found , runtime ) : """Adds a new record to the statistics ' database ' . This function is intended to be called after a website has been scraped . The arguments indicate the function that was called , the time taken to scrap the website and a boolean indicating if the lyrics ...
self . source_stats [ source . __name__ ] . add_runtime ( runtime ) if found : self . source_stats [ source . __name__ ] . successes += 1 else : self . source_stats [ source . __name__ ] . fails += 1
def print_download_uri ( self , version , source ) : """@ param version : version number or ' dev ' for svn @ type version : string @ param source : download source or egg @ type source : boolean @ returns : None"""
if version == "dev" : pkg_type = "subversion" source = True elif source : pkg_type = "source" else : pkg_type = "egg" # Use setuptools monkey - patch to grab url url = get_download_uri ( self . project_name , version , source , self . options . pypi_index ) if url : print ( "%s" % url ) else : s...
def _load_instance ( self , instance_id , force_reload = True ) : """Return instance with the given id . For performance reasons , the instance ID is first searched for in the collection of VM instances started by ElastiCluster ( ` self . _ instances ` ) , then in the list of all instances known to the clou...
if force_reload : try : # Remove from cache and get from server again vm = self . nova_client . servers . get ( instance_id ) except NotFound : raise InstanceNotFoundError ( "Instance `{instance_id}` not found" . format ( instance_id = instance_id ) ) # update caches self . _instances [ ...
def get_render_data ( self , ** kwargs ) : """Returns all data that should be passed to the renderer . By default adds the following arguments : * * * bundle * * - The bundle that is attached to this view instance . * * * url _ params * * - The url keyword arguments . i . e . : self . kwargs . * * * user * ...
obj = getattr ( self , 'object' , None ) data = dict ( self . extra_render_data ) data . update ( kwargs ) data . update ( { 'bundle' : self . bundle , 'navigation' : self . get_navigation ( ) , 'url_params' : self . kwargs , 'user' : self . request . user , 'object_header_tmpl' : self . object_header_tmpl , 'view_tags...
def get_component_related_issues ( self , component_id ) : """Returns counts of issues related to this component . : param component _ id : : return :"""
url = 'rest/api/2/component/{component_id}/relatedIssueCounts' . format ( component_id = component_id ) return self . get ( url )
def get_chemical ( self , chemical_name = None , chemical_id = None , cas_rn = None , drugbank_id = None , parent_id = None , parent_tree_number = None , tree_number = None , synonym = None , limit = None , as_df = False ) : """Get chemical : param bool as _ df : if set to True result returns as ` pandas . DataFr...
q = self . session . query ( models . Chemical ) if chemical_name : q = q . filter ( models . Chemical . chemical_name . like ( chemical_name ) ) if chemical_id : q = q . filter ( models . Chemical . chemical_id == chemical_id ) if cas_rn : q = q . filter ( models . Chemical . cas_rn == cas_rn ) if drugbank...
def set_iscsi_boot_info ( self , mac , target_name , lun , ip_address , port = '3260' , auth_method = None , username = None , password = None ) : """Set iscsi details of the system in uefi boot mode . The initiator system is set with the target details like IQN , LUN , IP , Port etc . : param mac : The MAC o...
LOG . warning ( "'set_iscsi_boot_info' is deprecated. The 'MAC' parameter" "passed in is ignored. Use 'set_iscsi_info' instead." ) return self . _call_method ( 'set_iscsi_info' , target_name , lun , ip_address , port , auth_method , username , password )
def add_node_configuration ( self , param_name , node_id , param_value ) : """Set a parameter for a given node : param param _ name : parameter identifier ( as specified by the chosen model ) : param node _ id : node identifier : param param _ value : parameter value"""
if param_name not in self . config [ 'nodes' ] : self . config [ 'nodes' ] [ param_name ] = { node_id : param_value } else : self . config [ 'nodes' ] [ param_name ] [ node_id ] = param_value
def forget_masks ( self ) : """Forget all loaded coordinates ."""
self . _seqno = 1 self . _maskobjs = [ ] self . _treepaths = [ ] self . tree_dict = Bunch . caselessDict ( ) self . redo ( )
def serve ( self , conn , addr , auth = False ) : """Handle a single client . : param conn : The Connection instance . : param addr : The address of the client , for logging purposes . : param auth : A boolean specifying whether the connection should be considered authenticated or not . Provided for debug...
try : # Handle data from the client while True : # Get the command try : cmd , payload = conn . recv ( ) except ValueError as exc : # Tell the client about the error conn . send ( 'ERR' , "Failed to parse command: %s" % str ( exc ) ) # If they haven ' t successful...
def get_setter ( self , oid ) : """Retrieve the nearest parent setter function for an OID"""
if hasattr ( self . setter , oid ) : return self . setter [ oid ] parents = [ poid for poid in list ( self . setter . keys ( ) ) if oid . startswith ( poid ) ] if parents : return self . setter [ max ( parents ) ] return self . default_setter
def _create_pipe ( self ) : """Creates a new pipe and returns the child end of the connection . To request an account from the pipe , use : : pipe = queue . _ create _ pipe ( ) # Let the account manager choose an account . pipe . send ( ( ' acquire - account - for - host ' , host ) ) account = pipe . recv...
child = _PipeHandler ( self . account_manager ) self . pipe_handlers [ id ( child ) ] = child child . start ( ) return child . to_parent
def gt ( self , value ) : """Construct a greater than ( ` ` > ` ` ) filter . : param value : Filter value : return : : class : ` filters . Field < filters . Field > ` object : rtype : filters . Field"""
self . op = '>' self . negate_op = '<=' self . value = self . _value ( value ) return self
def default_signal_map ( ) : """Create the default signal map for this system . : return : dict"""
name_map = { 'SIGTSTP' : None , 'SIGTTIN' : None , 'SIGTTOU' : None , 'SIGTERM' : 'terminate' } signal_map = { } for name , target in list ( name_map . items ( ) ) : if hasattr ( signal , name ) : signal_map [ getattr ( signal , name ) ] = target return signal_map
def makedirs ( name , mode = 0o777 , exist_ok = False ) : """Mimicks os . makedirs ( ) from Python 3."""
try : os . makedirs ( name , mode ) except OSError : if not os . path . isdir ( name ) or not exist_ok : raise
def get_session ( self , redirect_url ) : """Create Session to store credentials . Parameters redirect _ url ( str ) The full URL that the Uber server redirected to after the user authorized your app . Returns ( Session ) A Session object with OAuth 2.0 credentials . Raises UberIllegalState ( APIE...
query_params = self . _extract_query ( redirect_url ) error = query_params . get ( 'error' ) if error : raise UberIllegalState ( error ) # convert space delimited string to set scopes = query_params . get ( 'scope' ) scopes_set = { scope for scope in scopes . split ( ) } oauth2credential = OAuth2Credential ( client...
def safe_mkdir ( directory , clean = False ) : """Safely create a directory . Ensures a directory is present . If it ' s not there , it is created . If it is , it ' s a no - op . If clean is True , ensures the directory is empty ."""
if clean : safe_rmtree ( directory ) try : os . makedirs ( directory ) except OSError as e : if e . errno != errno . EEXIST : raise
def run ( self ) : '''Enter into the server loop'''
salt . utils . process . appendproctitle ( self . __class__ . __name__ ) # instantiate some classes inside our new process self . event = salt . utils . event . get_event ( self . opts [ '__role' ] , self . opts [ 'sock_dir' ] , self . opts [ 'transport' ] , opts = self . opts , listen = True ) self . wrap = ReactWrap ...
def _process_credentials ( self , req , resp , origin ) : """Adds the Access - Control - Allow - Credentials to the response if the cors settings indicates it should be set ."""
if self . _cors_config [ 'allow_credentials_all_origins' ] : self . _set_allow_credentials ( resp ) return True if origin in self . _cors_config [ 'allow_credentials_origins_list' ] : self . _set_allow_credentials ( resp ) return True credentials_regex = self . _cors_config [ 'allow_credentials_origins_...
def directions ( self , origin , destination , mode = None , alternatives = None , waypoints = None , optimize_waypoints = False , avoid = None , language = None , units = None , region = None , departure_time = None , arrival_time = None , sensor = None ) : """Get directions between locations : param origin : Or...
# noqa if optimize_waypoints : waypoints . insert ( 0 , "optimize:true" ) parameters = dict ( origin = self . assume_latlon_or_address ( origin ) , destination = self . assume_latlon_or_address ( destination ) , mode = mode , alternatives = alternatives , waypoints = waypoints or [ ] , avoid = avoid , language = la...
def is_uniform_join_units ( join_units ) : """Check if the join units consist of blocks of uniform type that can be concatenated using Block . concat _ same _ type instead of the generic concatenate _ join _ units ( which uses ` _ concat . _ concat _ compat ` ) ."""
return ( # all blocks need to have the same type all ( type ( ju . block ) is type ( join_units [ 0 ] . block ) for ju in join_units ) and # noqa # no blocks that would get missing values ( can lead to type upcasts ) # unless we ' re an extension dtype . all ( not ju . is_na or ju . block . is_extension for ju in join_...
def restore_backup ( path , backup_id ) : '''. . versionadded : : 0.17.0 Restore a previous version of a file that was backed up using Salt ' s : ref : ` file state backup < file - state - backups > ` system . path The path on the minion to check for backups backup _ id The numeric id for the backup you...
path = os . path . expanduser ( path ) # Note : This only supports minion backups , so this function will need to be # modified if / when master backups are implemented . ret = { 'result' : False , 'comment' : 'Invalid backup_id \'{0}\'' . format ( backup_id ) } try : if len ( six . text_type ( backup_id ) ) == len...
def vbreak ( image , mask = None , iterations = 1 ) : '''Remove horizontal breaks 1 1 1 1 1 1 0 1 0 - > 0 0 0 ( this case only ) 1 1 1 1 1 1'''
global vbreak_table if mask is None : masked_image = image else : masked_image = image . astype ( bool ) . copy ( ) masked_image [ ~ mask ] = False result = table_lookup ( masked_image , vbreak_table , False ) if not mask is None : result [ ~ mask ] = image [ ~ mask ] return result
def add_optional_parameters ( detail_json , detail , rating , rating_n , popularity , current_popularity , time_spent ) : """check for optional return parameters and add them to the result json : param detail _ json : : param detail : : param rating : : param rating _ n : : param popularity : : param cu...
if rating is not None : detail_json [ "rating" ] = rating elif "rating" in detail : detail_json [ "rating" ] = detail [ "rating" ] if rating_n is not None : detail_json [ "rating_n" ] = rating_n if "international_phone_number" in detail : detail_json [ "international_phone_number" ] = detail [ "internat...
def get_xmlrpc_server ( self ) : """Returns PyPI ' s XML - RPC server instance"""
check_proxy_setting ( ) if os . environ . has_key ( 'XMLRPC_DEBUG' ) : debug = 1 else : debug = 0 try : return xmlrpclib . Server ( XML_RPC_SERVER , transport = ProxyTransport ( ) , verbose = debug ) except IOError : self . logger ( "ERROR: Can't connect to XML-RPC server: %s" % XML_RPC_SERVER )
def reset_kernel ( self ) : """Reset kernel of current client ."""
client = self . get_current_client ( ) if client is not None : self . switch_to_plugin ( ) client . reset_namespace ( )
def set_location ( self , place , latitude , longitude , pipe = None ) : """Set the location of * place * to the location specified by * latitude * and * longitude * . * place * can be any pickle - able Python object ."""
pipe = self . redis if pipe is None else pipe pipe . geoadd ( self . key , longitude , latitude , self . _pickle ( place ) )
def save ( self , filename , format = None ) : """Saves the SArray to file . The saved SArray will be in a directory named with the ` targetfile ` parameter . Parameters filename : string A local path or a remote URL . If format is ' text ' , it will be saved as a text file . If format is ' binary ' , a...
from . sframe import SFrame as _SFrame if format is None : if filename . endswith ( ( '.csv' , '.csv.gz' , 'txt' ) ) : format = 'text' else : format = 'binary' if format == 'binary' : with cython_context ( ) : self . __proxy__ . save ( _make_internal_url ( filename ) ) elif format ==...
def append_columns ( self , colnames , values , ** kwargs ) : """Append new columns to the table . When appending a single column , ` ` values ` ` can be a scalar or an array of either length 1 or the same length as this array ( the one it ' s appended to ) . In case of multiple columns , values must have t...
n = len ( self ) if np . isscalar ( values ) : values = np . full ( n , values ) values = np . atleast_1d ( values ) if not isinstance ( colnames , str ) and len ( colnames ) > 1 : values = np . atleast_2d ( values ) self . _check_column_length ( values , n ) if values . ndim == 1 : if len ( values ) > ...
def delete_template ( server , token , template ) : """Delete template . Argument : server : TonicDNS API server token : TonicDNS API authentication token template : Delete template datas x - authentication - token : token"""
method = 'DELETE' uri = 'https://' + server + '/template/' + template connect . tonicdns_client ( uri , method , token , data = False )
def get ( self , request = None , timeout = 1.0 ) : """Get an NDEF message from the server . Temporarily connects to the default SNEP server if the client is not yet connected . . . deprecated : : 0.13 Use : meth : ` get _ records ` or : meth : ` get _ octets ` ."""
if request is None : request = nfc . ndef . Message ( nfc . ndef . Record ( ) ) if not isinstance ( request , nfc . ndef . Message ) : raise TypeError ( "request type must be nfc.ndef.Message" ) response_data = self . _get ( request , timeout ) if response_data is not None : try : response = nfc . n...
def _qemu_image_create ( disk , create_overlay = False , saltenv = 'base' ) : '''Create the image file using specified disk _ size or / and disk _ image Return path to the created image file'''
disk_size = disk . get ( 'size' , None ) disk_image = disk . get ( 'image' , None ) if not disk_size and not disk_image : raise CommandExecutionError ( 'Unable to create new disk {0}, please specify' ' disk size and/or disk image argument' . format ( disk [ 'filename' ] ) ) img_dest = disk [ 'source_file' ] log . d...
def _parse_fail ( name , var_type , value , values ) : """Helper function for raising a value error for bad assignment ."""
raise ValueError ( 'Could not parse hparam \'%s\' of type \'%s\' with value \'%s\' in %s' % ( name , var_type . __name__ , value , values ) )
def has_parent_objective_banks ( self , objective_bank_id ) : """Tests if the ` ` ObjectiveBank ` ` has any parents . arg : objective _ bank _ id ( osid . id . Id ) : the ` ` Id ` ` of an objective bank return : ( boolean ) - ` ` true ` ` if the objective bank has parents , ` ` false ` ` otherwise raise :...
# Implemented from template for # osid . resource . BinHierarchySession . has _ parent _ bins if self . _catalog_session is not None : return self . _catalog_session . has_parent_catalogs ( catalog_id = objective_bank_id ) return self . _hierarchy_session . has_parents ( id_ = objective_bank_id )
def zone_schedules_backup ( self , filename ) : """Backup all zones on control system to the given file ."""
_LOGGER . info ( "Backing up schedules from ControlSystem: %s (%s)..." , self . systemId , self . location . name ) schedules = { } if self . hotwater : _LOGGER . info ( "Retrieving DHW schedule: %s..." , self . hotwater . zoneId ) schedule = self . hotwater . schedule ( ) schedules [ self . hotwater . zone...
def process_params ( self , params ) : '''Populates the launch data from a dictionary . Only cares about keys in the LAUNCH _ DATA _ PARAMETERS list , or that start with ' custom _ ' or ' ext _ ' .'''
for key , val in params . items ( ) : if key in LAUNCH_DATA_PARAMETERS and val != 'None' : if key == 'roles' : if isinstance ( val , list ) : # If it ' s already a list , no need to parse self . roles = list ( val ) else : # If it ' s a ' , ' delimited string , split ...
def remove_handler ( ) : """Remove the user , group and policies for Blockade ."""
logger . debug ( "[#] Removing user, group and permissions for Blockade" ) client = boto3 . client ( "iam" , region_name = PRIMARY_REGION ) iam = boto3 . resource ( 'iam' ) account_id = iam . CurrentUser ( ) . arn . split ( ':' ) [ 4 ] try : logger . debug ( "[#] Removing %s from %s group" % ( BLOCKADE_USER , BLOCK...
def hexblock_byte ( cls , data , address = None , bits = None , separator = ' ' , width = 16 ) : """Dump a block of hexadecimal BYTEs from binary data . @ type data : str @ param data : Binary data . @ type address : str @ param address : Memory address where the data was read from . @ type bits : int @...
return cls . hexblock_cb ( cls . hexadecimal , data , address , bits , width , cb_kwargs = { 'separator' : separator } )
def setup ( app ) : "Setup function for Sphinx Extension"
app . add_config_value ( "sphinx_to_github" , True , '' ) app . add_config_value ( "sphinx_to_github_verbose" , True , '' ) app . connect ( "build-finished" , sphinx_extension )
def add_permission ( self , resource , operation ) : '''Add a new : class : ` Permission ` for ` ` resource ` ` to perform an ` ` operation ` ` . The resource can be either an object or a model .'''
if isclass ( resource ) : model_type = resource pk = '' else : model_type = resource . __class__ pk = resource . pkvalue ( ) p = Permission ( model_type = model_type , object_pk = pk , operation = operation ) session = self . session if session . transaction : session . add ( p ) self . permissi...
def calculate_x_ticks ( self , plot_width ) : """Calculate the x - axis items dependent on the plot width ."""
x_calibration = self . x_calibration uncalibrated_data_left = self . __uncalibrated_left_channel uncalibrated_data_right = self . __uncalibrated_right_channel calibrated_data_left = x_calibration . convert_to_calibrated_value ( uncalibrated_data_left ) if x_calibration is not None else uncalibrated_data_left calibrated...
def load_rsa_private_key_file ( rsakeyfile , passphrase ) : # type : ( str , str ) - > # cryptography . hazmat . primitives . asymmetric . rsa . RSAPrivateKey """Load an RSA Private key PEM file with passphrase if specified : param str rsakeyfile : RSA private key PEM file to load : param str passphrase : optio...
keypath = os . path . expandvars ( os . path . expanduser ( rsakeyfile ) ) with open ( keypath , 'rb' ) as keyfile : return cryptography . hazmat . primitives . serialization . load_pem_private_key ( keyfile . read ( ) , passphrase . encode ( 'utf8' ) if passphrase is not None else None , backend = cryptography . h...
def configure ( self , config ) : """See base class method ."""
super ( ) . configure ( config ) self . _regex = self . _build_matcher ( config . get ( 'regex{suffix}' . format ( suffix = self . _option_suffix ) , fallback = self . _regex . pattern ) )
def update_model_in_repo_based_on_filename ( self , model ) : """Adds a model to the repo ( not initially visible ) Args : model : the model to be added . If the model has no filename , a name is invented Returns : the filename of the model added to the repo"""
if model . _tx_filename is None : for fn in self . all_models . filename_to_model : if self . all_models . filename_to_model [ fn ] == model : return fn i = 0 while self . all_models . has_model ( "anonymous{}" . format ( i ) ) : i += 1 myfilename = "anonymous{}" . format ( i...
def full_game_name ( short_name ) : """CamelCase game name with mode suffix . Args : short _ name : snake _ case name without mode e . g " crazy _ climber " Returns : full game name e . g . " CrazyClimberNoFrameskip - v4" """
camel_game_name = misc_utils . snakecase_to_camelcase ( short_name ) full_name = camel_game_name + ATARI_GAME_MODE return full_name
def transform_to_length ( nndata , length ) : """Given NNData , transforms data to the specified fingerprint length Args : nndata : ( NNData ) length : ( int ) desired length of NNData"""
if length is None : return nndata if length : for cn in range ( length ) : if cn not in nndata . cn_weights : nndata . cn_weights [ cn ] = 0 nndata . cn_nninfo [ cn ] = [ ] return nndata
def _setdefault ( obj , key , value ) : """DO NOT USE _ _ dict _ _ . setdefault ( obj , key , value ) , IT DOES NOT CHECK FOR obj [ key ] = = None"""
v = obj . get ( key ) if v == None : obj [ key ] = value return value return v
def compile_binary ( source ) : """Prepare chkrootkit binary $ tar xzvf chkrootkit . tar . gz $ cd chkrootkit - 0.52 $ make sense sudo mv chkrootkit - 0.52 / usr / local / chkrootkit sudo ln - s"""
cmd = 'make sense' slink = '/usr/local/bin/chkrootkit' target = '/usr/local/chkrootkit/chkrootkit' # Tar Extraction t = tarfile . open ( source , 'r' ) t . extractall ( TMPDIR ) if isinstance ( t . getnames ( ) , list ) : extract_dir = t . getnames ( ) [ 0 ] . split ( '/' ) [ 0 ] os . chdir ( TMPDIR + '/' + ext...
def MakeSuiteFromHist ( hist , name = None ) : """Makes a normalized suite from a Hist object . Args : hist : Hist object name : string name Returns : Suite object"""
if name is None : name = hist . name # make a copy of the dictionary d = dict ( hist . GetDict ( ) ) return MakeSuiteFromDict ( d , name )
def sections ( self ) : '''List of section titles from the table of contents on the page .'''
if not getattr ( self , '_sections' , False ) : query_params = { 'action' : 'parse' , 'prop' : 'sections' , } query_params . update ( self . __title_query_param ) request = _wiki_request ( query_params ) self . _sections = [ section [ 'line' ] for section in request [ 'parse' ] [ 'sections' ] ] return s...
def scaleField ( self , scalingFactor ) : """Adjust the field of the magnet by the value of ` ` scalingFactor ` ` . The adjustment is multiplicative , so a value of ` ` scalingFactor = 1.0 ` ` will result in no change of the field ."""
self . field_strength = self . field_strength . _replace ( val = self . field_strength . val * scalingFactor )
def contamination_detection ( self ) : """Calculate the levels of contamination in the reads"""
self . qualityobject = quality . Quality ( self ) self . qualityobject . contamination_finder ( input_path = self . sequencepath , report_path = self . reportpath )
def find_all ( self , find_string , flags ) : """Return list of all positions of event _ find _ string in MainGrid . Only the code is searched . The result is not searched here . Parameters : gridpos : 3 - tuple of Integer \t Position at which the search starts find _ string : String \t String to find i...
code_array = self . grid . code_array string_match = code_array . string_match find_keys = [ ] for key in code_array : if string_match ( code_array ( key ) , find_string , flags ) is not None : find_keys . append ( key ) return find_keys
def rhypergeometric ( n , m , N , size = None ) : """Returns hypergeometric random variates ."""
if n == 0 : return np . zeros ( size , dtype = int ) elif n == N : out = np . empty ( size , dtype = int ) out . fill ( m ) return out return np . random . hypergeometric ( n , N - n , m , size )
def pad_timestamp ( string , pad_str = PAD_6_UP ) : """> > > pad _ timestamp ( ' 20 ' ) '209912' > > > pad _ timestamp ( ' 2014 ' ) '201412' > > > pad _ timestamp ( ' 20141011 ' ) '20141011' > > > pad _ timestamp ( ' 201410110010 ' ) '201410110010'"""
str_len = len ( string ) pad_len = len ( pad_str ) if str_len < pad_len : string = string + pad_str [ str_len : ] return string
def extract_morphological_information ( mrph_object , is_feature , is_surface ) : # type : ( pyknp . Morpheme , bool , bool ) - > TokenizedResult """This method extracts morphlogical information from token object ."""
assert isinstance ( mrph_object , pyknp . Morpheme ) assert isinstance ( is_feature , bool ) assert isinstance ( is_surface , bool ) surface = mrph_object . midasi word_stem = mrph_object . genkei tuple_pos = ( mrph_object . hinsi , mrph_object . bunrui ) misc_info = { 'katuyou1' : mrph_object . katuyou1 , 'katuyou2' :...
def transform_collection ( collection_dir ) : """Given an unzipped collection generate a giant HTML file representing the entire collection ( including loading and converting individual modules )"""
collxml_file = open ( os . path . join ( collection_dir , 'collection.xml' ) ) collxml_html = transform_collxml ( collxml_file ) # For each included module , parse and convert it for node in INCLUDE_XPATH ( collxml_html ) : href = node . attrib [ 'href' ] module = href . split ( '@' ) [ 0 ] # version = None...
def interventions ( self ) : """Dictionary of interventions in / scenario / interventions / vectorPop section"""
interventions = { } if self . et is None : return interventions for intervention in self . et . findall ( "intervention" ) : interventions [ intervention . attrib [ 'name' ] ] = VectorPopIntervention ( intervention ) return interventions
def _f16_oper ( op1 , op2 = None , useBC = False , reversed = False ) : """Returns pop sequence for 32 bits operands 1st operand in HLDE , 2nd operand remains in the stack Now it does support operands inversion calling _ _ SWAP32. However , if 1st operand is integer ( immediate ) or indirect , the stack wil...
output = [ ] if op1 is not None : op1 = str ( op1 ) if op2 is not None : op2 = str ( op2 ) op = op2 if op2 is not None else op1 float1 = False # whether op1 ( 2nd operand ) is float indirect = ( op [ 0 ] == '*' ) if indirect : op = op [ 1 : ] immediate = ( op [ 0 ] == '#' ) if immediate : op = op [ 1 : ...