signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_wish_list_by_id ( cls , wish_list_id , ** kwargs ) : """Find WishList Return single instance of WishList by its ID . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . get _ wish _ list _ by _ id ( wish _ lis...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _get_wish_list_by_id_with_http_info ( wish_list_id , ** kwargs ) else : ( data ) = cls . _get_wish_list_by_id_with_http_info ( wish_list_id , ** kwargs ) return data
def getAsTuple ( self , section ) : """Get section name tuple : param section : section name : return : tuple object"""
keys = self . getKeys ( section ) value_dict = self . getValues ( section ) return namedtuple ( section , keys ) ( ** value_dict )
def visit_IfStatement ( self , node ) : """Visitor for ` IfStatement ` AST node ."""
if_conditon , if_body = node . if_compound self . visit ( if_conditon ) self . visit ( if_body ) for else_if_compound in node . else_if_compounds : else_if_condition , else_if_body = else_if_compound self . visit ( else_if_condition ) self . visit ( else_if_body ) if node . else_compound is not None : _...
def _maybe_get_default_name ( self , name ) : """Checks a name and determines whether to use the default name . : param name : The current name to check . : return : Either None or a : class : ` str ` representing the name ."""
if name is None and self . uri . fragment : name = self . uri . fragment return name
def apply_string_substitutions ( inputs , substitutions , inverse = False , case_insensitive = False , unused_substitutions = "ignore" , ) : """Apply a number of substitutions to a string ( s ) . The substitutions are applied effectively all at once . This means that conflicting substitutions don ' t interact ....
if inverse : substitutions = { v : k for k , v in substitutions . items ( ) } # only possible to have conflicting substitutions when case insensitive if case_insensitive : _check_duplicate_substitutions ( substitutions ) if unused_substitutions != "ignore" : _check_unused_substitutions ( substitutions , inp...
def read_file ( filename : PathLike = "experiment.yml" ) -> Dict [ str , Any ] : """Read and parse yaml file ."""
logger . debug ( "Input file: %s" , filename ) with open ( filename , "r" ) as stream : structure = yaml . safe_load ( stream ) return structure
def _get_signed_predecessors ( im , node , polarity ) : """Get upstream nodes in the influence map . Return the upstream nodes along with the overall polarity of the path to that node by account for the polarity of the path to the given node and the polarity of the edge between the given node and its immediat...
signed_pred_list = [ ] for pred in im . predecessors ( node ) : pred_edge = ( pred , node ) yield ( pred , _get_edge_sign ( im , pred_edge ) * polarity )
def _view_interval ( self , queue_type , queue_id ) : """Updates the queue interval in SharQ ."""
response = { 'status' : 'failure' } try : request_data = json . loads ( request . data ) interval = request_data [ 'interval' ] except Exception , e : response [ 'message' ] = e . message return jsonify ( ** response ) , 400 request_data = { 'queue_type' : queue_type , 'queue_id' : queue_id , 'interval'...
def all ( self ) : """Primary method to fetch data based on filters Also trigged when the QuerySet is evaluated by calling one of the following methods : * len ( ) * bool ( ) * list ( ) * Iteration * Slicing"""
logger . debug ( f'Query `{self.__class__.__name__}` objects with filters {self}' ) # Destroy any cached results self . _result_cache = None # Fetch Model class and connected repository from Repository Factory model_cls = repo_factory . get_model ( self . _entity_cls ) repository = repo_factory . get_repository ( self ...
def _set_on_startup_overloadtime ( self , v , load = False ) : """Setter method for on _ startup _ overloadtime , mapped from YANG variable / routing _ system / router / isis / router _ isis _ cmds _ holder / router _ isis _ attributes / set _ overload _ bit / on _ startup / on _ startup _ overloadtime ( uint32) ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..4294967295' ] } , int_size = 32 ) , restriction_dict = { 'range' : [ u'5..86400' ] } ) , is_leaf = True , yang_na...
def start ( self , max_val ) : """: arg max _ val Maximum value : type max _ val int"""
self . _timer . init_timer ( max_value = max_val ) self . _infinite_mode = max_val <= 0 self . _infinite_position = 0 self . _max = max_val self . _fill_empty ( ) self . _value = 0 self . progress ( 0 ) self . _status = ProgressBarStatus . started
def wav_length ( fn : str ) -> float : """Returns the length of the WAV file in seconds ."""
args = [ config . SOX_PATH , fn , "-n" , "stat" ] p = subprocess . Popen ( args , stdin = PIPE , stdout = PIPE , stderr = PIPE ) length_line = str ( p . communicate ( ) [ 1 ] ) . split ( "\\n" ) [ 1 ] . split ( ) print ( length_line ) assert length_line [ 0 ] == "Length" return float ( length_line [ - 1 ] )
def build_feature_collection ( node , name = None ) : """Build and return a ( decoded ) GeoJSON FeatureCollection corresponding to this KML DOM node ( typically a KML Folder ) . If a name is given , store it in the FeatureCollection ' s ` ` ' name ' ` ` attribute ."""
# Initialize geojson = { 'type' : 'FeatureCollection' , 'features' : [ ] , } # Build features for placemark in get ( node , 'Placemark' ) : feature = build_feature ( placemark ) if feature is not None : geojson [ 'features' ] . append ( feature ) # Give the collection a name if requested if name is not ...
def _delete_images ( self , instance ) : """Deletes all user media images of the given instance ."""
UserMediaImage . objects . filter ( content_type = ContentType . objects . get_for_model ( instance ) , object_id = instance . pk , user = instance . user , ) . delete ( )
def ajax_only ( view_func ) : """Required the view is only accessed via AJAX ."""
@ wraps ( view_func , assigned = available_attrs ( view_func ) ) def _wrapped_view ( request , * args , ** kwargs ) : if request . is_ajax ( ) : return view_func ( request , * args , ** kwargs ) else : return http . HttpResponseBadRequest ( ) return _wrapped_view
def compute_strategy ( self , grads ) : """Returns : bool - False if grads cannot be packed due to various reasons ."""
for g in grads : assert g . shape . is_fully_defined ( ) , "Shape of {} is {}!" . format ( g . name , g . shape ) self . _shapes = [ g . shape for g in grads ] self . _sizes = [ g . shape . num_elements ( ) for g in grads ] self . _total_size = sum ( self . _sizes ) if self . _total_size / self . _num_split < 1024 ...
def stmt2dzn ( name , val , declare = True , assign = True , wrap = True ) : """Returns a dzn statement declaring and assigning the given value . Parameters val The value to serialize . declare : bool Whether to include the declaration of the variable in the statement or just the assignment . assign :...
if not ( declare or assign ) : raise ValueError ( 'The statement must be a declaration or an assignment.' ) stmt = [ ] if declare : val_type = _dzn_type ( val ) stmt . append ( '{}: ' . format ( val_type ) ) stmt . append ( name ) if assign : val_str = val2dzn ( val , wrap = wrap ) stmt . append ( '...
def get_interface_detail_output_interface_port_role ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_interface_detail = ET . Element ( "get_interface_detail" ) config = get_interface_detail output = ET . SubElement ( get_interface_detail , "output" ) interface = ET . SubElement ( output , "interface" ) interface_type_key = ET . SubElement ( interface , "interface-type" ) interfac...
def _get_dict_default ( obj , key ) : """obj MUST BE A DICT key IS EXPECTED TO BE LITERAL ( NO ESCAPING ) TRY BOTH ATTRIBUTE AND ITEM ACCESS , OR RETURN Null"""
try : return obj [ key ] except Exception as f : pass try : if float ( key ) == round ( float ( key ) , 0 ) : return obj [ int ( key ) ] except Exception as f : pass return NullType ( obj , key )
def n_to_one ( num_inputs , num_streams , bits_per_axis , weight_per_axis ) : """Creating inputs of the form : ` ` ( x , y , . . . , y ) ' ' Here n = num _ streams - 1. To be more precise , for each component we allocate a fixed number of units ` bits _ per _ axis ` and encode each component with a scalar e...
num_bits = num_streams * bits_per_axis # Setting up the scalar encoder encoder_params = { "dimensions" : num_streams , "max_values" : [ [ 0. , 1. ] ] * num_streams , "bits_per_axis" : [ bits_per_axis ] * num_streams , "weight_per_axis" : [ weight_per_axis ] * num_streams , "wrap_around" : False } scalar_encode = Scalar...
def get_email_context ( self , ** kwargs ) : '''Overrides EmailRecipientMixin'''
includeName = kwargs . pop ( 'includeName' , True ) context = super ( EventRegistration , self ) . get_email_context ( ** kwargs ) context . update ( { 'title' : self . event . name , 'start' : self . event . firstOccurrenceTime , 'end' : self . event . lastOccurrenceTime , } ) if includeName : context . update ( {...
def check_password ( self , hashed_password , plain_password ) : """Encode the plain _ password with the salt of the hashed _ password . Return the comparison with the encrypted _ password ."""
salt , encrypted_password = hashed_password . split ( '$' ) re_encrypted_password = self . get_hash ( salt , plain_password ) return encrypted_password == re_encrypted_password
def _pypi_head_package ( dependency ) : """Hit pypi with a http HEAD to check if pkg _ name exists ."""
if dependency . specs : _ , version = dependency . specs [ 0 ] url = BASE_PYPI_URL_WITH_VERSION . format ( name = dependency . project_name , version = version ) else : url = BASE_PYPI_URL . format ( name = dependency . project_name ) logger . debug ( "Doing HEAD requests against %s" , url ) req = request ....
def split_input ( cls , job_config ) : """Inherit docs ."""
params = job_config . input_reader_params count = params [ cls . COUNT ] string_length = params . get ( cls . STRING_LENGTH , cls . _DEFAULT_STRING_LENGTH ) shard_count = job_config . shard_count count_per_shard = count // shard_count mr_input_readers = [ cls ( count_per_shard , string_length ) for _ in range ( shard_c...
def username_validator ( self , form , field ) : """Ensure that Usernames contains at least 3 alphanumeric characters . Override this method to customize the username validator ."""
username = field . data if len ( username ) < 3 : raise ValidationError ( _ ( 'Username must be at least 3 characters long' ) ) valid_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._' chars = list ( username ) for char in chars : if char not in valid_chars : raise ValidationErr...
def update_letter ( self , letter_id , letter_dict ) : """Updates a letter : param letter _ id : the letter id : param letter _ dict : dict : return : dict"""
return self . _create_put_request ( resource = LETTERS , billomat_id = letter_id , send_data = letter_dict )
def snmp_server_group_group_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) snmp_server = ET . SubElement ( config , "snmp-server" , xmlns = "urn:brocade.com:mgmt:brocade-snmp" ) group = ET . SubElement ( snmp_server , "group" ) group_version_key = ET . SubElement ( group , "group-version" ) group_version_key . text = kwargs . pop ( 'group_version' ) group_na...
def get_loggable_url ( url ) : """Strip out secrets from taskcluster urls . Args : url ( str ) : the url to strip Returns : str : the loggable url"""
loggable_url = url or "" for secret_string in ( "bewit=" , "AWSAccessKeyId=" , "access_token=" ) : parts = loggable_url . split ( secret_string ) loggable_url = parts [ 0 ] if loggable_url != url : loggable_url = "{}<snip>" . format ( loggable_url ) return loggable_url
def check_odd ( num ) : """Python function to verify if a number is odd utilizing bitwise operators . > > > check _ odd ( 5) True > > > check _ odd ( 6) False > > > check _ odd ( 7) True"""
return True if ( num ^ 1 ) == ( num - 1 ) else False
def gen_scripts ( file_name , file_name_ext , obj_name , obj_ext_name , output , output_ext , field = 1 , notexplicit = None , ascii_props = False , append = False , prefix = "" ) : """Generate ` script ` property ."""
obj = { } obj2 = { } aliases = { } with codecs . open ( os . path . join ( HOME , 'unicodedata' , UNIVERSION , 'PropertyValueAliases.txt' ) , 'r' , 'utf-8' ) as uf : for line in uf : if line . startswith ( 'sc ;' ) : values = line . split ( ';' ) aliases [ format_name ( values [ 1 ] ...
def setData ( self , index , value , role = Qt . EditRole ) : """Cell content change"""
if not index . isValid ( ) or self . readonly : return False i = index . row ( ) j = index . column ( ) value = from_qvariant ( value , str ) dtype = self . _data . dtype . name if dtype == "bool" : try : val = bool ( float ( value ) ) except ValueError : val = value . lower ( ) == "true" el...
def wrap ( s , prefix = r'\b' , suffix = r'\b' , grouper = '()' ) : r"""Wrap a string ( tyically a regex ) with a prefix and suffix ( usually a nonconuming word break ) Arguments : prefix , suffix ( str ) : strings to append to the front and back of the provided string grouper ( 2 - len str or 2 - tuple ) : c...
return ( ( prefix or '' ) + try_get ( grouper , 0 , '' ) + ( s or '' ) + try_get ( grouper , 1 , try_get ( grouper , 0 , '' ) ) + ( suffix or '' ) )
def prices ( self ) : """TimeSeries of prices ."""
if self . root . stale : self . root . update ( self . now , None ) return self . _prices . loc [ : self . now ]
def _find_next_widget ( self , direction , stay_in_col = False , start_at = None , wrap = False ) : """Find the next widget to get the focus , stopping at the start / end of the list if hit . : param direction : The direction to move through the widgets . : param stay _ in _ col : Whether to limit search to cur...
current_widget = self . _live_widget current_col = self . _live_col if start_at is not None : self . _live_widget = start_at still_looking = True while still_looking : while 0 <= self . _live_col < len ( self . _columns ) : self . _live_widget += direction while 0 <= self . _live_widget < len ( ...
def is_complex ( arg ) : '''is _ complex ( x ) yields True if x is a complex numeric object and False otherwise . Note that this includes anything representable as as a complex number such as an integer or a boolean value . In effect , this makes this function an alias for is _ number ( arg ) .'''
return ( is_complex ( mag ( arg ) ) if is_quantity ( arg ) else True if isinstance ( arg , numbers . Complex ) else is_npscalar ( arg , 'complex' ) or is_npvalue ( arg , 'complex' ) )
def IOW ( type , nr , size ) : """An ioctl with write parameters . size ( ctype type or instance ) Type / structure of the argument passed to ioctl ' s " arg " argument ."""
return IOC ( IOC_WRITE , type , nr , IOC_TYPECHECK ( size ) )
def MaxPool3D ( a , k , strides , padding ) : """Maximum 3D pooling op ."""
patches = _pool_patches ( a , k , strides , padding . decode ( "ascii" ) ) return np . amax ( patches , axis = tuple ( range ( - len ( k ) , 0 ) ) ) ,
def join_struct_arrays ( arrays ) : """Takes a list of possibly structured arrays , concatenates their dtypes , and returns one big array with that dtype . Does the inverse of ` ` separate _ struct _ array ` ` . : param list arrays : List of ` ` np . ndarray ` ` s"""
# taken from http : / / stackoverflow . com / questions / 5355744 / numpy - joining - structured - arrays sizes = np . array ( [ a . itemsize for a in arrays ] ) offsets = np . r_ [ 0 , sizes . cumsum ( ) ] shape = arrays [ 0 ] . shape joint = np . empty ( shape + ( offsets [ - 1 ] , ) , dtype = np . uint8 ) for a , si...
def _interval_string_to_seconds ( interval_string ) : """Convert internal string like 1M , 1Y3M , 3W to seconds . : type interval _ string : str : param interval _ string : Interval string like 1M , 1W , 1M3W4h2s . . . ( s = > seconds , m = > minutes , h = > hours , D = > days , W = > weeks , M = > months ,...
interval_exc = "Bad interval format for {0}" . format ( interval_string ) interval_dict = { "s" : 1 , "m" : 60 , "h" : 3600 , "D" : 86400 , "W" : 7 * 86400 , "M" : 30 * 86400 , "Y" : 365 * 86400 } interval_regex = re . compile ( "^(?P<num>[0-9]+)(?P<ext>[smhDWMY])" ) seconds = 0 while interval_string : match = inte...
def densenet121 ( num_classes = 1000 , pretrained = 'imagenet' ) : r"""Densenet - 121 model from ` " Densely Connected Convolutional Networks " < https : / / arxiv . org / pdf / 1608.06993 . pdf > `"""
model = models . densenet121 ( pretrained = False ) if pretrained is not None : settings = pretrained_settings [ 'densenet121' ] [ pretrained ] model = load_pretrained ( model , num_classes , settings ) model = modify_densenets ( model ) return model
def mount ( self , fstype = None ) : """Based on the file system type as determined by : func : ` determine _ fs _ type ` , the proper mount command is executed for this volume . The volume is mounted in a temporary path ( or a pretty path if : attr : ` pretty ` is enabled ) in the mountpoint as specified by : ...
if not self . parent . is_mounted : raise NotMountedError ( self . parent ) if fstype is None : fstype = self . determine_fs_type ( ) self . _load_fsstat_data ( ) # Prepare mount command try : fstype . mount ( self ) self . was_mounted = True self . is_mounted = True self . fstype = fstype excep...
def get_infix_items ( tokens , callback = infix_error ) : """Perform infix token processing . Takes a callback that ( takes infix tokens and returns a string ) to handle inner infix calls ."""
internal_assert ( len ( tokens ) >= 3 , "invalid infix tokens" , tokens ) ( arg1 , func , arg2 ) , tokens = tokens [ : 3 ] , tokens [ 3 : ] args = list ( arg1 ) + list ( arg2 ) while tokens : args = [ callback ( [ args , func , [ ] ] ) ] ( func , newarg ) , tokens = tokens [ : 2 ] , tokens [ 2 : ] args += l...
def import_xml ( self , xml_gzipped_file_path , taxids = None , silent = False ) : """Imports XML : param str xml _ gzipped _ file _ path : path to XML file : param Optional [ list [ int ] ] taxids : NCBI taxonomy identifier : param bool silent : no output if True"""
version = self . session . query ( models . Version ) . filter ( models . Version . knowledgebase == 'Swiss-Prot' ) . first ( ) version . import_start_date = datetime . now ( ) entry_xml = '<entries>' number_of_entries = 0 interval = 1000 start = False if sys . platform in ( 'linux' , 'linux2' , 'darwin' ) : log . ...
def optimize_forecasting_method ( self , timeSeries , forecastingMethod ) : """Optimizes the parameters for the given timeSeries and forecastingMethod . : param TimeSeries timeSeries : TimeSeries instance , containing hte original data . : param BaseForecastingMethod forecastingMethod : ForecastingMethod that i...
tuneableParameters = forecastingMethod . get_optimizable_parameters ( ) remainingParameters = [ ] for tuneableParameter in tuneableParameters : remainingParameters . append ( [ tuneableParameter , [ item for item in self . _generate_next_parameter_value ( tuneableParameter , forecastingMethod ) ] ] ) # Collect the ...
def get_records ( self , name ) : """Return all the records for the given name in the cache . Args : name ( string ) : The name which the required models are stored under . Returns : list : A list of : class : ` cinder _ data . model . CinderModel ` models ."""
if name in self . _cache : return self . _cache [ name ] . values ( ) else : return [ ]
def _strip_leading_zeros ( coeffs , threshold = _COEFFICIENT_THRESHOLD ) : r"""Strip leading zero coefficients from a polynomial . . . note : : This assumes the polynomial : math : ` f ` defined by ` ` coeffs ` ` has been normalized ( via : func : ` . normalize _ polynomial ` ) . Args : coeffs ( numpy . n...
while np . abs ( coeffs [ - 1 ] ) < threshold : coeffs = coeffs [ : - 1 ] return coeffs
def _press_special_key ( self , key , down ) : """Helper method for special keys . Source : http : / / stackoverflow . com / questions / 11045814 / emulate - media - key - press - on - mac"""
key_code = special_key_translate_table [ key ] ev = NSEvent . otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_ ( NSSystemDefined , # type ( 0 , 0 ) , # location 0xa00 if down else 0xb00 , # flags 0 , # timestamp 0 , # window 0 , # ctx 8 , # subtype ( key_code << 16 ) | ( ( 0...
def filter_geometry ( queryset , ** filters ) : """Helper function for spatial lookups filters . Provide spatial lookup types as keywords without underscores instead of the usual " geometryfield _ _ lookuptype " format ."""
fieldname = geo_field ( queryset ) . name query = { '%s__%s' % ( fieldname , k ) : v for k , v in filters . items ( ) } return queryset . filter ( ** query )
def check_name_collision ( self , name , block_id , checked_ops ) : """Are there any colliding names in this block ? Set the ' _ _ collided _ _ ' flag and related flags if so , so we don ' t commit them . Not called directly ; called by the @ state _ create ( ) decorator in blockstack . lib . operations . regis...
return self . check_collision ( "name" , name , block_id , checked_ops , OPCODE_NAME_STATE_CREATIONS )
def smooth_n_point ( scalar_grid , n = 5 , passes = 1 ) : """Filter with normal distribution of weights . Parameters scalar _ grid : array - like or ` pint . Quantity ` Some 2D scalar grid to be smoothed . n : int The number of points to use in smoothing , only valid inputs are 5 and 9 . Defaults to 5. ...
if n == 9 : p = 0.25 q = 0.125 r = 0.0625 elif n == 5 : p = 0.5 q = 0.125 r = 0.0 else : raise ValueError ( 'The number of points to use in the smoothing ' 'calculation must be either 5 or 9.' ) smooth_grid = scalar_grid [ : ] . copy ( ) for _i in range ( passes ) : smooth_grid [ 1 : - 1...
def change_logger_levels ( logger = None , level = logging . DEBUG ) : """Go through the logger and handlers and update their levels to the one specified . : param logger : logging name or object to modify , defaults to root logger : param level : logging level to set at ( 10 = Debug , 20 = Info , 30 = Warn ,...
if not isinstance ( logger , logging . Logger ) : logger = logging . getLogger ( logger ) logger . setLevel ( level ) for handler in logger . handlers : handler . level = level
def cd_ctx ( directory ) : """Context manager . Stores current dir , then changes to given directory . At the end it changes back . : param directory : : return :"""
prevdir = os . path . abspath ( os . curdir ) if os . path . isdir ( directory ) : os . chdir ( directory ) yield os . chdir ( prevdir )
def get_hierarchy_admin_session ( self , proxy ) : """Gets the hierarchy administrative session . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . hierarchy . HierarchyAdminSession ) - a ` ` HierarchyAdminSession ` ` raise : NullArgument - ` ` proxy ` ` is ` ` null ` ` raise : OperationFai...
if not self . supports_hierarchy_admin ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . HierarchyAdminSession ( proxy = proxy , runtime = self . _runtime )
def _get_fans ( shape ) : r"""Returns the size of input dimension and output dimension , given ` shape ` . Args : shape : A list of integers . Returns : fan _ in : An int . The value of input dimension . fan _ out : An int . The value of output dimension ."""
if len ( shape ) == 2 : fan_in = shape [ 0 ] fan_out = shape [ 1 ] elif len ( shape ) == 4 or len ( shape ) == 5 : # assuming convolution kernels ( 2D or 3D ) . kernel_size = np . prod ( shape [ : 2 ] ) fan_in = shape [ - 2 ] * kernel_size fan_out = shape [ - 1 ] * kernel_size else : # no specific a...
def convertbinary ( value , argument ) : """Convert text to binary form or backwards . : type value : string : param value : The text or the binary text : type argument : string : param argument : The action to perform on the value . Can be " to " or " from " ."""
if argument == 'to' : return bin ( value ) elif argument == 'from' : return format ( value ) raise ValueError ( "Invalid argument specified." )
def canonical_headers ( self , headers_to_sign ) : """Return the headers that need to be included in the StringToSign in their canonical form by converting all header keys to lower case , sorting them in alphabetical order and then joining them into a string , separated by newlines ."""
l = [ '%s:%s' % ( n . lower ( ) . strip ( ) , headers_to_sign [ n ] . strip ( ) ) for n in headers_to_sign ] l . sort ( ) return '\n' . join ( l )
def getAnalogID ( self , num ) : """Returns the COMTRADE ID of a given channel number . The number to be given is the same of the COMTRADE header ."""
listidx = self . An . index ( num ) # Get the position of the channel number . return self . Ach_id [ listidx ]
def import_tf_tensor ( self , x , tf_x ) : """Import a tf . Tensor , producing a LaidOutTensor . Args : x : a Tensor tf _ x : a tf . Tensor Returns : a LaidOutTensor"""
return self . LaidOutTensor ( self . make_slices ( tf_x , x . shape ) )
def virtual_resource ( self ) : """Available on a Master Engine only . To get all virtual resources call : : engine . virtual _ resource . all ( ) : raises UnsupportedEngineFeature : master engine only : rtype : CreateCollection ( VirtualResource )"""
resource = create_collection ( self . get_relation ( 'virtual_resources' , UnsupportedEngineFeature ) , VirtualResource ) resource . _load_from_engine ( self , 'virtualResources' ) return resource
def close ( self ) : """Close the underlying hdf5 file"""
if self . parent != ( ) : self . parent . flush ( ) self . parent . close ( ) if self . hdf5 : # is open self . hdf5 . flush ( ) self . hdf5 . close ( ) self . hdf5 = ( )
def _update_buffers ( self , from_step , data , offset , is_last ) : """Update the buffers of all steps that need data from ` ` from _ step ` ` . If ` ` from _ step ` ` is None it means the data is the input data ."""
for to_step , buffer in self . target_buffers [ from_step ] : parent_index = 0 # if there multiple inputs we have to get the correct index , to keep the ordering if isinstance ( to_step , Reduction ) : parent_index = to_step . parents . index ( from_step ) buffer . update ( data , offset , is_la...
def _get_property_columns ( tabletype , columns ) : """Returns list of GPS columns required to read gpsproperties for a table Examples > > > _ get _ property _ columns ( lsctables . SnglBurstTable , [ ' peak ' ] ) [ ' peak _ time ' , ' peak _ time _ ns ' ]"""
from ligo . lw . lsctables import gpsproperty as GpsProperty # get properties for row object rowvars = vars ( tabletype . RowType ) # build list of real column names for fancy properties extracols = { } for key in columns : prop = rowvars [ key ] if isinstance ( prop , GpsProperty ) : extracols [ key ] ...
def __parse_domain_to_employer_line ( self , raw_domain , raw_org ) : """Parse domain to employer lines"""
d = re . match ( self . DOMAIN_REGEX , raw_domain , re . UNICODE ) if not d : cause = "invalid domain format: '%s'" % raw_domain raise InvalidFormatError ( cause = cause ) dom = d . group ( 'domain' ) . strip ( ) o = re . match ( self . ORGANIZATION_REGEX , raw_org , re . UNICODE ) if not o : cause = "inval...
def connectRoute ( amp , router , receiver , protocol ) : """Connect the given receiver to a new box receiver for the given protocol . After connecting this router to an AMP server , use this method similarly to how you would use C { reactor . connectTCP } to establish a new connection to an HTTP , SMTP , o...
route = router . bindRoute ( receiver ) d = amp . callRemote ( Connect , origin = route . localRouteName , protocol = protocol ) def cbGotRoute ( result ) : route . connectTo ( result [ 'route' ] ) return receiver d . addCallback ( cbGotRoute ) return d
def get_residue_mapping ( self ) : '''Returns a mapping between the sequences ONLY IF there are exactly two . This restriction makes the code much simpler .'''
if len ( self . sequence_ids ) == 2 : if not self . alignment_output : self . align ( ) assert ( self . alignment_output ) return self . _create_residue_map ( self . _get_alignment_lines ( ) , self . sequence_ids [ 1 ] , self . sequence_ids [ 2 ] ) else : return None
def _generate_data_for_format ( fmt ) : """Generate a fake data dictionary to fill in the provided format string ."""
# finally try some data , create some random data for the fmt . data = { } # keep track of how many " free _ size " ( wildcard ) parameters we have # if we get two in a row then we know the pattern is invalid , meaning # we ' ll never be able to match the second wildcard field free_size_start = False for literal_text ,...
def trace3D ( self ) : """Give a 3D representation of the traceroute . right button : rotate the scene middle button : zoom left button : move the scene left button on a ball : toggle IP displaying ctrl - left button on a ball : scan ports 21,22,23,25,80 and 443 and display the result"""
trace = self . get_trace ( ) import visual class IPsphere ( visual . sphere ) : def __init__ ( self , ip , ** kargs ) : visual . sphere . __init__ ( self , ** kargs ) self . ip = ip self . label = None self . setlabel ( self . ip ) def setlabel ( self , txt , visible = None ) : ...
def error_and_result ( f ) : """Format task result into json dictionary ` { ' data ' : task return value } ` if no exception was raised during the task execution . If there was raised an exception during task execution , formats task result into dictionary ` { ' error ' : exception message with traceback } ` ...
@ wraps ( f ) def error_and_result_decorator ( * args , ** kwargs ) : return error_and_result_decorator_inner_fn ( f , False , * args , ** kwargs ) return error_and_result_decorator
async def close ( self ) -> None : """Explicit exit . If so configured , populate cache to prove for any creds on schemata , cred defs , and rev regs marked of interest in configuration at initialization , archive cache , and purge prior cache archives . : return : current object"""
LOGGER . debug ( 'OrgHubAnchor.close >>>' ) archive_caches = False if self . config . get ( 'archive-holder-prover-caches-on-close' , False ) : archive_caches = True await self . load_cache_for_proof ( False ) if self . config . get ( 'archive-verifier-caches-on-close' , { } ) : archive_caches = True aw...
def duplicateAnalysis ( analysis ) : """Duplicate an analysis consist on creating a new analysis with the same analysis service for the same sample . It is used in order to reduce the error procedure probability because both results must be similar . : base : the analysis object used as the creation base ."...
ar = analysis . aq_parent kw = analysis . getKeyword ( ) # Rename the analysis to make way for it ' s successor . # Support multiple duplicates by renaming to * - 0 , * - 1 , etc cnt = [ x for x in ar . objectValues ( "Analysis" ) if x . getId ( ) . startswith ( kw ) ] a_id = "{0}-{1}" . format ( kw , len ( cnt ) ) dup...
def set_dynamic_settings ( s ) : """Called at the end of the project ' s settings module , and is passed its globals dict for updating with some final tweaks for settings that generally aren ' t specified , but can be given some better defaults based on other settings that have been specified . Broken out i...
# Moves an existing list setting value to a different position . move = lambda n , k , i : s [ n ] . insert ( i , s [ n ] . pop ( s [ n ] . index ( k ) ) ) # Add a value to the end of a list setting if not in the list . append = lambda n , k : s [ n ] . append ( k ) if k not in s [ n ] else None # Add a value to the st...
def DocInheritMeta ( style = "parent" , abstract_base_class = False ) : """A metaclass that merges the respective docstrings of a parent class and of its child , along with their properties , methods ( including classmethod , staticmethod , decorated methods ) . Parameters style : Union [ Any , Callable [ [ s...
merge_func = store [ style ] metaclass = _DocInheritorBase metaclass . class_doc_inherit = staticmethod ( merge_func ) metaclass . attr_doc_inherit = staticmethod ( merge_func ) return metaclass if not abstract_base_class else type ( "abc" + metaclass . __name__ , ( _ABCMeta , metaclass ) , { } )
def insert ( self , space_no , * args ) : """insert tuple , if primary key exists server will return error"""
d = self . replyQueue . get ( ) packet = RequestInsert ( self . charset , self . errors , d . _ipro_request_id , space_no , Request . TNT_FLAG_ADD , * args ) self . transport . write ( bytes ( packet ) ) return d . addCallback ( self . handle_reply , self . charset , self . errors , None )
def every ( delay , task , name ) : """Executes a task every ` delay ` seconds : param delay : the delay in seconds : param task : the method to run . The method should return False if you want the loop to stop . : return : None"""
next_time = time . time ( ) + delay while True : time . sleep ( max ( 0 , next_time - time . time ( ) ) ) try : if task ( ) is False : break except Exception : logger . debug ( "Problem while executing repetitive task: %s" % name , exc_info = True ) # skip tasks if we are beh...
def led_rgb ( self , color ) : """Set devices LED color ."""
if ( not isinstance ( color , ( list , tuple ) ) or not all ( isinstance ( item , int ) for item in color ) ) : raise SkybellException ( ERROR . COLOR_VALUE_NOT_VALID , color ) self . _set_setting ( { CONST . SETTINGS_LED_R : color [ 0 ] , CONST . SETTINGS_LED_G : color [ 1 ] , CONST . SETTINGS_LED_B : color [ 2 ] ...
def get_albums ( self , search , start = 0 , max_items = 100 ) : """Search for albums . See get _ music _ service _ information for details on the arguments"""
return self . get_music_service_information ( 'albums' , search , start , max_items )
def cache_files ( db , aid : int , anime_files : AnimeFiles ) -> None : """Cache files for anime ."""
with db : cache_status ( db , aid ) db . cursor ( ) . execute ( """UPDATE cache_anime SET anime_files=? WHERE aid=?""" , ( anime_files . to_json ( ) , aid ) )
def use_comparative_proficiency_view ( self ) : """Pass through to provider ProficiencyLookupSession . use _ comparative _ proficiency _ view"""
self . _object_views [ 'proficiency' ] = COMPARATIVE # self . _ get _ provider _ session ( ' proficiency _ lookup _ session ' ) # To make sure the session is tracked for session in self . _get_provider_sessions ( ) : try : session . use_comparative_proficiency_view ( ) except AttributeError : pa...
def properties_from_mapping ( self , bt_addr ) : """Retrieve properties ( namespace , instance ) for the specified bt address ."""
for addr , properties in self . eddystone_mappings : if addr == bt_addr : return properties return None
def plot ( self , size = 1 ) : """Plot the values in the color palette as a horizontal array . See Seaborn ' s palplot function for inspiration . Parameters size : int scaling factor for size of the plot"""
n = len ( self ) fig , ax = plt . subplots ( 1 , 1 , figsize = ( n * size , size ) ) ax . imshow ( np . arange ( n ) . reshape ( 1 , n ) , cmap = mpl . colors . ListedColormap ( list ( self ) ) , interpolation = "nearest" , aspect = "auto" ) ax . set_xticks ( np . arange ( n ) - .5 ) ax . set_yticks ( [ - .5 , .5 ] ) a...
def toggle_item ( self , item , test_func , field_name = None ) : """Toggles the section based on test _ func . test _ func takes an item and returns a boolean . If it returns True , the item will be added to the given section . It will be removed from the section otherwise . Intended for use with items of ...
if test_func ( item ) : self . add_item ( item , field_name ) return True else : self . remove_item ( item , field_name ) return False
def get_chat_members_count ( self , chat_id : Union [ int , str ] ) -> int : """Use this method to get the number of members in a chat . Args : chat _ id ( ` ` int ` ` | ` ` str ` ` ) : Unique identifier ( int ) or username ( str ) of the target chat . Returns : On success , an integer is returned . Rai...
peer = self . resolve_peer ( chat_id ) if isinstance ( peer , types . InputPeerChat ) : return self . send ( functions . messages . GetChats ( id = [ peer . chat_id ] ) ) . chats [ 0 ] . participants_count elif isinstance ( peer , types . InputPeerChannel ) : return self . send ( functions . channels . GetFullC...
def get_bank_lookup_session ( self ) : """Gets the OsidSession associated with the bank lookup service . return : ( osid . assessment . BankLookupSession ) - a ` ` BankLookupSession ` ` raise : OperationFailed - unable to complete request raise : Unimplemented - ` ` supports _ bank _ lookup ( ) is false ` `...
if not self . supports_bank_lookup ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . BankLookupSession ( runtime = self . _runtime )
def delete_observation ( observation_id : int , access_token : str ) -> List [ Dict [ str , Any ] ] : """Delete an observation . : param observation _ id : : param access _ token : : return :"""
headers = _build_auth_header ( access_token ) headers [ 'Content-type' ] = 'application/json' response = requests . delete ( url = "{base_url}/observations/{id}.json" . format ( base_url = INAT_BASE_URL , id = observation_id ) , headers = headers ) response . raise_for_status ( ) # According to iNaturalist documentatio...
def first_and_second_harmonic_function ( phi , c ) : """Compute the harmonic function value used to calculate the corrections for ellipse fitting . This function includes simultaneously both the first and second order harmonics : . . math : : f ( phi ) = c [ 0 ] + c [ 1 ] * \\ sin ( phi ) + c [ 2 ] * \\ c...
return ( c [ 0 ] + c [ 1 ] * np . sin ( phi ) + c [ 2 ] * np . cos ( phi ) + c [ 3 ] * np . sin ( 2 * phi ) + c [ 4 ] * np . cos ( 2 * phi ) )
def setValue ( self , value ) : """Cast some known data in custom parameters ."""
if self . name in self . _CUSTOM_INT_PARAMS : value = int ( value ) elif self . name in self . _CUSTOM_FLOAT_PARAMS : value = float ( value ) elif self . name in self . _CUSTOM_BOOL_PARAMS : value = bool ( value ) elif self . name in self . _CUSTOM_INTLIST_PARAMS : value = readIntlist ( value ) elif sel...
def upload ( ctx , yes = False ) : """Upload the package to PyPI ."""
import callee version = callee . __version__ # check the packages version # TODO : add a ' release ' to automatically bless a version as release one if version . endswith ( '-dev' ) : fatal ( "Can't upload a development version (%s) to PyPI!" , version ) # run the upload if it has been confirmed by the user if not ...
def isset ( name ) : """Only execute the function if the variable is set . Args : name : The name of the environment variable Returns : The function return value or ` None ` if the function was skipped ."""
def wrapped ( func ) : @ functools . wraps ( func ) def _decorator ( * args , ** kwargs ) : if core . isset ( name ) : return func ( * args , ** kwargs ) return _decorator return wrapped
def delete_project ( self , owner , id , ** kwargs ) : """Delete a project Permanently deletes a project and all data associated with it . This operation cannot be undone , although a new project may be created with the same id . This method makes a synchronous HTTP request by default . To make an asynchronou...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . delete_project_with_http_info ( owner , id , ** kwargs ) else : ( data ) = self . delete_project_with_http_info ( owner , id , ** kwargs ) return data
def is_sleep ( key ) : """Determine return data by use cache if this key is in the sleep time window ( happened error )"""
lock . acquire ( ) try : if key not in sleep_record : return False return time . time ( ) < sleep_record [ key ] finally : lock . release ( )
def _initialize ( self ) : """Initialize the binary . : return : None"""
# figure out section alignments for section in self . project . loader . main_object . sections : in_segment = False for segment in self . project . loader . main_object . segments : segment_addr = segment . vaddr if segment_addr <= section . vaddr < segment_addr + segment . memsize : ...
def make_container_tree ( folders , files , path_delim = "/" , parse_files = True ) : '''make _ container _ tree will convert a list of folders and files into a json structure that represents a graph . : param folders : a list of folders in the image : param files : a list of files in the folder : param parse...
nodes = { } # first we will make a list of nodes lookup = { } count = 1 # count will hold an id for nodes max_depth = 0 for folder in folders : if folder != "." : folder = re . sub ( "^[.]/" , "" , folder ) path_components = folder . split ( path_delim ) for p in range ( len ( path_component...
def create_expansions ( self , environment_id , collection_id , expansions , ** kwargs ) : """Create or update expansion list . Create or replace the Expansion list for this collection . The maximum number of expanded terms per collection is ` 500 ` . The current expansion list is replaced with the uploaded c...
if environment_id is None : raise ValueError ( 'environment_id must be provided' ) if collection_id is None : raise ValueError ( 'collection_id must be provided' ) if expansions is None : raise ValueError ( 'expansions must be provided' ) expansions = [ self . _convert_model ( x , Expansion ) for x in expan...
async def set_chat_sticker_set ( self , chat_id : typing . Union [ base . Integer , base . String ] , sticker_set_name : base . String ) -> base . Boolean : """Use this method to set a new group sticker set for a supergroup . The bot must be an administrator in the chat for this to work and must have the appropri...
payload = generate_payload ( ** locals ( ) ) result = await self . request ( api . Methods . SET_CHAT_STICKER_SET , payload ) return result
def is_info_germline ( rec ) : """Check if a variant record is germline based on INFO attributes . Works with VarDict ' s annotation of STATUS ."""
if hasattr ( rec , "INFO" ) : status = rec . INFO . get ( "STATUS" , "" ) . lower ( ) else : status = rec . info . get ( "STATUS" , "" ) . lower ( ) return status == "germline" or status . find ( "loh" ) >= 0
def populate_unpaired_line ( d_vals , f_f_header , missing_val = None ) : """used when a value in d _ vals doesn ' t match anything in the other file . : return : a dictionary , indexed by key value , with the correct missing values populated for the other file ."""
if missing_val is None : raise MissingValueError ( "Need missing value to output " + " unpaired lines" ) if f_f_header is not None : f_f_flds = [ dict ( zip ( f_f_header , [ missing_val ] * len ( f_f_header ) ) ) ] else : assert ( len ( d_vals ) > 0 ) f_f_num_cols = len ( d_vals [ d_vals . keys ( ) [ 0 ...
def apply_rule ( self , pattern , replacement , recursive = True ) : """Apply a single rules to the expression This is equivalent to : meth : ` apply _ rules ` with ` ` rules = [ ( pattern , replacement ) ] ` ` Args : pattern ( . Pattern ) : A pattern containing one or more wildcards replacement ( callabl...
return self . apply_rules ( [ ( pattern , replacement ) ] , recursive = recursive )
def clear_provider_links ( self ) : """Removes the provider chain . raise : NoAccess - ` ` Metadata . isRequired ( ) ` ` is ` ` true ` ` or ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` ` * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . learning . ActivityForm . clear _ assets _ template if ( self . get_provider_links_metadata ( ) . is_read_only ( ) or self . get_provider_links_metadata ( ) . is_required ( ) ) : raise errors . NoAccess ( ) self . _my_map [ 'providerLinkIds' ] = self . _provider_links_default
def total_deformation ( u , v , dx , dy ) : r"""Calculate the horizontal total deformation of the horizontal wind . Parameters u : ( M , N ) ndarray x component of the wind v : ( M , N ) ndarray y component of the wind dx : float or ndarray The grid spacing ( s ) in the x - direction . If an array , t...
dudy , dudx = gradient ( u , deltas = ( dy , dx ) , axes = ( - 2 , - 1 ) ) dvdy , dvdx = gradient ( v , deltas = ( dy , dx ) , axes = ( - 2 , - 1 ) ) return np . sqrt ( ( dvdx + dudy ) ** 2 + ( dudx - dvdy ) ** 2 )
def check_mailfy ( self , query , kwargs = { } ) : """Verifying a mailfy query in this platform . This might be redefined in any class inheriting from Platform . The only condition is that any of this should return a dictionary as defined . Args : query : The element to be searched . kwargs : Dictionary w...
import requests s = requests . Session ( ) # Getting the first response to grab the csrf _ token r1 = s . get ( 'https://www.infojobs.net' ) # Launching the query to Instagram r2 = s . post ( 'https://www.infojobs.net/candidate/profile/check-email-registered.xhtml' , data = { "email" : query } , ) if '{"email_is_secure...