signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def run ( self , endpoint : str , loop : AbstractEventLoop = None ) : """Run server main task . : param endpoint : Socket endpoint to listen to , e . g . " tcp : / / * : 1234" : param loop : Event loop to run server in ( alternatively just use run _ async method )"""
if not loop : loop = asyncio . get_event_loop ( ) try : loop . run_until_complete ( self . run_async ( endpoint ) ) except KeyboardInterrupt : self . _shutdown ( )
def _get_paths_for_status ( self , status ) : """Returns sorted list of paths for given ` ` status ` ` . : param status : one of : * added * , * modified * or * deleted *"""
added , modified , deleted = self . _changes_cache return sorted ( { 'added' : list ( added ) , 'modified' : list ( modified ) , 'deleted' : list ( deleted ) } [ status ] )
def _aix_iqn ( ) : '''Return iSCSI IQN from an AIX host .'''
ret = [ ] aix_cmd = 'lsattr -E -l iscsi0 | grep initiator_name' aix_ret = salt . modules . cmdmod . run ( aix_cmd ) if aix_ret [ 0 ] . isalpha ( ) : try : ret . append ( aix_ret . split ( ) [ 1 ] . rstrip ( ) ) except IndexError : pass return ret
def conf ( self ) : '''Configuration ( namedtuple )'''
conf = namedtuple ( 'conf' , field_names = self . _conf . keys ( ) ) return conf ( ** self . _conf )
def close ( self ) : """Close SummaryWriter . Final !"""
if not self . _closed : self . _event_writer . close ( ) self . _closed = True del self . _event_writer
def _load_libcrypto ( ) : '''Load OpenSSL libcrypto'''
if sys . platform . startswith ( 'win' ) : # cdll . LoadLibrary on windows requires an ' str ' argument return cdll . LoadLibrary ( str ( 'libeay32' ) ) # future lint : disable = blacklisted - function elif getattr ( sys , 'frozen' , False ) and salt . utils . platform . is_smartos ( ) : return cdll . LoadL...
def get_kwargs ( self , form , name ) : """Return the keyword arguments that are used to instantiate the formset ."""
kwargs = { 'prefix' : self . get_prefix ( form , name ) , 'initial' : self . get_initial ( form , name ) , } kwargs . update ( self . default_kwargs ) return kwargs
def transpose ( self , name = None ) : """Returns matching ` Conv1D ` module . Args : name : Optional string assigning name of transpose module . The default name is constructed by appending " _ transpose " to ` self . name ` . Returns : ` Conv1D ` module ."""
if name is None : name = self . module_name + "_transpose" if self . _data_format == DATA_FORMAT_NWC : stride = self . _stride [ 1 : - 1 ] else : # self . _ data _ format = = DATA _ FORMAT _ NCW stride = self . _stride [ 2 : ] return Conv1D ( output_channels = lambda : self . input_channels , kernel_shape =...
def count ( self ) : '''A count based on ` count _ field ` and ` format _ args ` .'''
args = self . format_args if args is None or ( isinstance ( args , dict ) and self . count_field not in args ) : raise TypeError ( "count is required" ) return args [ self . count_field ] if isinstance ( args , dict ) else args
def block ( self , mcs ) : """Block a ( previously computed ) MCS . The MCS should be given as an iterable of integers . Note that this method is not automatically invoked from : func : ` enumerate ` because a user may want to block some of the MCSes conditionally depending on the needs . For example , one ...
self . oracle . add_clause ( [ self . sels [ cl_id - 1 ] for cl_id in mcs ] )
def title ( self ) : """Banana banana"""
resolved_title = Link . resolving_title_signal ( self ) resolved_title = [ elem for elem in resolved_title if elem is not None ] if resolved_title : return str ( resolved_title [ 0 ] ) return self . _title
def get_neighborhood_at_voxel ( image , center , kernel , physical_coordinates = False ) : """Get a hypercube neighborhood at a voxel . Get the values in a local neighborhood of an image . ANTsR function : ` getNeighborhoodAtVoxel ` Arguments image : ANTsImage image to get values from . center : tuple /...
if not isinstance ( image , iio . ANTsImage ) : raise ValueError ( 'image must be ANTsImage type' ) if ( not isinstance ( center , ( tuple , list ) ) ) or ( len ( center ) != image . dimension ) : raise ValueError ( 'center must be tuple or list with length == image.dimension' ) if ( not isinstance ( kernel , (...
def create_subscriptions ( config , profile_name ) : '''Adds supported subscriptions'''
if 'kinesis' in config . subscription . keys ( ) : data = config . subscription [ 'kinesis' ] function_name = config . name stream_name = data [ 'stream' ] batch_size = data [ 'batch_size' ] starting_position = data [ 'starting_position' ] starting_position_ts = None if starting_position == ...
def sinh ( x , context = None ) : """Return the hyperbolic sine of x ."""
return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_sinh , ( BigFloat . _implicit_convert ( x ) , ) , context , )
def get_field_descriptor ( self , class_name , field_name , descriptor ) : """Return the specific field : param class _ name : the class name of the field : type class _ name : string : param field _ name : the name of the field : type field _ name : string : param descriptor : the descriptor of the field...
key = class_name + field_name + descriptor if self . __cache_fields is None : self . __cache_fields = { } for i in self . get_classes ( ) : for j in i . get_fields ( ) : self . __cache_fields [ j . get_class_name ( ) + j . get_name ( ) + j . get_descriptor ( ) ] = j return self . __cache_fie...
def registry_ont_id ( self , ont_id : str , ctrl_acct : Account , payer : Account , gas_limit : int , gas_price : int ) : """This interface is used to send a Transaction object which is used to registry ontid . : param ont _ id : OntId . : param ctrl _ acct : an Account object which indicate who will sign for t...
if not isinstance ( ctrl_acct , Account ) or not isinstance ( payer , Account ) : raise SDKException ( ErrorCode . require_acct_params ) b58_payer_address = payer . get_address_base58 ( ) bytes_ctrl_pub_key = ctrl_acct . get_public_key_bytes ( ) tx = self . new_registry_ont_id_transaction ( ont_id , bytes_ctrl_pub_...
def make ( parser ) : """Gather authentication keys for provisioning new nodes ."""
parser . add_argument ( 'mon' , metavar = 'HOST' , nargs = '+' , help = 'monitor host to pull keys from' , ) parser . set_defaults ( func = gatherkeys , )
def _to_dict ( self ) : """Internal method that serializes object into a dictionary ."""
data = { 'name' : self . name , 'referenceId' : self . reference_id , 'shortDescription' : self . short_description , 'playlistType' : self . type , 'id' : self . id } if self . videos : for video in self . videos : if video . id not in self . video_ids : self . video_ids . append ( video . id )...
def get_local ( self , variable_name ) : '''Return the value of the local variable . Raises UnknownVariable is the name is not known .'''
if variable_name not in self . _locals : raise UnknownVariable ( 'Unknown variable %s' % variable_name ) return self . _locals [ variable_name ]
def save_cache ( data , filename ) : """Save cookies to a file ."""
with open ( filename , 'wb' ) as handle : pickle . dump ( data , handle )
def relabel ( self , label = None , group = None , depth = 1 ) : """Clone object and apply new group and / or label . Applies relabeling to children up to the supplied depth . Args : label ( str , optional ) : New label to apply to returned object group ( str , optional ) : New group to apply to returned ob...
return super ( HoloMap , self ) . relabel ( label = label , group = group , depth = depth )
def plot_fiber_slice ( self , plane = None , index = None , fig = None ) : r"""Plot one slice from the fiber image Parameters plane : array _ like List of 3 values , [ x , y , z ] , 2 must be zero and the other must be between zero and one representing the fraction of the domain to slice along the non - z...
if hasattr ( self , '_fiber_image' ) is False : logger . warning ( 'This method only works when a fiber image exists' ) return slice_image = self . _get_fiber_slice ( plane , index ) if slice_image is not None : if fig is None : plt . figure ( ) plt . imshow ( slice_image . T , cmap = 'Greys' , ...
def flatten_spec ( spec , prefix , joiner = " :: " ) : """Flatten a canonical specification with nesting into one without nesting . When building unique names , concatenate the given prefix to the local test name without the " Test " tag ."""
if any ( filter ( operator . methodcaller ( "startswith" , "Test" ) , spec . keys ( ) ) ) : flat_spec = { } for ( k , v ) in spec . items ( ) : flat_spec . update ( flatten_spec ( v , prefix + joiner + k [ 5 : ] ) ) return flat_spec else : return { "Test " + prefix : spec }
def validate_offset ( reference_event , estimated_event , t_collar = 0.200 , percentage_of_length = 0.5 ) : """Validate estimated event based on event offset Parameters reference _ event : dict Reference event . estimated _ event : dict Estimated event . t _ collar : float > 0 , seconds First conditio...
# Detect field naming style used and validate onset if 'event_offset' in reference_event and 'event_offset' in estimated_event : annotated_length = reference_event [ 'event_offset' ] - reference_event [ 'event_onset' ] return math . fabs ( reference_event [ 'event_offset' ] - estimated_event [ 'event_offset' ] ...
def break_args_options ( line ) : # type : ( Text ) - > Tuple [ str , Text ] """Break up the line into an args and options string . We only want to shlex ( and then optparse ) the options , not the args . args can contain markers which are corrupted by shlex ."""
tokens = line . split ( ' ' ) args = [ ] options = tokens [ : ] for token in tokens : if token . startswith ( '-' ) or token . startswith ( '--' ) : break else : args . append ( token ) options . pop ( 0 ) return ' ' . join ( args ) , ' ' . join ( options )
def get_port_channel_detail_output_lacp_aggr_member_rbridge_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_port_channel_detail = ET . Element ( "get_port_channel_detail" ) config = get_port_channel_detail output = ET . SubElement ( get_port_channel_detail , "output" ) lacp = ET . SubElement ( output , "lacp" ) aggr_member = ET . SubElement ( lacp , "aggr-member" ) rbridge_id = ET . Sub...
def get ( self , ns , label = None ) : """Return : class : ` tags instances < ~ Tag > ` for the namespace ` ns ` , ordered by label . If ` label ` is not None the only one instance may be returned , or ` None ` if no tags exists for this label ."""
query = Tag . query . filter ( Tag . ns == ns ) if label is not None : return query . filter ( Tag . label == label ) . first ( ) return query . all ( )
def relabel ( self , qubits : Qubits ) -> 'Density' : """Return a copy of this state with new qubits"""
return Density ( self . vec . tensor , qubits , self . _memory )
def posthoc_nemenyi ( a , val_col = None , group_col = None , dist = 'chi' , sort = True ) : '''Post hoc pairwise test for multiple comparisons of mean rank sums ( Nemenyi ' s test ) . May be used after Kruskal - Wallis one - way analysis of variance by ranks to do pairwise comparisons [ 1 ] _ . Parameters ...
def compare_stats_chi ( i , j ) : diff = np . abs ( x_ranks_avg . loc [ i ] - x_ranks_avg . loc [ j ] ) A = n * ( n + 1. ) / 12. B = ( 1. / x_lens . loc [ i ] + 1. / x_lens . loc [ j ] ) chi = diff ** 2. / ( A * B ) return chi def compare_stats_tukey ( i , j ) : diff = np . abs ( x_ranks_avg . l...
def apply ( self , styles = None , verbose = False ) : """Applies the specified style to the selected views and returns the SUIDs of the affected views . : param styles ( string ) : Name of Style to be applied to the selected views . = [ ' Directed ' , ' BioPAX _ SIF ' , ' Bridging Reads Histogram : unique _ ...
PARAMS = set_param ( [ "styles" ] , [ styles ] ) response = api ( url = self . __url + "/apply" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
def change_score_for ( self , member , delta , member_data = None ) : '''Change the score for a member in the leaderboard by a score delta which can be positive or negative . @ param member [ String ] Member name . @ param delta [ float ] Score change . @ param member _ data [ String ] Optional member data .'...
self . change_score_for_member_in ( self . leaderboard_name , member , delta , member_data )
def create_sequence_rule ( self , sequence_rule_form ) : """Creates a new ` ` SequenceRule ` ` . arg : sequence _ rule _ form ( osid . assessment . authoring . SequenceRuleForm ) : the form for this ` ` SequenceRule ` ` return : ( osid . assessment . authoring . SequenceRule ) - the new ` ` SequenceRule `...
# Implemented from template for # osid . resource . ResourceAdminSession . create _ resource _ template collection = JSONClientValidated ( 'assessment_authoring' , collection = 'SequenceRule' , runtime = self . _runtime ) if not isinstance ( sequence_rule_form , ABCSequenceRuleForm ) : raise errors . InvalidArgumen...
def compute_acl ( cls , filename , start_index = None , end_index = None , min_nsamples = 10 ) : """Computes the autocorrleation length for all model params and temperatures in the given file . Parameter values are averaged over all walkers at each iteration and temperature . The ACL is then calculated over t...
acls = { } with cls . _io ( filename , 'r' ) as fp : if end_index is None : end_index = fp . niterations tidx = numpy . arange ( fp . ntemps ) for param in fp . variable_params : these_acls = numpy . zeros ( fp . ntemps ) for tk in tidx : samples = fp . read_raw_samples (...
def url_quote ( url ) : """Ensure url is valid"""
try : return quote ( url , safe = URL_SAFE ) except KeyError : return quote ( encode ( url ) , safe = URL_SAFE )
def view_isometric ( self ) : """Resets the camera to a default isometric view showing all the actors in the scene ."""
self . camera_position = self . get_default_cam_pos ( ) self . camera_set = False return self . reset_camera ( )
def _convert_slice_incement_inconsistencies ( dicom_input ) : """If there is slice increment inconsistency detected , for the moment CT images , then split the volumes into subvolumes based on the slice increment and process each volume separately using a space constructed based on the highest resolution increment"...
# Estimate the " first " slice increment based on the 2 first slices increment = numpy . array ( dicom_input [ 0 ] . ImagePositionPatient ) - numpy . array ( dicom_input [ 1 ] . ImagePositionPatient ) # Create as many volumes as many changes in slice increment . NB Increments might be repeated in different volumes max_...
def to_hdf5 ( input ) : """Convert . xml and . npz files to . hdf5 files ."""
with performance . Monitor ( 'to_hdf5' ) as mon : for input_file in input : if input_file . endswith ( '.npz' ) : output = convert_npz_hdf5 ( input_file , input_file [ : - 3 ] + 'hdf5' ) elif input_file . endswith ( '.xml' ) : # for source model files output = convert_xml_hdf...
def add_letter_to_axis ( ax , let , col , x , y , height ) : """Add ' let ' with position x , y and height height to matplotlib axis ' ax ' ."""
if len ( let ) == 2 : colors = [ col , "white" ] elif len ( let ) == 1 : colors = [ col ] else : raise ValueError ( "3 or more Polygons are not supported" ) for polygon , color in zip ( let , colors ) : new_polygon = affinity . scale ( polygon , yfact = height , origin = ( 0 , 0 , 0 ) ) new_polygon ...
def loads ( schema_str ) : """Parse a schema given a schema string"""
try : if sys . version_info [ 0 ] < 3 : return schema . parse ( schema_str ) else : return schema . Parse ( schema_str ) except schema . SchemaParseException as e : raise ClientError ( "Schema parse failed: %s" % ( str ( e ) ) )
def nav_controller_output_encode ( self , nav_roll , nav_pitch , nav_bearing , target_bearing , wp_dist , alt_error , aspd_error , xtrack_error ) : '''The state of the fixed wing navigation and position controller . nav _ roll : Current desired roll in degrees ( float ) nav _ pitch : Current desired pitch in de...
return MAVLink_nav_controller_output_message ( nav_roll , nav_pitch , nav_bearing , target_bearing , wp_dist , alt_error , aspd_error , xtrack_error )
def show ( ) : """Shows the URL of the current cloud server or throws an error if no cloud server is selected"""
utils . check_for_cloud_server ( ) click . echo ( "Using cloud server at \"{}\"" . format ( config [ "cloud_server" ] [ "url" ] ) ) if config [ "cloud_server" ] [ "username" ] : click . echo ( "Logged in as user \"{}\"" . format ( config [ "cloud_server" ] [ "username" ] ) ) if config [ "cloud_server" ] [ "farm_nam...
def leave_multicast ( self , universe : int ) -> None : """Try to leave the multicast group with the specified universe . This does not throw any exception if the group could not be leaved . : param universe : the universe to leave the multicast group . The network hardware has to support the multicast featur...
try : self . sock . setsockopt ( socket . SOL_IP , socket . IP_DROP_MEMBERSHIP , socket . inet_aton ( calculate_multicast_addr ( universe ) ) + socket . inet_aton ( self . _bindAddress ) ) except : # try to leave the multicast group for the universe pass
def add_debug ( parser ) : """Add a ` debug ` flag to the _ parser _ ."""
parser . add_argument ( '-d' , '--debug' , action = 'store_const' , const = logging . DEBUG , default = logging . INFO , help = 'Set DEBUG output' )
def areIndicesValid ( self , inds ) : """Test if indices are valid @ param inds index set @ return True if valid , False otherwise"""
return reduce ( operator . and_ , [ 0 <= inds [ d ] < self . dims [ d ] for d in range ( self . ndims ) ] , True )
def serve ( request , tail , server ) : """Django adapter . It has three arguments : # . ` ` request ` ` is a Django request object , # . ` ` tail ` ` is everything that ' s left from an URL , which adapter is attached to , # . ` ` server ` ` is a pyws server object . First two are the context of an appli...
if request . GET : body = '' else : try : body = request . body except AttributeError : body = request . raw_post_data request = Request ( tail , body , parse_qs ( request . META [ 'QUERY_STRING' ] ) , parse_qs ( body ) , request . COOKIES , ) response = server . process_request ( request ) ...
def _apply_weighting ( F , loss , weight = None , sample_weight = None ) : """Apply weighting to loss . Parameters loss : Symbol The loss to be weighted . weight : float or None Global scalar weight for loss . sample _ weight : Symbol or None Per sample weighting . Must be broadcastable to the same ...
if sample_weight is not None : loss = F . broadcast_mul ( loss , sample_weight ) if weight is not None : assert isinstance ( weight , numeric_types ) , "weight must be a number" loss = loss * weight return loss
def from_bid ( cls , value ) : """Create an instance of : class : ` Decimal128 ` from Binary Integer Decimal string . : Parameters : - ` value ` : 16 byte string ( 128 - bit IEEE 754-2008 decimal floating point in Binary Integer Decimal ( BID ) format ) ."""
if not isinstance ( value , bytes ) : raise TypeError ( "value must be an instance of bytes" ) if len ( value ) != 16 : raise ValueError ( "value must be exactly 16 bytes" ) return cls ( ( _UNPACK_64 ( value [ 8 : ] ) [ 0 ] , _UNPACK_64 ( value [ : 8 ] ) [ 0 ] ) )
def complement ( self , alphabet ) : """Returns the complement of DFA Args : alphabet ( list ) : The input alphabet Returns : None"""
self . _addsink ( alphabet ) for state in self . automaton . states ( ) : if self . automaton . final ( state ) == fst . Weight . One ( self . automaton . weight_type ( ) ) : self . automaton . set_final ( state , fst . Weight . Zero ( self . automaton . weight_type ( ) ) ) else : self . automat...
def find_files_cmd ( data_path , minutes , start_time , end_time ) : """Find the log files depending on their modification time . : param data _ path : the path to the Kafka data directory : type data _ path : str : param minutes : check the files modified in the last N minutes : type minutes : int : para...
if minutes : return FIND_MINUTES_COMMAND . format ( data_path = data_path , minutes = minutes , ) if start_time : if end_time : return FIND_RANGE_COMMAND . format ( data_path = data_path , start_time = start_time , end_time = end_time , ) else : return FIND_START_COMMAND . format ( data_path...
def bonus ( self , participant ) : """Calculate a participants bonus ."""
scores = [ n . score for n in participant . nodes ( ) if n . network . role == "experiment" ] average = float ( sum ( scores ) ) / float ( len ( scores ) ) bonus = round ( max ( 0.0 , ( ( average - 0.5 ) * 2 ) ) * self . bonus_payment , 2 ) return bonus
def get_customer_transitions ( self , issue_id_or_key ) : """Returns a list of transitions that customers can perform on the request : param issue _ id _ or _ key : str : return :"""
url = 'rest/servicedeskapi/request/{}/transition' . format ( issue_id_or_key ) return self . get ( url , headers = self . experimental_headers )
def _exec_loop ( self , a , bd_all , mask ) : """Solves the kriging system by looping over all specified points . Less memory - intensive , but involves a Python - level loop ."""
npt = bd_all . shape [ 0 ] n = self . X_ADJUSTED . shape [ 0 ] kvalues = np . zeros ( npt ) sigmasq = np . zeros ( npt ) a_inv = scipy . linalg . inv ( a ) for j in np . nonzero ( ~ mask ) [ 0 ] : # Note that this is the same thing as range ( npt ) if mask is not defined , bd = bd_all [ j ] # otherwise it takes...
def discands ( record ) : """Display the candidates contained in a candidate record list"""
import pyraf , pyfits pyraf . iraf . tv ( ) display = pyraf . iraf . tv . display width = 128 cands = record [ 'cands' ] exps = record [ 'fileId' ] # # # load some header info from the mophead file headers = { } for exp in exps : f = pyfits . open ( exp + ".fits" ) headers [ exp ] = { } for key in [ 'MJDATE...
def renderXRDS ( request , type_uris , endpoint_urls ) : """Render an XRDS page with the specified type URIs and endpoint URLs in one service block , and return a response with the appropriate content - type ."""
response = direct_to_template ( request , 'xrds.xml' , { 'type_uris' : type_uris , 'endpoint_urls' : endpoint_urls , } ) response [ 'Content-Type' ] = YADIS_CONTENT_TYPE return response
def add_table_item ( self , table ) : """Adds a Table to the publish group ."""
if not table . is_draft_version : raise ValueError ( "Table isn't a draft version" ) self . items . append ( table . latest_version )
def fix_e305 ( self , result ) : """Add missing 2 blank lines after end of function or class ."""
cr = '\n' # check comment line offset = result [ 'line' ] - 2 while True : if offset < 0 : break line = self . source [ offset ] . lstrip ( ) if len ( line ) == 0 : break if line [ 0 ] != '#' : break offset -= 1 offset += 1 self . source [ offset ] = cr + self . source [ offs...
def igmp_snooping_ip_pim_snooping_pimv4_enable ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) igmp_snooping = ET . SubElement ( config , "igmp-snooping" , xmlns = "urn:brocade.com:mgmt:brocade-igmp-snooping" ) ip = ET . SubElement ( igmp_snooping , "ip" ) pim = ET . SubElement ( ip , "pim" ) snooping = ET . SubElement ( pim , "snooping" ) pimv4_enable = ET . SubElement ( snoop...
def cmd_reindex ( ) : """Uses CREATE INDEX CONCURRENTLY to create a duplicate index , then tries to swap the new index for the original . The index swap is done using a short lock timeout to prevent it from interfering with running queries . Retries until the rename succeeds ."""
db = connect ( args . database ) for idx in args . indexes : pg_reindex ( db , idx )
def _JzIntegrand ( z , Ez , pot ) : """The J _ z integrand"""
return nu . sqrt ( 2. * ( Ez - potentialVertical ( z , pot ) ) )
def stringify ( data ) : """Turns all dictionary values into strings"""
if isinstance ( data , dict ) : for key , value in data . items ( ) : data [ key ] = stringify ( value ) elif isinstance ( data , list ) : return [ stringify ( item ) for item in data ] else : return smart_text ( data ) return data
def bad_solution_count ( self , * args , ** kwargs ) : "Return a count of how many : class : ` TxIn ` objects are not correctly solved ."
return sum ( 0 if self . is_solution_ok ( idx , * args , ** kwargs ) else 1 for idx in range ( len ( self . txs_in ) ) )
def contains_angle_degrees ( self , angle ) : '''Returns true , if a point with the corresponding angle ( given in degrees ) is within the arc . Does no tolerance checks ( i . e . if the arc is of length 0 , you must provide angle = = from _ angle = = to _ angle to get a positive answer here ) > > > a = Arc ( (...
_d = self . sign * ( angle - self . from_angle ) % 360.0 return ( _d <= self . length_degrees ( ) )
def post ( self , endpoint : str , ** kwargs ) -> dict : """HTTP POST operation to API endpoint ."""
return self . _request ( 'POST' , endpoint , ** kwargs )
def which ( program ) : """Find a program in PATH and return path From : http : / / stackoverflow . com / q / 377017/"""
def is_exe ( fpath ) : found = os . path . isfile ( fpath ) and os . access ( fpath , os . X_OK ) if not found and sys . platform == 'win32' : fpath = fpath + ".exe" found = os . path . isfile ( fpath ) and os . access ( fpath , os . X_OK ) return found fpath , _ = os . path . split ( progra...
def get_long_description ( ) : """Convert the README file into the long description ."""
with open ( path . join ( root_path , 'README.md' ) , encoding = 'utf-8' ) as f : long_description = f . read ( ) return long_description
def adjoint ( self ) : """Return the adjoint operator . The laplacian is self - adjoint , so this returns ` ` self ` ` ."""
return Laplacian ( self . range , self . domain , pad_mode = self . pad_mode , pad_const = 0 )
def __convert_string_list ( node ) : """Converts a StringListProperty node to JSON format ."""
converted = __convert_node ( node ) # Determine flags for the string list flags = vsflags ( VSFlags . UserValue ) # Check for a separator to determine if it is semicolon appendable # If not present assume the value should be ; separator = __get_attribute ( node , 'Separator' , default_value = ';' ) if separator == ';' ...
def save_partial ( self , data = None , allow_protected_fields = False , ** kwargs ) : """Saves just the currently set fields in the database ."""
# Backwards compat , deprecated argument if "dotnotation" in kwargs : del kwargs [ "dotnotation" ] if data is None : data = dotdict ( self ) if "_id" not in data : raise KeyError ( "_id must be set in order to do a save_partial()" ) del data [ "_id" ] if len ( data ) == 0 : return if not all...
def print_stats ( self , header = True , file = sys . stdout ) : """Pretty print stats table ."""
if header : print ( "CACHE {:*^18} {:*^18} {:*^18} {:*^18} {:*^18}" . format ( "HIT" , "MISS" , "LOAD" , "STORE" , "EVICT" ) , file = file ) for s in self . stats ( ) : print ( "{name:>5} {HIT_count:>6} ({HIT_byte:>8}B) {MISS_count:>6} ({MISS_byte:>8}B) " "{LOAD_count:>6} ({LOAD_byte:>8}B) {STORE_count:>6} " "(...
def mutate_rows ( self , rows , retry = DEFAULT_RETRY ) : """Mutates multiple rows in bulk . For example : . . literalinclude : : snippets _ table . py : start - after : [ START bigtable _ mutate _ rows ] : end - before : [ END bigtable _ mutate _ rows ] The method tries to update all specified rows . I...
retryable_mutate_rows = _RetryableMutateRowsWorker ( self . _instance . _client , self . name , rows , app_profile_id = self . _app_profile_id , timeout = self . mutation_timeout , ) return retryable_mutate_rows ( retry = retry )
def confidence_interval_survival_function_ ( self ) : """The confidence interval of the survival function ."""
return self . _compute_confidence_bounds_of_transform ( self . _survival_function , self . alpha , self . _ci_labels )
def unpack_layer ( plane ) : """Return a correctly shaped numpy array given the feature layer bytes ."""
size = point . Point . build ( plane . size ) if size == ( 0 , 0 ) : # New layer that isn ' t implemented in this SC2 version . return None data = np . frombuffer ( plane . data , dtype = Feature . dtypes [ plane . bits_per_pixel ] ) if plane . bits_per_pixel == 1 : data = np . unpackbits ( data ) if data ....
def set_phases ( self , literals = [ ] ) : """Sets polarities of a given list of variables ."""
if self . lingeling : pysolvers . lingeling_setphases ( self . lingeling , literals )
def _validate_charm ( url , service_name , add_error ) : """Validate the given charm URL . Use the given service name to describe possible errors . Use the given add _ error callable to register validation error . If the URL is valid , return the corresponding charm reference object . Return None otherwise ...
if url is None : add_error ( 'no charm specified for service {}' . format ( service_name ) ) return None if not isstring ( url ) : add_error ( 'invalid charm specified for service {}: {}' '' . format ( service_name , url ) ) return None if not url . strip ( ) : add_error ( 'empty charm specified for...
def zpk ( self , zeros , poles , gain , analog = True , ** kwargs ) : """Filter this ` TimeSeries ` by applying a zero - pole - gain filter Parameters zeros : ` array - like ` list of zero frequencies ( in Hertz ) poles : ` array - like ` list of pole frequencies ( in Hertz ) gain : ` float ` DC gain ...
return self . filter ( zeros , poles , gain , analog = analog , ** kwargs )
def iterate ( it ) : """Generate values from a sychronous or asynchronous iterable ."""
if is_async_iterable ( it ) : return from_async_iterable . raw ( it ) if isinstance ( it , Iterable ) : return from_iterable . raw ( it ) raise TypeError ( f"{type(it).__name__!r} object is not (async) iterable" )
def retrieve ( self , id ) : """Retrieve a single reason Returns a single loss reason available to the user by the provided id If a loss reason with the supplied unique identifier does not exist , it returns an error : calls : ` ` get / loss _ reasons / { id } ` ` : param int id : Unique identifier of a Los...
_ , _ , loss_reason = self . http_client . get ( "/loss_reasons/{id}" . format ( id = id ) ) return loss_reason
def from_array_list ( required_type , result , list_level , is_builtin ) : """Tries to parse the ` result ` as type given in ` required _ type ` , while traversing into lists as often as specified in ` list _ level ` . : param required _ type : What it should be parsed as : type required _ type : class : para...
logger . debug ( "Trying parsing as {type}, list_level={list_level}, is_builtin={is_builtin}" . format ( type = required_type . __name__ , list_level = list_level , is_builtin = is_builtin ) ) if list_level > 0 : assert isinstance ( result , ( list , tuple ) ) return [ from_array_list ( required_type , obj , li...
def loadtxt_str ( path : PathOrStr ) -> np . ndarray : "Return ` ndarray ` of ` str ` of lines of text from ` path ` ."
with open ( path , 'r' ) as f : lines = f . readlines ( ) return np . array ( [ l . strip ( ) for l in lines ] )
def get_epoch_price_multiplier ( block_height , namespace_id , units ) : """what ' s the name price multiplier for this epoch ? Not all epochs have one - - - if this epoch has BLOCKSTACK _ INT _ DIVISION set , use get _ epoch _ price _ divisor ( ) instead ."""
try : assert units in [ TOKEN_TYPE_STACKS , 'BTC' ] , 'Unknown units {}' . format ( units ) except AssertionError as ae : log . exception ( ae ) log . error ( "FATAL: No such units {}" . format ( units ) ) os . abort ( ) multiplier = 'PRICE_MULTIPLIER' if units == 'BTC' else 'PRICE_MULTIPLIER_STACKS' ep...
def get_location ( self , place ) : """Return a dict with the coordinates * place * . The dict ' s keys are ` ` ' latitude ' ` ` and ` ` ' longitude ' ` ` . If it ' s not present in the collection , ` ` None ` ` will be returned instead ."""
pickled_place = self . _pickle ( place ) try : longitude , latitude = self . redis . geopos ( self . key , pickled_place ) [ 0 ] except ( AttributeError , TypeError ) : return None return { 'latitude' : latitude , 'longitude' : longitude }
def basic_cancel ( self , consumer_tag , nowait = False ) : """End a queue consumer This method cancels a consumer . This does not affect already delivered messages , but it does mean the server will not send any more messages for that consumer . The client may receive an abitrary number of messages in betw...
if self . connection is not None : self . no_ack_consumers . discard ( consumer_tag ) args = AMQPWriter ( ) args . write_shortstr ( consumer_tag ) args . write_bit ( nowait ) self . _send_method ( ( 60 , 30 ) , args ) return self . wait ( allowed_methods = [ ( 60 , 31 ) , # Channel . basic _ can...
def load_shellcode ( shellcode , arch , start_offset = 0 , load_address = 0 ) : """Load a new project based on a string of raw bytecode . : param shellcode : The data to load : param arch : The name of the arch to use , or an archinfo class : param start _ offset : The offset into the data to start analysis (...
return Project ( BytesIO ( shellcode ) , main_opts = { 'backend' : 'blob' , 'arch' : arch , 'entry_point' : start_offset , 'base_addr' : load_address , } )
def _start_connect ( self , connect_type ) : """Starts the connection process , as called ( internally ) from the user context , either from auto _ connect ( ) or connect ( ) . Never call this from the _ comm ( ) process context ."""
if self . _connect_state . value != self . CS_NOT_CONNECTED : # already done or in process , assume success return self . _connected . value = 0 self . _connect_state . value = self . CS_ATTEMPTING_CONNECT # tell comm process to attempt connection self . _attempting_connect . value = connect_type # EXTREMELY IMPORT...
def subgraph ( self , nodes ) : """Return the subgraph consisting of the given nodes and edges between thses nodes . Parameters nodes : array _ like ( int , ndim = 1) Array of node indices . Returns DiGraph A DiGraph representing the subgraph ."""
adj_matrix = self . csgraph [ np . ix_ ( nodes , nodes ) ] weighted = True # To copy the dtype if self . node_labels is not None : node_labels = self . node_labels [ nodes ] else : node_labels = None return DiGraph ( adj_matrix , weighted = weighted , node_labels = node_labels )
def evaluate_mask ( matrix , matrix_size ) : """Evaluates the provided ` matrix ` of a QR code . ISO / IEC 18004:2015 ( E ) - - 7.8.3 Evaluation of data masking results ( page 53) : param matrix : The matrix to evaluate : param matrix _ size : The width ( or height ) of the matrix . : return int : The penal...
return score_n1 ( matrix , matrix_size ) + score_n2 ( matrix , matrix_size ) + score_n3 ( matrix , matrix_size ) + score_n4 ( matrix , matrix_size )
def _add_cli_args ( self ) : """Add the cli arguments to the argument parser ."""
# Optional cli arguments self . _arg_parser . add_argument ( '-l' , '--list' , action = 'store_true' , help = 'List installed sprockets apps' ) self . _arg_parser . add_argument ( '-s' , '--syslog' , action = 'store_true' , help = 'Log to syslog' ) self . _arg_parser . add_argument ( '-v' , '--verbose' , action = 'coun...
def by_col ( cls , df , x , y = None , w = None , inplace = False , pvalue = 'sim' , outvals = None , ** stat_kws ) : """Function to compute a Moran _ BV statistic on a dataframe Arguments df : pandas . DataFrame a pandas dataframe with a geometry column X : list of strings column name or list of column n...
return _bivariate_handler ( df , x , y = y , w = w , inplace = inplace , pvalue = pvalue , outvals = outvals , swapname = cls . __name__ . lower ( ) , stat = cls , ** stat_kws )
def interm_fluent_variables ( self ) -> FluentParamsList : '''Returns the instantiated intermediate fluents in canonical order . Returns : Sequence [ Tuple [ str , List [ str ] ] ] : A tuple of pairs of fluent name and a list of instantiated fluents represented as strings .'''
fluents = self . domain . intermediate_fluents ordering = self . domain . interm_fluent_ordering return self . _fluent_params ( fluents , ordering )
def get_dependency_graph ( component ) : """Generate a component ' s graph of dependencies , which can be passed to : func : ` run ` or : func : ` run _ incremental ` ."""
if component not in DEPENDENCIES : raise Exception ( "%s is not a registered component." % get_name ( component ) ) if not DEPENDENCIES [ component ] : return { component : set ( ) } graph = defaultdict ( set ) def visitor ( c , parent ) : if parent is not None : graph [ parent ] . add ( c ) walk_de...
def run ( self ) : """run the plugin"""
if self . workflow . builder . base_from_scratch and not self . workflow . builder . parent_images : self . log . info ( "from scratch single stage can't add repos from koji target" ) return target_info = self . xmlrpc . getBuildTarget ( self . target ) if target_info is None : self . log . error ( "provide...
def transfers ( self , ** params ) : """Return a deferred ."""
params [ 'recipient' ] = self . id return Transfer . all ( self . api_key , ** params )
def getCatalogDefinitions ( ) : """Returns a dictionary with catalogs definitions ."""
final = { } analysis_request = bika_catalog_analysisrequest_listing_definition analysis = bika_catalog_analysis_listing_definition autoimportlogs = bika_catalog_autoimportlogs_listing_definition worksheet = bika_catalog_worksheet_listing_definition report = bika_catalog_report_definition # Merging the catalogs final . ...
def view_set ( method_name ) : """Creates a setter that will call the view method with the context ' s key as first parameter and the value as second parameter . @ param method _ name : the name of a method belonging to the view . @ type method _ name : str"""
def view_set ( value , context , ** _params ) : method = getattr ( context [ "view" ] , method_name ) return _set ( method , context [ "key" ] , value , ( ) , { } ) return view_set
def stream ( self ) : """: class : ` Stream ` object for playing"""
# Add song to queue self . _connection . request ( 'addSongsToQueue' , { 'songIDsArtistIDs' : [ { 'artistID' : self . artist . id , 'source' : 'user' , 'songID' : self . id , 'songQueueSongID' : 1 } ] , 'songQueueID' : self . _connection . session . queue } , self . _connection . header ( 'addSongsToQueue' , 'jsqueue' ...
def has_key ( tup , key ) : """has ( tuple , string ) - > bool Return whether a given tuple has a key and the key is bound ."""
if isinstance ( tup , framework . TupleLike ) : return tup . is_bound ( key ) if isinstance ( tup , dict ) : return key in tup if isinstance ( tup , list ) : if not isinstance ( key , int ) : raise ValueError ( 'Key must be integer when checking list index' ) return key < len ( tup ) raise Value...
def fit ( pointlist ) : '''Parameter pointlist [ [ x0 , y0 ] , [ x1 , y1 ] , . . . ]'''
gapless_pointlist = gaze_repair ( pointlist ) src , sacc , tgt , mle = saccade_model_em ( gapless_pointlist ) return { 'source_points' : src , 'saccade_points' : sacc , 'target_points' : tgt , 'mean_squared_error' : mle }
def ConsultarContribuyentes ( self , fecha_desde , fecha_hasta , cuit_contribuyente ) : "Realiza la consulta remota a ARBA , estableciendo los resultados"
self . limpiar ( ) try : self . xml = SimpleXMLElement ( XML_ENTRADA_BASE ) self . xml . fechaDesde = fecha_desde self . xml . fechaHasta = fecha_hasta self . xml . contribuyentes . contribuyente . cuitContribuyente = cuit_contribuyente xml = self . xml . as_xml ( ) self . CodigoHash = md5 . md5...
def find ( path , * args , ** kwargs ) : '''Approximate the Unix ` ` find ( 1 ) ` ` command and return a list of paths that meet the specified criteria . The options include match criteria : . . code - block : : text name = path - glob # case sensitive iname = path - glob # case insensitive regex = path...
if 'delete' in args : kwargs [ 'delete' ] = 'f' elif 'print' in args : kwargs [ 'print' ] = 'path' try : finder = salt . utils . find . Finder ( kwargs ) except ValueError as ex : return 'error: {0}' . format ( ex ) ret = [ item for i in [ finder . find ( p ) for p in glob . glob ( os . path . expanduse...
def scale ( self , s = None ) : """Set / get actor ' s scaling factor . : param s : scaling factor ( s ) . : type s : float , list . . note : : if ` s = = ( sx , sy , sz ) ` scale differently in the three coordinates ."""
if s is None : return np . array ( self . GetScale ( ) ) self . SetScale ( s ) return self