signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_version ( self ) : """Get the version object for the related object ."""
return Version . objects . get ( content_type = self . content_type , object_id = self . object_id , version_number = self . publish_version , )
def serialize_packet_id ( packet : dict ) -> str : """Serialize packet identifiers into one reversable string . > > > serialize _ packet _ id ( { . . . ' protocol ' : ' newkaku ' , . . . ' id ' : ' 000001 ' , . . . ' switch ' : ' 01 ' , . . . ' command ' : ' on ' , ' newkaku _ 000001_01' > > > seriali...
# translate protocol in something reversable protocol = protocol_translations [ packet [ 'protocol' ] ] if protocol == UNKNOWN : protocol = 'rflink' return '_' . join ( filter ( None , [ protocol , packet . get ( 'id' , None ) , packet . get ( 'switch' , None ) , ] ) )
def _compute_std ( self , C , stddevs , idx ) : """Compute total standard deviation , see tables 3 and 4 , pages 227 and 228."""
for stddev in stddevs : stddev [ idx ] += C [ 'sigma' ]
def create_driver_script ( driver , script_create = None ) : # noqa : E501 """Create a new script Create a new script # noqa : E501 : param driver : The driver to use for the request . ie . github : type driver : str : param script _ create : The data needed to create this script : type script _ create : ...
if connexion . request . is_json : script_create = ScriptCreate . from_dict ( connexion . request . get_json ( ) ) # noqa : E501 response = errorIfUnauthorized ( role = 'developer' ) if response : return response else : response = ApitaxResponse ( ) driver : Driver = LoadedDrivers . getDriver ( driver ) dri...
def db004 ( self , value = None ) : """Corresponds to IDD Field ` db004 ` Dry - bulb temperature corresponding to 0.4 % annual cumulative frequency of occurrence ( warm conditions ) Args : value ( float ) : value for IDD Field ` db004 ` Unit : C if ` value ` is None it will not be checked against the sp...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `db004`' . format ( value ) ) self . _db004 = value
def process_bucket_set ( account_info , buckets ) : """Process a collection of buckets . For each bucket fetch location , versioning and size and then kickoff processing strategy based on size ."""
region_clients = { } log = logging . getLogger ( 'salactus.bucket-set' ) log . info ( "processing account %s" , account_info ) session = get_session ( account_info ) client = session . client ( 's3' , config = s3config ) for b in buckets : bid = bucket_id ( account_info , b ) with bucket_ops ( bid ) : i...
def get_future ( self ) : """Get current and future forecasts ."""
now = dt . now ( ) four_days = now + timedelta ( hours = 96 ) now = now . timestamp ( ) four_days = four_days . timestamp ( ) url = build_url ( self . api_key , self . spot_id , self . fields , self . unit , now , four_days ) return get_msw ( url )
def delete ( self ) : '''Deletes this model from the database , calling delete in each field to properly delete special cases'''
redis = type ( self ) . get_redis ( ) for fieldname , field in self . proxy : field . delete ( redis ) redis . delete ( self . key ( ) ) redis . srem ( type ( self ) . members_key ( ) , self . id ) if isinstance ( self , PermissionHolder ) : redis . delete ( self . allow_key ( ) ) if self . notify : data = ...
def suggest_localhost ( func ) : '''Decorator : prompt user for value of env . host _ string with default to ' localhost ' when env . host _ string is empty . Modification of decorator function fabric . network . needs _ host'''
from fabric . network import handle_prompt_abort , to_dict @ wraps ( func ) def host_prompting_wrapper ( * args , ** kwargs ) : while not env . get ( 'host_string' , False ) : handle_prompt_abort ( "the target host connection string" ) host_string = raw_input ( "No hosts found. Please specify " "hos...
def __dispatch_request ( self , handler_input ) : # type : ( Input ) - > Union [ Output , None ] """Process the request and return handler output . When the method is invoked , using the registered list of : py : class : ` RequestMapper ` , a Handler Chain is found that can handle the request . The handler in...
request_handler_chain = None for mapper in self . request_mappers : request_handler_chain = mapper . get_request_handler_chain ( handler_input ) if request_handler_chain is not None : break if request_handler_chain is None : raise DispatchException ( "Unable to find a suitable request handler" ) req...
def trace ( self , data , callback = None ) : """Trace data asynchronously . If no one is listening for traced data , it will be dropped otherwise it will be queued for sending . Args : data ( bytearray , string ) : Unstructured data to trace to any connected client . callback ( callable ) : Optional ca...
if self . _push_channel is None : return self . _push_channel . trace ( data , callback = callback )
def paths_to_top ( self , term ) : """Returns all possible paths to the root node Each path includes the term given . The order of the path is top - > bottom , i . e . it starts with the root and ends with the given term ( inclusively ) . Parameters : - term : the id of the GO term , where the paths beg...
# error handling consistent with original authors if term not in self : print ( "Term %s not found!" % term , file = sys . stderr ) return def _paths_to_top_recursive ( rec ) : if rec . level == 0 : return [ [ rec ] ] paths = [ ] for parent in rec . parents : top_paths = _paths_to_to...
def check_files ( self , to_path = None ) : """Check that all of the files contained in the archive are within the target directory ."""
if to_path : target_path = os . path . normpath ( os . path . realpath ( to_path ) ) else : target_path = os . getcwd ( ) for filename in self . filenames ( ) : extract_path = os . path . join ( target_path , filename ) extract_path = os . path . normpath ( os . path . realpath ( extract_path ) ) if...
def logsumexp ( a , axis = None , b = None , use_numexpr = True ) : """Compute the log of the sum of exponentials of input elements . Parameters a : array _ like Input array . axis : None or int , optional , default = None Axis or axes over which the sum is taken . By default ` axis ` is None , and all ...
a = np . asarray ( a ) a_max = np . amax ( a , axis = axis , keepdims = True ) if a_max . ndim > 0 : a_max [ ~ np . isfinite ( a_max ) ] = 0 elif not np . isfinite ( a_max ) : a_max = 0 if b is not None : b = np . asarray ( b ) if use_numexpr and HAVE_NUMEXPR : out = np . log ( numexpr . evaluat...
def get_connection ( connection_id , deep = False ) : """Get Heroku Connection connection information . For more details check the link - https : / / devcenter . heroku . com / articles / heroku - connect - api # step - 8 - monitor - the - connection - and - mapping - status Sample response from API call is b...
url = os . path . join ( settings . HEROKU_CONNECT_API_ENDPOINT , 'connections' , connection_id ) payload = { 'deep' : deep } response = requests . get ( url , params = payload , headers = _get_authorization_headers ( ) ) response . raise_for_status ( ) return response . json ( )
def set_property ( self , name , value ) : """Helper to set a property value by name , translating to correct dbus type See also : py : meth : ` get _ property ` : param str name : The property name in the object ' s dictionary whose value shall be set . : param value : Properties new value to be assigned...
typeof = type ( self . get_property ( name ) ) self . _interface . SetProperty ( name , translate_to_dbus_type ( typeof , value ) )
def polyFitIgnoringOutliers ( x , y , deg = 2 , niter = 3 , nstd = 2 , return_outliers = False ) : """Returns : ( np . poly1d ) : callable function of polynomial fit excluding all outliers Args : deg ( int ) : degree of polynomial fit n _ iter ( int ) : do linear regression n times successive removing n...
if return_outliers : a = all_outliers = np . zeros_like ( y , dtype = bool ) for i in range ( niter ) : poly = np . polyfit ( x , y , deg ) p = np . poly1d ( poly ) if i == niter - 1 : break y_fit = p ( x ) dy = y - y_fit std = ( dy ** 2 ) . mean ( ) ** 0.5 inliers = abs ( dy ) <...
def get_form ( ) : """Return the form to use for commenting ."""
global form_class from fluent_comments import appsettings if form_class is None : if appsettings . FLUENT_COMMENTS_FORM_CLASS : from django . utils . module_loading import import_string form_class = import_string ( appsettings . FLUENT_COMMENTS_FORM_CLASS ) else : from fluent_comments . ...
def voice ( self , consonant ) : '''Voices a consonant , by searching the sound inventory for a consonant having the same features as the argument , but + voice .'''
voiced_consonant = deepcopy ( consonant ) voiced_consonant [ Voiced ] = Voiced . pos return self . _find_sound ( voiced_consonant )
def apt_add_key ( keyid , keyserver = 'keyserver.ubuntu.com' , log = False ) : """trust a new PGP key related to a apt - repository"""
if log : log_green ( 'trusting keyid %s from %s' % ( keyid , keyserver ) ) with settings ( hide ( 'warnings' , 'running' , 'stdout' ) ) : sudo ( 'apt-key adv --keyserver %s --recv %s' % ( keyserver , keyid ) ) return True
def update ( self , ** kwargs ) : """Change the configuration of the resource on the device . This method uses Http PUT alter the service state on the device . The attributes of the instance will be packaged as a dictionary . That dictionary will be updated with kwargs . It is then submitted as JSON to the ...
self . __dict__ . pop ( 'tmCommand' , '' ) self . __dict__ . pop ( 'agent' , '' ) self . __dict__ . pop ( 'method' , '' ) super ( Real_Server , self ) . update ( ** kwargs )
def sent2features ( sentence , template ) : """extract features in a sentence : type sentence : list of token , each token is a list of tag"""
return [ word2features ( sentence , i , template ) for i in range ( len ( sentence ) ) ]
def BatchNorm ( inputs , axis = None , training = None , momentum = 0.9 , epsilon = 1e-5 , center = True , scale = True , beta_initializer = tf . zeros_initializer ( ) , gamma_initializer = tf . ones_initializer ( ) , virtual_batch_size = None , data_format = 'channels_last' , internal_update = False , sync_statistics ...
# parse shapes data_format = get_data_format ( data_format , keras_mode = False ) shape = inputs . get_shape ( ) . as_list ( ) ndims = len ( shape ) assert ndims in [ 2 , 4 ] , ndims if sync_statistics is not None : sync_statistics = sync_statistics . lower ( ) assert sync_statistics in [ None , 'nccl' , 'horovod' ...
def is_production ( flag_name : str = 'PRODUCTION' , strict : bool = False ) : """Reads env ` ` PRODUCTION ` ` variable as a boolean . : param flag _ name : environment variable name : param strict : raise a ` ` ValueError ` ` if variable does not look like a normal boolean : return : ` ` True ` ` if has trut...
return env_bool_flag ( flag_name , strict = strict )
def stop ( self ) : """Request thread to stop . Does not wait for actual termination ( use join ( ) method ) ."""
if self . is_alive ( ) : self . _can_run = False self . _stop_event . set ( ) self . _profiler . total_time += time ( ) - self . _start_time self . _start_time = None
def summary ( self ) : """Summary of model definition for labeling . Intended to be somewhat readable but unique to a given model definition ."""
if self . features is not None : feature_count = len ( self . features ) else : feature_count = 0 feature_hash = 'feathash:' + str ( hash ( tuple ( self . features ) ) ) return ( str ( self . estimator ) , feature_count , feature_hash , self . target )
def p_config ( self , p ) : """config : config contents | contents"""
n = len ( p ) if n == 3 : p [ 0 ] = p [ 1 ] + [ p [ 2 ] ] elif n == 2 : p [ 0 ] = [ 'config' , p [ 1 ] ]
def describe_alarm_history ( self , alarm_name = None , start_date = None , end_date = None , max_records = None , history_item_type = None , next_token = None ) : """Retrieves history for the specified alarm . Filter alarms by date range or item type . If an alarm name is not specified , Amazon CloudWatch retu...
params = { } if alarm_name : params [ 'AlarmName' ] = alarm_name if start_date : params [ 'StartDate' ] = start_date . isoformat ( ) if end_date : params [ 'EndDate' ] = end_date . isoformat ( ) if history_item_type : params [ 'HistoryItemType' ] = history_item_type if max_records : params [ 'MaxRec...
def tryImportModule ( self , name ) : """Imports the module and sets version information If the module cannot be imported , the version is set to empty values ."""
self . _name = name try : import importlib self . _module = importlib . import_module ( name ) except ImportError : self . _module = None self . _version = '' self . _packagePath = '' else : if self . _versionAttribute : self . _version = getattr ( self . _module , self . _versionAttribu...
def backend_status ( self , backend = 'ibmqx4' , access_token = None , user_id = None ) : """Get the status of a chip"""
if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) backend_type = self . _check_backend ( backend , 'status' ) if not backend_type : raise BadBackendError ( backend ) status = self . req . get ( '/Backends/' + backend_type + ...
def infer_type ( data ) : """Infer the type of objects returned by indicators . infer _ type returns : - ' scalar ' for a number or None , - ' summarystats ' for a SummaryStats object , - ' distribution _ scalar ' for a list of scalars , - ' distribution _ summarystats ' for a list of SummaryStats objects...
if isinstance ( data , ( type ( None ) , numbers . Number ) ) : return 'scalar' if isinstance ( data , SummaryStats ) : return 'summarystats' if hasattr ( data , "__len__" ) : # list or numpy array data = [ x for x in data if x is not None ] if len ( data ) == 0 or isinstance ( data [ 0 ] , numbers . Nu...
def lock ( self , page ) : """Locks * page * ."""
result = self . _dokuwiki . send ( 'dokuwiki.setLocks' , lock = [ page ] , unlock = [ ] ) if result [ 'lockfail' ] : raise DokuWikiError ( 'unable to lock page' )
def start ( self ) : '''Create a process in which the isolated code will be run .'''
assert self . _client is None logger . debug ( 'IsolationContext[%d] starting' , id ( self ) ) # Create the queues request_queue = multiprocessing . Queue ( ) response_queue = multiprocessing . Queue ( ) # Launch the server process server = Server ( request_queue , response_queue ) # Do not keep a reference to this obj...
def strip_brackets ( text , brackets = None ) : """Strip brackets and what is inside brackets from text . . . note : : If the text contains only one opening bracket , the rest of the text will be ignored . This is a feature , not a bug , as we want to avoid that this function raises errors too easily ."""
res = [ ] for c , type_ in _tokens ( text , brackets = brackets ) : if type_ == TextType . text : res . append ( c ) return '' . join ( res ) . strip ( )
def check_folder_exists ( project , path , folder_name ) : ''': param project : project id : type project : string : param path : path to where we should look for the folder in question : type path : string : param folder _ name : name of the folder in question : type folder _ name : string : returns : ...
if folder_name is None or path is None : return False try : folder_list = dxpy . api . container_list_folder ( project , { "folder" : path , "only" : "folders" } ) except dxpy . exceptions . DXAPIError as e : if e . name == 'ResourceNotFound' : raise ResolutionError ( str ( e . msg ) ) else : ...
def _cho_solve_AATI ( A , rho , b , c , lwr , check_finite = True ) : """Patched version of : func : ` sporco . linalg . cho _ solve _ AATI ` ."""
N , M = A . shape if N >= M : x = ( b - _cho_solve ( ( c , lwr ) , b . dot ( A ) . T , check_finite = check_finite ) . T . dot ( A . T ) ) / rho else : x = _cho_solve ( ( c , lwr ) , b . T , check_finite = check_finite ) . T return x
def set_field ( self , field , rate , approach = 'linear' , mode = 'persistent' , wait_for_stability = True , delay = 1 ) : """Sets the magnetic field . : param field : The target field in Oersted . . . note : : The conversion is 1 Oe = 0.1 mT . : param rate : The field rate in Oersted per minute . : param ...
self . target_field = field , rate , approach , mode if wait_for_stability and self . system_status [ 'magnet' ] . startswith ( 'persist' ) : # Wait until the persistent switch heats up . time . sleep ( self . magnet_config [ 5 ] ) while wait_for_stability : status = self . system_status [ 'magnet' ] if sta...
def _getresult ( self , captcha_id , timeout = None ) : """Poll until a captcha ` captcha _ id ` has been solved , or the poll times out . The timeout is the default 60 seconds , unless overridden by ` timeout ` ( which is in seconds ) . Polling is done every 8 seconds ."""
timeout = timeout if not timeout : timeout = self . waittime poll_interval = 8 start = time . time ( ) for x in range ( int ( timeout / poll_interval ) + 1 ) : self . log . info ( "Sleeping %s seconds (poll %s of %s, elapsed %0.2fs of %0.2f)." , poll_interval , x , int ( timeout / poll_interval ) + 1 , ( time ....
def pdbechem_parse ( download = False , filename = '/kortemmelab/shared/mirror/PDBeChem/chem_comp.xml' ) : '''This is slower than using SAX but much easier to write / read . If you need this to perform well , rewrite with SAX .'''
xml_data = None if download : # this URL will go out of date try : resource = [ 'ftp.ebi.ac.uk' , '/pub/databases/msd/pdbechem/chem_comp.xml' ] xml_data = get_insecure_resource ( resource [ 0 ] , resource [ 1 ] ) except FTPException550 , e : colortext . error ( "This resource ftp://%s ap...
def _pretend_to_run ( self , migration , method ) : """Pretend to run the migration . : param migration : The migration : type migration : orator . migrations . migration . Migration : param method : The method to execute : type method : str"""
self . _note ( "" ) names = [ ] for query in self . _get_queries ( migration , method ) : name = migration . __class__ . __name__ bindings = None if isinstance ( query , tuple ) : query , bindings = query query = highlight ( query , SqlLexer ( ) , CommandFormatter ( ) ) . strip ( ) if bindin...
def parse_from_template ( template_name ) : """Return an element loaded from the XML in the template file identified by * template _ name * ."""
thisdir = os . path . split ( __file__ ) [ 0 ] filename = os . path . join ( thisdir , '..' , 'templates' , '%s.xml' % template_name ) with open ( filename , 'rb' ) as f : xml = f . read ( ) return parse_xml ( xml )
def save ( self , designName = "" ) : # type : ( ASaveDesign ) - > None """Save the current design to file"""
self . try_stateful_function ( ss . SAVING , ss . READY , self . do_save , designName )
def get_action ( self , create = False ) : """Get the shared widget action for this widget . This API is used to support widgets in tool bars and menus . Parameters create : bool , optional Whether to create the action if it doesn ' t already exist . The default is False . Returns result : QWidgetActi...
action = self . _widget_action if action is None and create : action = self . _widget_action = QWidgetAction ( None ) action . setDefaultWidget ( self . widget ) return action
def to_dict ( self , model_run ) : """Create a Json - like dictionary for a model run object . Extends the basic object with run state , arguments , and optional prediction results or error descriptions . Parameters model _ run : PredictionHandle Returns ( JSON ) Json - like object , i . e . , diction...
# Get the basic Json object from the super class json_obj = super ( DefaultModelRunManager , self ) . to_dict ( model_run ) # Add run state json_obj [ 'state' ] = ModelRunState . to_dict ( model_run . state ) # Add run scheduling Timestamps json_obj [ 'schedule' ] = model_run . schedule # Add experiment information jso...
def _cell_to_python ( cell ) : """Convert a PyOpenXL ' s ` Cell ` object to the corresponding Python object ."""
data_type , value = cell . data_type , cell . value if type ( cell ) is EmptyCell : return None elif data_type == "f" and value == "=TRUE()" : return True elif data_type == "f" and value == "=FALSE()" : return False elif cell . number_format . lower ( ) == "yyyy-mm-dd" : return str ( value ) . split ( "...
def populateImagesFromSurveys ( self , surveys = dss2 + twomass ) : '''Load images from archives .'''
# what ' s the coordinate center ? coordinatetosearch = '{0.ra.deg} {0.dec.deg}' . format ( self . center ) # query sky view for those images paths = astroquery . skyview . SkyView . get_images ( position = coordinatetosearch , radius = self . radius , survey = surveys ) # populate the images for each of these self . i...
def intersperse ( lis , value ) : """Put value between each existing item in list . Parameters lis : list List to intersperse . value : object Value to insert . Returns list interspersed list"""
out = [ value ] * ( len ( lis ) * 2 - 1 ) out [ 0 : : 2 ] = lis return out
def refine_time_offset ( image_list , frame_timestamps , rotation_sequence , rotation_timestamps , camera_matrix , readout_time ) : """Refine a time offset between camera and IMU using rolling shutter aware optimization . To refine the time offset using this function , you must meet the following constraints 1 ...
# ) Track points max_corners = 200 quality_level = 0.07 min_distance = 5 max_tracks = 20 initial_points = cv2 . goodFeaturesToTrack ( image_list [ 0 ] , max_corners , quality_level , min_distance ) ( points , status ) = tracking . track_retrack ( image_list , initial_points ) # Prune to at most max _ tracks number of t...
def pmt_with_id ( self , pmt_id ) : """Get PMT with global pmt _ id"""
try : return self . pmts [ self . _pmt_index_by_pmt_id [ pmt_id ] ] except KeyError : raise KeyError ( "No PMT found for ID: {0}" . format ( pmt_id ) )
def lines_once ( cls , code , ** kwargs ) : """One - off code generation using : meth : ` lines ` . If keyword args are provided , initialized using : meth : ` with _ id _ processor ` ."""
if kwargs : g = cls . with_id_processor ( ) g . _append_context ( kwargs ) else : g = cls ( ) g . lines ( code ) return g . code
def throw ( self , command ) : """Posts an exception ' s stacktrace string as returned by ' traceback . format _ exc ( ) ' in an ' except ' block . : param command : The command object that holds all the necessary information from the remote process ."""
exception_message = '[Process {}{}]:\n{}' . format ( command . pid , ' - {}' . format ( command . process_title ) if command . process_title else '' , command . stacktrace ) message = self . get_format ( ) message = message . replace ( '{L}' , 'EXCEPTION' ) message = '{}\t{}\n' . format ( message , exception_message ) ...
def split_feature ( f , n ) : """Split an interval into ` n ` roughly equal portions"""
if not isinstance ( n , int ) : raise ValueError ( 'n must be an integer' ) orig_feature = copy ( f ) step = ( f . stop - f . start ) / n for i in range ( f . start , f . stop , step ) : f = copy ( orig_feature ) start = i stop = min ( i + step , orig_feature . stop ) f . start = start f . stop ...
def _update ( self ) : r"""Update This method updates the current reconstruction Notes Implements algorithm 3 from [ K2018 ] _"""
# Step 4 from alg . 3 self . _grad . get_grad ( self . _x_old ) self . _u_new = self . _x_old - self . _beta * self . _grad . grad # Step 5 from alg . 3 self . _t_new = 0.5 * ( 1 + np . sqrt ( 1 + 4 * self . _t_old ** 2 ) ) # Step 6 from alg . 3 t_shifted_ratio = ( self . _t_old - 1 ) / self . _t_new sigma_t_ratio = se...
def list_sinks ( self , page_size = None , page_token = None ) : """List sinks for the project associated with this client . See https : / / cloud . google . com / logging / docs / reference / v2 / rest / v2 / projects . sinks / list : type page _ size : int : param page _ size : Optional . The maximum nu...
return self . sinks_api . list_sinks ( self . project , page_size , page_token )
def _registered ( self ) : """A optional boolean property indidcating whether this job store is registered . The registry is the authority on deciding if a job store exists or not . If True , this job store exists , if None the job store is transitioning from True to False or vice versa , if False the job sto...
# The weird mapping of the SDB item attribute value to the property value is due to # backwards compatibility . ' True ' becomes True , that ' s easy . Toil < 3.3.0 writes this at # the end of job store creation . Absence of either the registry , the item or the # attribute becomes False , representing a truly absent ,...
def run_instances ( self , image_id , min_count = 1 , max_count = 1 , key_name = None , security_groups = None , user_data = None , addressing_type = None , instance_type = 'm1.small' , placement = None , kernel_id = None , ramdisk_id = None , monitoring_enabled = False , subnet_id = None , block_device_map = None , di...
params = { 'ImageId' : image_id , 'MinCount' : min_count , 'MaxCount' : max_count } if key_name : params [ 'KeyName' ] = key_name if security_group_ids : l = [ ] for group in security_group_ids : if isinstance ( group , SecurityGroup ) : l . append ( group . id ) else : ...
def validate_config_json ( pjson ) : """Takes the parsed JSON ( output from json . load ) from a configuration file and checks it for common errors ."""
# Make sure that the root json is a dict if type ( pjson ) is not dict : raise ParseError ( "Configuration file should contain a single JSON object/dictionary. Instead got a %s." % type ( pjson ) ) # if ' configuration ' is present it should be a dict of strings and numbers . # The ArgumentParser will do the rest o...
def setup ( self , app ) : """Initialize the plugin . Fill the plugin ' s options from application ."""
self . app = app for name , ptype in self . dependencies . items ( ) : if name not in app . ps or not isinstance ( app . ps [ name ] , ptype ) : raise PluginException ( 'Plugin `%s` requires for plugin `%s` to be installed to the application.' % ( self . name , ptype ) ) for oname , dvalue in self . default...
def get_shelvesets ( self , request_data = None , top = None , skip = None ) : """GetShelvesets . Return a collection of shallow shelveset references . : param : class : ` < TfvcShelvesetRequestData > < azure . devops . v5_0 . tfvc . models . TfvcShelvesetRequestData > ` request _ data : name , owner , and maxC...
query_parameters = { } if request_data is not None : if request_data . name is not None : query_parameters [ 'requestData.name' ] = request_data . name if request_data . owner is not None : query_parameters [ 'requestData.owner' ] = request_data . owner if request_data . max_comment_length i...
def restore_type ( self , dtype , sample = None ) : """Restore type from Pandas"""
# Pandas types if pdc . is_bool_dtype ( dtype ) : return 'boolean' elif pdc . is_datetime64_any_dtype ( dtype ) : return 'datetime' elif pdc . is_integer_dtype ( dtype ) : return 'integer' elif pdc . is_numeric_dtype ( dtype ) : return 'number' # Python types if sample is not None : if isinstance ( ...
def download_sdk ( self , rest_api_id , output_dir , api_gateway_stage = DEFAULT_STAGE_NAME , sdk_type = 'javascript' ) : # type : ( str , str , str , str ) - > None """Download an SDK to a directory . This will generate an SDK and download it to the provided ` ` output _ dir ` ` . If you ' re using ` ` get _ s...
zip_stream = self . get_sdk_download_stream ( rest_api_id , api_gateway_stage = api_gateway_stage , sdk_type = sdk_type ) tmpdir = tempfile . mkdtemp ( ) with open ( os . path . join ( tmpdir , 'sdk.zip' ) , 'wb' ) as f : f . write ( zip_stream . read ( ) ) tmp_extract = os . path . join ( tmpdir , 'extracted' ) wi...
def set_slave_bus_bypass ( self , enable ) : """Put the aux i2c bus on the MPU - 6050 in bypass mode , thus connecting it to the main i2c bus directly Dont forget to use wakeup ( ) or else the slave bus is unavailable : param enable : : return :"""
current = self . i2c_read_register ( 0x37 , 1 ) [ 0 ] if enable : current |= 0b00000010 else : current &= 0b11111101 self . i2c_write_register ( 0x37 , current )
def chmod_and_retry ( func , path , exc_info ) : """Define an error handler to pass to shutil . rmtree . On Windows , when a file is marked read - only as git likes to do , rmtree will fail . To handle that , on errors try to make the file writable . We want to retry most operations here , but listdir is one ...
if func is os . listdir or os . name != 'nt' : raise os . chmod ( path , stat . S_IREAD | stat . S_IWRITE ) # on error , this will raise . func ( path )
def detach ( self , filt , view = None ) : """Detach a filter . Parameters filt : object The filter to detach . view : instance of VisualView | None The view to use ."""
if view is None : self . _vshare . filters . remove ( filt ) for view in self . _vshare . views . keys ( ) : filt . _detach ( view ) else : view . _filters . remove ( filt ) filt . _detach ( view )
def getRemoteFile ( urlOrPath , destPath ) : '''Fetches URL to local path or just returns absolute path . : param urlOrPath : resource locator , generally URL or path : param destPath : path to store the resource , usually a path on file system : return : tuple having ( path , ' local ' / ' remote ' )'''
urlp = urlparse ( urlOrPath ) if urlp . scheme == '' : return ( os . path . abspath ( urlOrPath ) , 'local' ) elif urlp . scheme not in ( 'http' , 'https' ) : return ( urlOrPath , 'local' ) else : filename = toFilename ( urlOrPath ) destPath = destPath + '/' + filename log . info ( 'Retrieving %s to...
def explain_permutation_importance ( estimator , vec = None , top = _TOP , target_names = None , # ignored targets = None , # ignored feature_names = None , feature_re = None , feature_filter = None , ) : """Return an explanation of PermutationImportance . See : func : ` eli5 . explain _ weights ` for description...
coef = estimator . feature_importances_ coef_std = estimator . feature_importances_std_ return get_feature_importance_explanation ( estimator , vec , coef , coef_std = coef_std , feature_names = feature_names , feature_filter = feature_filter , feature_re = feature_re , top = top , description = DESCRIPTION_SCORE_DECRE...
def get_dc_keywords ( index_page ) : """Return list of ` keywords ` parsed from Dublin core . Args : index _ page ( str ) : Content of the page as UTF - 8 string Returns : list : List of : class : ` . SourceString ` objects ."""
keyword_lists = ( keyword_list . split ( ) for keyword_list in parse_meta ( index_page , "dc.keywords" , "DC" ) ) return [ SourceString ( keyword , source = "DC" ) for keyword in sum ( keyword_lists , [ ] ) # flattern the list ]
def spliced_offset ( self , position ) : """Convert from an absolute chromosomal position to the offset into this transcript " s spliced mRNA . Position must be inside some exon ( otherwise raise exception ) ."""
# this code is performance sensitive , so switching from # typechecks . require _ integer to a simpler assertion assert type ( position ) == int , "Position argument must be an integer, got %s : %s" % ( position , type ( position ) ) if position < self . start or position > self . end : raise ValueError ( "Invalid ...
def configure ( self , * , handlers = None , levels = None , extra = None , activation = None ) : """Configure the core logger . It should be noted that ` ` extra ` ` values set using this function are available across all modules , so this is the best way to set overall default values . Parameters handlers...
if handlers is not None : self . remove ( ) else : handlers = [ ] if levels is not None : for params in levels : self . level ( ** params ) if extra is not None : with self . _lock : self . _extra_class . clear ( ) self . _extra_class . update ( extra ) if activation is not None ...
def _render_round_end ( self , rewards : np . array ) -> None : '''Prints round end information about ` rewards ` .'''
print ( "*********************************************************" ) print ( ">>> ROUND END" ) print ( "*********************************************************" ) total_reward = np . sum ( rewards ) print ( "==> Objective value = {}" . format ( total_reward ) ) print ( "==> rewards = {}" . format ( list ( rewards ) ...
def join_room ( room , sid = None , namespace = None ) : """Join a room . This function puts the user in a room , under the current namespace . The user and the namespace are obtained from the event context . This is a function that can only be called from a SocketIO event handler . Example : : @ socketio ....
socketio = flask . current_app . extensions [ 'socketio' ] sid = sid or flask . request . sid namespace = namespace or flask . request . namespace socketio . server . enter_room ( sid , room , namespace = namespace )
def channel ( self , rpc_timeout = 60 , lazy = False ) : """Open Channel . : param int rpc _ timeout : Timeout before we give up waiting for an RPC response from the server . : raises AMQPInvalidArgument : Invalid Parameters : raises AMQPChannelError : Raises if the channel encountered an error . : raises...
LOGGER . debug ( 'Opening a new Channel' ) if not compatibility . is_integer ( rpc_timeout ) : raise AMQPInvalidArgument ( 'rpc_timeout should be an integer' ) elif self . is_closed : raise AMQPConnectionError ( 'socket/connection closed' ) with self . lock : channel_id = self . _get_next_available_channel_...
def create_key ( self , title , key ) : """Create a deploy key . : param str title : ( required ) , title of key : param str key : ( required ) , key text : returns : : class : ` Key < github3 . users . Key > ` if successful , else None"""
json = None if title and key : data = { 'title' : title , 'key' : key } url = self . _build_url ( 'keys' , base_url = self . _api ) json = self . _json ( self . _post ( url , data = data ) , 201 ) return Key ( json , self ) if json else None
def _connected ( self , link_uri ) : """This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded ."""
print ( 'Connected to %s' % link_uri ) mems = self . _cf . mem . get_mems ( MemoryElement . TYPE_I2C ) print ( 'Found {} EEPOM(s)' . format ( len ( mems ) ) ) if len ( mems ) > 0 : print ( 'Writing default configuration to' ' memory {}' . format ( mems [ 0 ] . id ) ) elems = mems [ 0 ] . elements elems [ 'v...
def check_array ( array , accept_sparse = None , dtype = "numeric" , order = None , copy = False , force_all_finite = True , ensure_2d = True , allow_nd = False , ensure_min_samples = 1 , ensure_min_features = 1 , warn_on_dtype = False ) : """Input validation on an array , list , sparse matrix or similar . By def...
if isinstance ( accept_sparse , str ) : accept_sparse = [ accept_sparse ] # store whether originally we wanted numeric dtype dtype_numeric = dtype == "numeric" dtype_orig = getattr ( array , "dtype" , None ) if not hasattr ( dtype_orig , 'kind' ) : # not a data type ( e . g . a column named dtype in a pandas DataFr...
def nvmlDeviceGetAccountingStats ( handle , pid ) : r"""* Queries process ' s accounting stats . * For Kepler & tm ; or newer fully supported devices . * Accounting stats capture GPU utilization and other statistics across the lifetime of a process . * Accounting stats can be queried during life time of the p...
stats = c_nvmlAccountingStats_t ( ) fn = _nvmlGetFunctionPointer ( "nvmlDeviceGetAccountingStats" ) ret = fn ( handle , c_uint ( pid ) , byref ( stats ) ) _nvmlCheckReturn ( ret ) if ( stats . maxMemoryUsage == NVML_VALUE_NOT_AVAILABLE_ulonglong . value ) : # special case for WDDM on Windows , see comment above sta...
def to_dict ( self , tool_long_names = True ) : """Get a representation of the workflow as a dictionary for display purposes : param tool _ long _ names : Indicates whether to use long names , such as SplitterFromStream ( element = None , use _ mapping _ keys _ only = True ) or short names , such as splitte...
d = dict ( nodes = [ ] , factors = [ ] , plates = defaultdict ( list ) ) for node in self . nodes : node_id = self . nodes [ node ] . node_id d [ 'nodes' ] . append ( { 'id' : node_id } ) for plate_id in self . nodes [ node ] . plate_ids : d [ 'plates' ] [ plate_id ] . append ( { 'id' : node_id , 't...
def _print_beam ( self , sequences : mx . nd . NDArray , accumulated_scores : mx . nd . NDArray , finished : mx . nd . NDArray , inactive : mx . nd . NDArray , constraints : List [ Optional [ constrained . ConstrainedHypothesis ] ] , timestep : int ) -> None : """Prints the beam for debugging purposes . : param s...
logger . info ( 'BEAM AT TIMESTEP %d' , timestep ) batch_beam_size = sequences . shape [ 0 ] for i in range ( batch_beam_size ) : # for each hypothesis , print its entire history score = accumulated_scores [ i ] . asscalar ( ) word_ids = [ int ( x . asscalar ( ) ) for x in sequences [ i ] ] unmet = constrai...
def convert_errno ( e ) : """Convert an errno value ( as from an ` ` OSError ` ` or ` ` IOError ` ` ) into a standard SFTP result code . This is a convenience function for trapping exceptions in server code and returning an appropriate result . : param int e : an errno code , as from ` ` OSError . errno ` ` ....
if e == errno . EACCES : # permission denied return SFTP_PERMISSION_DENIED elif ( e == errno . ENOENT ) or ( e == errno . ENOTDIR ) : # no such file return SFTP_NO_SUCH_FILE else : return SFTP_FAILURE
def list_color_tag ( self , pkg ) : """Tag with color installed packages"""
name = GetFromInstalled ( pkg ) . name ( ) find = name + self . meta . sp if pkg . endswith ( ".txz" ) or pkg . endswith ( ".tgz" ) : find = pkg [ : - 4 ] if find_package ( find , self . meta . pkg_path ) : pkg = "{0}{1}{2}" . format ( self . meta . color [ "GREEN" ] , pkg , self . meta . color [ "ENDC" ] ) ret...
def csd ( timeseries , other , segmentlength , noverlap = None , ** kwargs ) : """Calculate the CSD of two ` TimeSeries ` using Welch ' s method Parameters timeseries : ` ~ gwpy . timeseries . TimeSeries ` time - series of data other : ` ~ gwpy . timeseries . TimeSeries ` time - series of data segmentle...
# calculate CSD try : freqs , csd_ = scipy . signal . csd ( timeseries . value , other . value , noverlap = noverlap , fs = timeseries . sample_rate . decompose ( ) . value , nperseg = segmentlength , ** kwargs ) except AttributeError as exc : exc . args = ( '{}, scipy>=0.16 is required' . format ( str ( exc ) ...
def derivativeY ( self , mLvl , pLvl , MedShk ) : '''Evaluate the derivative of consumption and medical care with respect to permanent income at given levels of market resources , permanent income , and medical need shocks . Parameters mLvl : np . array Market resource levels . pLvl : np . array Perma...
xLvl = self . xFunc ( mLvl , pLvl , MedShk ) dxdp = self . xFunc . derivativeY ( mLvl , pLvl , MedShk ) dcdx = self . cFunc . derivativeX ( xLvl , MedShk ) dcdp = dxdp * dcdx dMeddp = ( dxdp - dcdp ) / self . MedPrice return dcdp , dMeddp
def remove ( self , key ) : """Remove the first key - value pair with key * key * . If the key was not found , a ` ` KeyError ` ` is raised ."""
self . _find_lt ( key ) node = self . _path [ 0 ] [ 2 ] if node is self . _tail or key < node [ 0 ] : raise KeyError ( '{!r} is not in list' . format ( key ) ) self . _remove ( node )
def grad_global_norm ( parameters , max_norm ) : """Calculate the 2 - norm of gradients of parameters , and how much they should be scaled down such that their 2 - norm does not exceed ` max _ norm ` . If gradients exist for more than one context for a parameter , user needs to explicitly call ` ` trainer . a...
# collect gradient arrays arrays = [ ] idx = 0 for p in parameters : if p . grad_req != 'null' : p_grads = p . list_grad ( ) arrays . append ( p_grads [ idx % len ( p_grads ) ] ) idx += 1 assert len ( arrays ) > 0 , 'No parameter found available for gradient norm.' # compute gradient norms d...
def help ( self , subject = None , args = None ) : """Get help information about Automation API . The following values can be specified for the subject : None - - gets an overview of help . ' commands ' - - gets a list of API functions command name - - get info about the specified command . object type - ...
if subject : if subject not in ( 'commands' , 'create' , 'config' , 'get' , 'delete' , 'perform' , 'connect' , 'connectall' , 'disconnect' , 'disconnectall' , 'apply' , 'log' , 'help' ) : self . _check_session ( ) status , data = self . _rest . get_request ( 'help' , subject , args ) else : status ,...
def do_help ( self , argv ) : """$ { cmd _ name } : give detailed help on a specific sub - command Usage : $ { name } help [ COMMAND ]"""
if len ( argv ) > 1 : # asking for help on a particular command doc = None cmdname = self . _get_canonical_cmd_name ( argv [ 1 ] ) or argv [ 1 ] if not cmdname : return self . helpdefault ( argv [ 1 ] , False ) else : helpfunc = getattr ( self , "help_" + cmdname , None ) if help...
def get_monitor_ping ( request ) : """MNCore . ping ( ) → Boolean ."""
response = d1_gmn . app . views . util . http_response_with_boolean_true_type ( ) d1_gmn . app . views . headers . add_http_date_header ( response ) return response
def summary ( args ) : """% prog summary txtfile fastafile The txtfile can be generated by : % prog mstmap - - noheader - - freq = 0 Tabulate on all possible combinations of genotypes and provide results in a nicely - formatted table . Give a fastafile for SNP rate ( average # of SNPs per Kb ) . Only thre...
from jcvi . utils . cbook import thousands from jcvi . utils . table import tabulate p = OptionParser ( summary . __doc__ ) p . add_option ( "--counts" , help = "Print SNP counts in a txt file [default: %default]" ) p . add_option ( "--bed" , help = "Print SNPs locations in a bed file [default: %default]" ) opts , args...
def show_fibrechannel_interface_info_output_show_fibrechannel_interface_portsgroup_rbridgeid ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_fibrechannel_interface_info = ET . Element ( "show_fibrechannel_interface_info" ) config = show_fibrechannel_interface_info output = ET . SubElement ( show_fibrechannel_interface_info , "output" ) show_fibrechannel_interface = ET . SubElement ( output , "show-fibrechannel-interfa...
def _make_constants ( func , builtin_only = False , stoplist = None , verbose = None ) : """Generate new function where code is an input function code with all LOAD _ GLOBAL statements changed to LOAD _ CONST statements . : param function func : code function to transform . : param bool builtin _ only : only ...
result = func if stoplist is None : stoplist = [ ] try : fcode = func . __code__ except AttributeError : return func # Jython doesn ' t have a _ _ code _ _ attribute . newcode = list ( fcode . co_code ) if PY3 else [ ord ( co ) for co in fcode . co_code ] newconsts = list ( fcode . co_consts ) names = f...
def namespace_map ( self , target ) : """Returns the namespace _ map used for Thrift generation . : param target : The target to extract the namespace _ map from . : type target : : class : ` pants . backend . codegen . targets . java _ thrift _ library . JavaThriftLibrary ` : returns : The namespaces to rema...
self . _check_target ( target ) return target . namespace_map or self . _default_namespace_map
def show_buff ( self , pos ) : """Return the display of the instruction : rtype : string"""
buff = self . get_name ( ) + " " for i in range ( 0 , len ( self . keys ) ) : buff += "%x:%x " % ( self . keys [ i ] , self . targets [ i ] ) return buff
def to_json_object ( self ) : """Returns a dict representation that can be serialized to JSON ."""
obj_dict = dict ( namespace_start = self . namespace_start , namespace_end = self . namespace_end ) if self . app is not None : obj_dict [ 'app' ] = self . app return obj_dict
def do_req ( self , method , url , body = None , headers = None , status = None ) : """Used internally to send a request to the API , left public so it can be used to talk to the API more directly ."""
if body is None : body = '' else : body = json . dumps ( body ) res = self . backend . dispatch_request ( method = method , url = url , body = body , headers = self . get_headers ( headers ) , auth = self . auth ) if not isinstance ( res , MapiResponse ) : res = MapiResponse ( * res ) if status is None : ...
def scroll_backward_vertically ( self , steps = 10 , * args , ** selectors ) : """Perform scroll backward ( vertically ) action on the object which has * selectors * attributes . Return whether the object can be Scroll or not . See ` Scroll Forward Vertically ` for more details ."""
return self . device ( ** selectors ) . scroll . vert . backward ( steps = steps )
def _days_from_3744 ( hebrew_year ) : """Return : Number of days since 3,1,3744."""
# Start point for calculation is Molad new year 3744 ( 16BC ) years_from_3744 = hebrew_year - 3744 molad_3744 = get_chalakim ( 1 + 6 , 779 ) # Molad 3744 + 6 hours in parts # Time in months # Number of leap months leap_months = ( years_from_3744 * 7 + 1 ) // 19 leap_left = ( years_from_3744 * 7 + 1 ) % 19 # Months left...
def granulometry_filter ( image , min_radius , max_radius , mask = None ) : '''Enhances bright structures within a min and max radius using a rolling ball filter image - grayscale 2 - d image radii - a vector of radii : we enhance holes at each given radius'''
# Do 4 - connected erosion se = np . array ( [ [ False , True , False ] , [ True , True , True ] , [ False , True , False ] ] ) # Initialize inverted_image = image . max ( ) - image previous_opened_image = image eroded_image = image selected_granules_image = np . zeros ( image . shape ) # Select granules by successive ...
def _make_phylesystem_cache_region ( ** kwargs ) : """Only intended to be called by the Phylesystem singleton ."""
global _CACHE_REGION_CONFIGURED , _REGION if _CACHE_REGION_CONFIGURED : return _REGION _CACHE_REGION_CONFIGURED = True try : # noinspection PyPackageRequirements from dogpile . cache import make_region except : _LOG . debug ( 'dogpile.cache not available' ) return region = None trial_key = 'test_key' tr...
def map_rus_to_lat ( char ) : """функция преобразует русские символы в такие же ( по написанию ) латинские"""
map_dict = { u'Е' : u'E' , u'Т' : u'T' , u'У' : u'Y' , u'О' : u'O' , u'Р' : u'P' , u'А' : u'A' , u'Н' : u'H' , u'К' : u'K' , u'Х' : u'X' , u'С' : u'C' , u'В' : u'B' , u'М' : u'M' , } # если буква есть в списке русских сиволов , преобразуем ее в латинский двойник if char in map_dict : return map_dict [ char ] else...
def _item_to_entry ( iterator , entry_pb , loggers ) : """Convert a log entry protobuf to the native object . . . note : : This method does not have the correct signature to be used as the ` ` item _ to _ value ` ` argument to : class : ` ~ google . api _ core . page _ iterator . Iterator ` . It is intended...
resource = _parse_log_entry ( entry_pb ) return entry_from_resource ( resource , iterator . client , loggers )