signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def sort_via_radix ( lst ) : """Function to sort a list using radix sort technique . > > > sort _ via _ radix ( [ 15 , 79 , 25 , 68 , 37 ] ) [15 , 25 , 37 , 68 , 79] > > > sort _ via _ radix ( [ 9 , 11 , 8 , 7 , 3 , 2 ] ) [2 , 3 , 7 , 8 , 9 , 11] > > > sort _ via _ radix ( [ 36 , 12 , 24 , 26 , 29 ] ) [...
RADIX = 10 max_digit_val = max ( lst ) exp = 1 while max_digit_val / exp > 0 : buckets = [ [ ] for _ in range ( RADIX ) ] for number in lst : index = int ( ( ( number / exp ) % RADIX ) ) buckets [ index ] . append ( number ) index = 0 for section in range ( RADIX ) : bucket = buc...
def get_mr_filters ( data_shape , opt = '' , coarse = False ) : # pragma : no cover """Get mr _ transform filters This method obtains wavelet filters by calling mr _ transform Parameters data _ shape : tuple 2D data shape opt : list , optional List of additonal mr _ transform options coarse : bool , o...
# Adjust the shape of the input data . data_shape = np . array ( data_shape ) data_shape += data_shape % 2 - 1 # Create fake data . fake_data = np . zeros ( data_shape ) fake_data [ tuple ( zip ( data_shape // 2 ) ) ] = 1 # Call mr _ transform . mr_filters = call_mr_transform ( fake_data , opt = opt ) # Return filters ...
def ciphers ( from_suite = None ) : """This is a helper method that will return all of the cipher strings used in a specified TLSCryptographySuite or returns the system default NIST profile list of ciphers . This can be used as a helper to identify the ciphers to specify / add when creating a new TLSCryptog...
suite = from_suite or TLSCryptographySuite . objects . filter ( 'NIST' ) . first ( ) return suite . data . get ( 'tls_cryptography_suites' )
def assemble_component ( compname , compinfo , hpx_order ) : """Assemble the source map file for one binning component Parameters compname : str The key for this component ( e . g . , E0 _ PSF3) compinfo : dict Information about this component hpx _ order : int Maximum order for maps"""
sys . stdout . write ( "Working on component %s\n" % compname ) ccube = compinfo [ 'ccube' ] outsrcmap = compinfo [ 'outsrcmap' ] source_dict = compinfo [ 'source_dict' ] hpx_order = AssembleModel . copy_ccube ( ccube , outsrcmap , hpx_order ) hdulist = AssembleModel . open_outsrcmap ( outsrcmap ) for comp_name in sort...
def get_elements ( self , tag_name , attribute ) : """Return elements in xml files which match with the tag name and the specific attribute : param tag _ name : a string which specify the tag name : param attribute : a string which specify the attribute"""
l = [ ] for i in self . xml : for item in self . xml [ i ] . getElementsByTagName ( tag_name ) : value = item . getAttributeNS ( NS_ANDROID_URI , attribute ) value = self . format_value ( value ) l . append ( str ( value ) ) return l
def to_sky ( self , wcs , origin = _DEFAULT_WCS_ORIGIN , mode = _DEFAULT_WCS_MODE ) : """Convert this ` PixCoord ` to ` ~ astropy . coordinates . SkyCoord ` . Calls : meth : ` astropy . coordinates . SkyCoord . from _ pixel ` . See parameter description there ."""
return SkyCoord . from_pixel ( xp = self . x , yp = self . y , wcs = wcs , origin = origin , mode = mode , )
def set_data ( self , data ) : """Sets this parameter ' s value on all contexts ."""
self . shape = data . shape if self . _data is None : assert self . _deferred_init , "Parameter '%s' has not been initialized" % self . name self . _deferred_init = self . _deferred_init [ : 3 ] + ( data , ) return # if update _ on _ kvstore , we need to make sure the copy stored in kvstore is in sync if se...
def sample_dropout_mask ( x , dropout_probability = .5 , columns = None , stream = None , target = None , dropout_mask = None , dropout_prob_array = None ) : """Samples a dropout mask and applies it in place"""
assert x . flags . c_contiguous if columns is not None : assert len ( columns ) == 2 x_tmp = x x = extract_columns ( x , columns [ 0 ] , columns [ 1 ] ) shape = x . shape if dropout_prob_array is None : dropout_prob_array = gpuarray . empty ( shape , x . dtype , allocator = memory_pool . allocate ) samp...
def __obj2choices ( self , values ) : """- json list of key , value pairs : Example : [ [ " A " , " Option 1 Label " ] , [ " B " , " Option 2 Label " ] ] - space separated string with a list of options : Example : " Option1 Opt2 Opt3" will be converted to a key , value pair of the following form : ( ( " O...
choices = values # choices from string if type ( values ) == type ( '' ) : obj = None # try json string try : obj = json . loads ( values ) except ValueError : obj = values if type ( obj ) == type ( [ ] ) : choices = obj else : choices = obj . split ( ) return cho...
def formatDropEvent ( event ) : """Formats information from the drop event . : param event | < QtGui . QDropEvent >"""
text = [ ] text . append ( '#------------------------------------------------------' ) text . append ( '# Drop Data ' ) text . append ( '#------------------------------------------------------' ) text . append ( '\taction: {0}' . format ( event . dropAction ( ) ) ) text . append...
def get_filtering_args_from_filterset ( filterset_class , type ) : """Inspect a FilterSet and produce the arguments to pass to a Graphene Field . These arguments will be available to filter against in the GraphQL"""
from . . forms . converter import convert_form_field args = { } for name , filter_field in six . iteritems ( filterset_class . base_filters ) : field_type = convert_form_field ( filter_field . field ) . Argument ( ) field_type . description = filter_field . label args [ name ] = field_type return args
def multireplace ( string , # type : unicode patterns , # type : str _ or _ str _ iterable substitutions , # type : str _ istr _ icallable maxreplace = 0 , # type : int flags = 0 # type : unicode ) : # type : ( . . . ) - > bool """Like unicode . replace ( ) but accept several substitutions and regexes Args : st...
# we can pass either a string or an iterable of strings patterns = ensure_tuple ( patterns ) substitutions = ensure_tuple ( substitutions ) # you can either have : # - many patterns , one substitution # - many patterns , exactly as many substitutions # anything else is an error num_of_subs = len ( substitutions ) num_o...
def clear_knowledge_category ( self ) : """Clears the knowledge category . raise : NoAccess - ` ` Metadata . isRequired ( ) ` ` or ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` ` * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . resource . ResourceForm . clear _ avatar _ template if ( self . get_knowledge_category_metadata ( ) . is_read_only ( ) or self . get_knowledge_category_metadata ( ) . is_required ( ) ) : raise errors . NoAccess ( ) self . _my_map [ 'knowledgeCategoryId' ] = self . _knowledge_c...
def find_files ( directory = "." , ext = None , name = None , match_case = False , disable_glob = False , depth = None , abspath = False , enable_scandir = False ) : """Walk through a file directory and return an iterator of files that match requirements . Will autodetect if name has glob as magic characters . ...
if ext or not name : disable_glob = True if not disable_glob : disable_glob = not glob . has_magic ( name ) if ext and isinstance ( ext , str ) : ext = [ ext ] elif ext and not isinstance ( ext , ( list , tuple ) ) : raise TypeError ( "extension must be either one extension or a list" ) if abspath : ...
def code ( self , value ) : """Set the code of the message . : type value : Codes : param value : the code : raise AttributeError : if value is not a valid code"""
if value not in list ( defines . Codes . LIST . keys ( ) ) and value is not None : raise AttributeError self . _code = value
def get_clean_interp_index ( arr , dim , use_coordinate = True , ** kwargs ) : '''get index to use for x values in interpolation . If use _ coordinate is True , the coordinate that shares the name of the dimension along which interpolation is being performed will be used as the x values . If use _ coordinat...
if use_coordinate : if use_coordinate is True : index = arr . get_index ( dim ) else : index = arr . coords [ use_coordinate ] if index . ndim != 1 : raise ValueError ( 'Coordinates used for interpolation must be 1D, ' '%s is %dD.' % ( use_coordinate , index . ndim ) ) # ...
def iterstraight ( self , raw ) : """Iterator that undoes the effect of filtering Yields each row in serialised format ( as a sequence of bytes ) . Assumes input is straightlaced . ` raw ` should be an iterable that yields the raw bytes in chunks of arbitrary size ."""
# length of row , in bytes ( with filter ) rb_1 = self . row_bytes + 1 a = bytearray ( ) filt = Filter ( self . bitdepth * self . planes ) for some in raw : a . extend ( some ) offset = 0 while len ( a ) >= rb_1 + offset : filter_type = a [ offset ] if filter_type not in ( 0 , 1 , 2 , 3 , 4 ...
def _set_port_security_mac_address ( self , v , load = False ) : """Setter method for port _ security _ mac _ address , mapped from YANG variable / interface / port _ channel / switchport / port _ security / port _ security _ mac _ address ( list ) If this variable is read - only ( config : false ) in the sourc...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "mac_address port_sec_vlan" , port_security_mac_address . port_security_mac_address , yang_name = "port-security-mac-address" , rest_name = "port-security-mac-address" , parent = self , is_container = 'list' , ...
def plot_emg_rms_area ( time , signal , rms , area ) : """Brief With the current function it will be plotted the EMG signals together with RMS line and the time - series that describes the evolution of the cumulative area . Description Function intended to generate a single Bokeh figure graphically describi...
# List that store the figure handler list_figures = [ ] # Plotting of EMG area and RMS line list_figures . append ( figure ( x_axis_label = 'Frequency (Hz)' , y_axis_label = 'Electric Tension (mV)' , x_range = [ 0 , time [ - 1 ] ] , y_range = [ - 1 , 1 ] , ** opensignals_kwargs ( "figure" ) ) ) list_figures [ - 1 ] . l...
def xstep ( self ) : """The xstep of the baseline consensus class from which this class is derived is re - used to implement the xstep of the modified algorithm by replacing ` ` self . ZSf ` ` , which is constant in the baseline algorithm , with a quantity derived from the additional variables ` ` self . Y1...
self . YU1 [ : ] = self . Y1 - self . U1 self . ZSf = np . conj ( self . Zf ) * ( self . Sf + sl . rfftn ( self . YU1 , None , self . cri . axisN ) ) rho = self . rho self . rho = 1.0 super ( ConvCnstrMODMaskDcpl_Consensus , self ) . xstep ( ) self . rho = rho
def get_port_def ( port_num , proto = 'tcp' ) : '''Given a port number and protocol , returns the port definition expected by docker - py . For TCP ports this is simply an integer , for UDP ports this is ( port _ num , ' udp ' ) . port _ num can also be a string in the format ' port _ num / udp ' . If so , th...
try : port_num , _ , port_num_proto = port_num . partition ( '/' ) except AttributeError : pass else : if port_num_proto : proto = port_num_proto try : if proto . lower ( ) == 'udp' : return int ( port_num ) , 'udp' except AttributeError : pass return int ( port_num )
def unpack_db_to_component_dfs ( self , convert_dates = False ) : """Returns the set of known tables in the adjustments file in DataFrame form . Parameters convert _ dates : bool , optional By default , dates are returned in seconds since EPOCH . If convert _ dates is True , all ints in date columns will ...
return { t_name : self . get_df_from_table ( t_name , convert_dates ) for t_name in self . _datetime_int_cols }
def create ( self , environments ) : """Method to create environments vip : param environments vip : Dict containing environments vip desired to be created on database : return : None"""
data = { 'environments_vip' : environments } uri = 'api/v3/environment-vip/' return super ( ApiEnvironmentVip , self ) . post ( uri , data )
def abbreviate_road ( name ) : """Function that abbreviates ' road ' as ' rd . ' in the input string . Examples : abbreviate _ road ( ' ravipadu Road ' ) - > ' ravipadu Rd . ' abbreviate _ road ( ' palnadu Road ' ) - > ' palnadu Rd . ' abbreviate _ road ( ' eshwar enclave Road ' ) - > ' eshwar enclave Rd . ...
import re return re . sub ( 'Road$' , 'Rd.' , name )
def std_scale ( expr , columns = None , with_means = True , with_std = True , preserve = False , suffix = '_scaled' , group = None ) : """Resize a data frame by mean and standard error . : param DataFrame expr : Input DataFrame : param bool with _ means : Determine whether the output will be subtracted by means...
time_suffix = str ( int ( time . time ( ) ) ) def calc_agg ( expr , col ) : return [ getattr ( expr , col ) . mean ( ) . rename ( col + '_mean_' + time_suffix ) , getattr ( expr , col ) . std ( ddof = 0 ) . rename ( col + '_std_' + time_suffix ) , ] def do_scale ( expr , col ) : c = getattr ( expr , col ) m...
def _normalize_query ( self , query ) : """Converts Arrays in the query to comma separaters lists for proper API handling ."""
for k , v in query . items ( ) : if isinstance ( v , list ) : query [ k ] = ',' . join ( [ str ( e ) for e in v ] )
def read_tex ( src ) : r"""Read next expression from buffer : param Buffer src : a buffer of tokens"""
c = next ( src ) if c . startswith ( '%' ) : return c elif c . startswith ( '$' ) : name = '$$' if c . startswith ( '$$' ) else '$' expr = TexEnv ( name , [ ] , nobegin = True ) return read_math_env ( src , expr ) elif c . startswith ( '\[' ) or c . startswith ( "\(" ) : if c . startswith ( '\[' ) :...
def _form_pages ( self , message_no , content , out , height , width ) : """Form the pages"""
self . pages [ message_no ] = [ ] page_height = height - 4 # 2-3 for menu , 1 for cursor outline = u'' no_lines_page = 0 for original , formatted in zip ( content . split ( '\n' ) , out . split ( '\n' ) ) : no_lines_original = int ( math . ceil ( len ( original ) / float ( width ) ) ) # Blank line if len ( ...
def selection ( self ) : """Selection property . : return : None if no font is selected and font family name if one is selected . : rtype : None or str"""
if self . _font . get ( ) is "" or self . _font . get ( ) not in self . _fonts : return None else : return self . _font . get ( )
def create_command_class ( name , func_module ) : """Dynamically creates subclass of MigratingCommand . Method takes name of the function , module it is part of and builds the subclass of : py : class : ` MigratingCommand ` . Having a subclass of : py : class : ` cliff . command . Command ` is mandatory for...
cmd_name = name [ 3 : ] . replace ( '_' , '-' ) callback = getattr ( func_module , name ) desc = callback . __doc__ or '' help = desc . strip ( ) . split ( '\n' ) [ 0 ] arguments = getattr ( callback , 'arguments' , [ ] ) body = { '_args' : arguments , '_callback' : staticmethod ( callback ) , '_description' : desc , '...
def response ( self , url ) : """Grab an API response ."""
resp = requests . get ( url ) . content return self . parseresponse ( resp )
def iterate_ngrams ( text , n ) : """Generator to yield ngrams in ` ` text ` ` . Example : > > > for ngram in iterate _ ngrams ( " example " , 4 ) : . . . print ( ngram ) exam xamp ampl mple Args : text ( str ) : text to iterate over n ( int ) : size of window for iteration Returns : Generat...
if n <= 0 : raise ValueError ( "n must be a positive integer" ) return [ text [ i : i + n ] for i in range ( len ( text ) - n + 1 ) ]
def config_maker ( project_name , path ) : """Creates a config file based on the project name"""
with open ( skeleton_path ( "config.py" ) , "r" ) as config_source : config_content = config_source . read ( ) config_content = config_content . replace ( "__PROJECT_NAME__" , project_name ) with open ( path , "w" ) as config_dest : config_dest . write ( config_content )
def report_stats ( self , payload , is_retry = False ) : """Send data to graphite host : param payload : Data to send to graphite"""
if self . debug : if self . pickle_proto : print "reporting pickled stats" else : print "reporting stats -> {\n%s}" % payload try : graphite = socket . socket ( ) with eventlet . Timeout ( self . graphite_timeout , True ) : graphite . connect ( self . graphite_addr ) grap...
def getScoringVector ( self , orderVector ) : """Returns a scoring vector such that the first k candidates recieve 1 point and all others recive 0 This function is called by getUtilities ( ) which is implemented in the parent class . : ivar list < int > orderVector : A list of integer representations for each...
scoringVector = [ ] for i in range ( 0 , self . k ) : scoringVector . append ( 1 ) for i in range ( self . k , len ( orderVector ) ) : scoringVector . append ( 0 ) return scoringVector
def create_perm ( self , using = None , * args , ** kwargs ) : """Creates a fake content type and permission to be able to check for permissions"""
from django . conf import settings from django . contrib . auth . models import Permission from django . contrib . contenttypes . models import ContentType constance_dbs = getattr ( settings , 'CONSTANCE_DBS' , None ) if constance_dbs is not None and using not in constance_dbs : return if ContentType . _meta . inst...
def set_client_params ( self , start_unsubscribed = None , clear_on_exit = None , unsubscribe_on_reload = None , announce_interval = None ) : """Sets subscribers related params . : param bool start _ unsubscribed : Configure subscriptions but do not send them . . . note : : Useful with master FIFO . : param b...
self . _set ( 'start-unsubscribed' , start_unsubscribed , cast = bool ) self . _set ( 'subscription-clear-on-shutdown' , clear_on_exit , cast = bool ) self . _set ( 'unsubscribe-on-graceful-reload' , unsubscribe_on_reload , cast = bool ) self . _set ( 'subscribe-freq' , announce_interval ) return self . _section
def get_calculated_display_values ( self , immediate : bool = False ) -> DisplayValues : """Return the display values . Return the current ( possibly uncalculated ) display values unless ' immediate ' is specified . If ' immediate ' , return the existing ( calculated ) values if they exist . Using the ' immedia...
if not immediate or not self . __is_master or not self . __last_display_values : if not self . __current_display_values and self . __data_item : self . __current_display_values = DisplayValues ( self . __data_item . xdata , self . sequence_index , self . collection_index , self . slice_center , self . slice...
def fetch_suvi_l1b ( self , product , correct = True , median_kernel = 5 ) : """Given a product keyword , downloads the SUVI l1b image into the current directory . NOTE : the suvi _ l1b _ url must be properly set for the Fetcher object : param product : the keyword for the product , e . g . suvi - l1b - fe094 ...
if self . date < datetime ( 2018 , 5 , 23 ) and not ( self . date >= datetime ( 2017 , 9 , 6 ) and self . date <= datetime ( 2017 , 9 , 10 , 23 , 59 ) ) : print ( "SUVI data is only available after 2018-5-23" ) return product , None , None url = self . suvi_base_url + product + "/{}/{:02d}/{:02d}" . format ( se...
def stage_import_from_url ( self , url , token = None , username = None , password = None , insecure = False ) : """Stage an import from a URL to another CDRouter system . : param url : URL to import as string . : param token : ( optional ) API token to use as string ( may be required if importing from a CDRout...
schema = ImportSchema ( ) resp = self . service . post ( self . base , params = { 'url' : url , 'token' : token , 'username' : username , 'password' : password , 'insecure' : insecure } ) return self . service . decode ( schema , resp )
def add_message ( self , msg_content , folder , ** kwargs ) : """Inject a message : params string msg _ content : The entire message ' s content . : params string folder : Folder pathname ( starts with ' / ' ) or folder ID"""
content = { 'm' : kwargs } content [ 'm' ] [ 'l' ] = str ( folder ) content [ 'm' ] [ 'content' ] = { '_content' : msg_content } return self . request ( 'AddMsg' , content )
def count_of_assigned_jobs ( self ) : "Number of fields that have attrib [ ' JobAssigned ' ] set to true ."
assigned = len ( [ x . attrib [ 'JobAssigned' ] for x in self . fields if x . attrib [ 'JobAssigned' ] == 'true' ] ) return assigned
def version_info ( self ) : """Returns API version information for the HMC . This operation does not require authentication . Returns : : term : ` HMC API version ` : The HMC API version supported by the HMC . Raises : : exc : ` ~ zhmcclient . HTTPError ` : exc : ` ~ zhmcclient . ParseError ` : exc : ...
if self . _api_version is None : self . query_api_version ( ) return self . _api_version [ 'api-major-version' ] , self . _api_version [ 'api-minor-version' ]
def _init_datastores ( ) : """Initialize all datastores ."""
global _DATASTORES array = settings . DATASTORES for config in array : cls = _lookup ( config [ 'ENGINE' ] ) ds = _get_datastore ( cls , DataStore , config ) _DATASTORES . append ( ds ) legacy_settings = getattr ( settings , 'MACHINE_CATEGORY_DATASTORES' , None ) if legacy_settings is not None : warning...
def _generate ( self ) : """Parses a file or directory of files into a set of ` ` Document ` ` objects ."""
doc_count = 0 for fp in self . all_files : for doc in self . _get_docs_for_path ( fp ) : yield doc doc_count += 1 if doc_count >= self . max_docs : return
def route ( self , uri , methods = frozenset ( { 'GET' } ) , host = None , strict_slashes = False , stream = False , websocket = False ) : '''Decorate a function to be registered as a route : param uri : path of the URL : param methods : list or tuple of methods allowed : param host : : param strict _ slash...
# Fix case where the user did not prefix the URL with a / # and will probably get confused as to why it ' s not working if not uri . startswith ( '/' ) : uri = '/' + uri def response ( handler ) : if websocket : handler . is_websocket = True elif stream : handler . is_stream = True self ...
def _subset_by_support ( orig_vcf , cmp_calls , data ) : """Subset orig _ vcf to calls also present in any of the comparison callers ."""
cmp_vcfs = [ x [ "vrn_file" ] for x in cmp_calls ] out_file = "%s-inensemble.vcf.gz" % utils . splitext_plus ( orig_vcf ) [ 0 ] if not utils . file_uptodate ( out_file , orig_vcf ) : with file_transaction ( data , out_file ) as tx_out_file : cmd = "bedtools intersect -header -wa -f 0.5 -r -a {orig_vcf} -b "...
def convert_to_oqhazardlib ( self , tom , simple_mesh_spacing = 1.0 , complex_mesh_spacing = 2.0 , area_discretisation = 10.0 , use_defaults = False ) : """Converts the source model to an iterator of sources of : class : openquake . hazardlib . source . base . BaseSeismicSource"""
oq_source_model = [ ] for source in self . sources : if isinstance ( source , mtkAreaSource ) : oq_source_model . append ( source . create_oqhazardlib_source ( tom , simple_mesh_spacing , area_discretisation , use_defaults ) ) elif isinstance ( source , mtkPointSource ) : oq_source_model . appen...
def WaitUntilDone ( self , timeout = None ) : """Wait until the flow completes . Args : timeout : timeout in seconds . None means default timeout ( 1 hour ) . 0 means no timeout ( wait forever ) . Returns : Fresh flow object . Raises : PollTimeoutError : if timeout is reached . FlowFailedError : if ...
f = utils . Poll ( generator = self . Get , condition = lambda f : f . data . state != f . data . RUNNING , timeout = timeout ) if f . data . state != f . data . TERMINATED : raise errors . FlowFailedError ( "Flow %s (%s) failed: %s" % ( self . flow_id , self . client_id , f . data . context . current_state ) ) ret...
def unsafe_execute ( self , result = None ) : """un - wrapped execution , can raise excepetion : return : Execution result : rtype : kser . result . Result"""
if result : self . result += result self . _prerun ( ) return self . _onsuccess ( self . _postrun ( self . _run ( ) ) )
def is_callable ( self ) : """Ensures : attr : ` subject ` is a callable ."""
if not callable ( self . _subject ) : raise self . _error_factory ( _format ( "Expected {} to be callable" , self . _subject ) )
def main ( ) : """Command line interface for the ` ` coloredlogs ` ` program ."""
actions = [ ] try : # Parse the command line arguments . options , arguments = getopt . getopt ( sys . argv [ 1 : ] , 'cdh' , [ 'convert' , 'to-html' , 'demo' , 'help' , ] ) # Map command line options to actions . for option , value in options : if option in ( '-c' , '--convert' , '--to-html' ) : ...
def hset ( key , field , value , host = None , port = None , db = None , password = None ) : '''Set the value of a hash field . . . versionadded : : 2017.7.0 CLI Example : . . code - block : : bash salt ' * ' redis . hset foo _ hash bar _ field bar _ value'''
server = _connect ( host , port , db , password ) return server . hset ( key , field , value )
def should_indent ( code ) : """Determines whether the next line should be indented ."""
last = rem_comment ( code . splitlines ( ) [ - 1 ] ) return last . endswith ( ":" ) or last . endswith ( "\\" ) or paren_change ( last ) < 0
def u16le_list_to_byte_list ( data ) : """! @ brief Convert a halfword array into a byte array"""
byteData = [ ] for h in data : byteData . extend ( [ h & 0xff , ( h >> 8 ) & 0xff ] ) return byteData
def on_person_new ( self , people ) : """New people joined the audience : param people : People that just joined the audience : type people : list [ paps . person . Person ] : rtype : None"""
self . debug ( "()" ) changed = [ ] with self . _people_lock : for p in people : person = Person . from_person ( p ) if person . id in self . _people : self . warning ( u"{} already in audience" . format ( person . id ) ) self . _people [ person . id ] = person changed . ...
def do ( self ) : """Instantiate Services"""
if not self . _nodes : return # Let ' s retain original copy of _ nodes node_copy = dict ( self . _nodes ) self . _do ( node_copy ) return self . _factory . get_instantiated_services ( )
def paste ( self , other ) : """Return a new Image with the given image pasted on top . This image will show through transparent areas of the given image ."""
r , g , b , alpha = other . pil_image . split ( ) pil_image = self . pil_image . copy ( ) pil_image . paste ( other . pil_image , mask = alpha ) return kurt . Image ( pil_image )
def _calculate_crc_ccitt ( data ) : """All CRC stuff ripped from PyCRC , GPLv3 licensed"""
global CRC_CCITT_TABLE if not CRC_CCITT_TABLE : crc_ccitt_table = [ ] for i in range ( 0 , 256 ) : crc = 0 c = i << 8 for j in range ( 0 , 8 ) : if ( crc ^ c ) & 0x8000 : crc = c_ushort ( crc << 1 ) . value ^ 0x1021 else : crc = c_u...
def select_projects ( self , * args ) : """Copy the query and add filtering by monitored projects . This is only useful if the target project represents a Stackdriver account containing the specified monitored projects . Examples : : query = query . select _ projects ( ' project - 1 ' ) query = query . se...
new_query = copy . deepcopy ( self ) new_query . _filter . projects = args return new_query
def reset_password ( self ) : """Return the new random password that has been reset : param user _ login : AuthUserLogin : return : string - the new password"""
def cb ( ) : password = get_random_password ( ) self . change_password ( password ) return password return signals . user_update ( self , ACTIONS [ "PASSWORD" ] , cb )
def checkASN ( filename ) : """Determine if the filename provided to the function belongs to an association . Parameters filename : string Returns validASN : boolean value"""
# Extract the file extn type : extnType = filename [ filename . rfind ( '_' ) + 1 : filename . rfind ( '.' ) ] # Determine if this extn name is valid for an assocation file if isValidAssocExtn ( extnType ) : return True else : return False
def getbr ( self , name ) : """Return a bridge object ."""
for br in self . showall ( ) : if br . name == name : return br raise BridgeException ( "Bridge does not exist." )
def __get_substitution_paths ( g ) : """get atoms paths from detached atom to attached : param g : CGRContainer : return : tuple of atoms numbers"""
for n , nbrdict in g . adjacency ( ) : for m , l in combinations ( nbrdict , 2 ) : nms = nbrdict [ m ] [ 'sp_bond' ] nls = nbrdict [ l ] [ 'sp_bond' ] if nms == ( 1 , None ) and nls == ( None , 1 ) : yield m , n , l elif nms == ( None , 1 ) and nls == ( 1 , None ) : ...
def fft_transpose_fftw ( vec ) : """Perform an FFT transpose from vec into outvec . ( Alex to provide more details in a write - up . ) Parameters vec : array Input array . Returns outvec : array Transposed output array ."""
global _thetransposeplan outvec = pycbc . types . zeros ( len ( vec ) , dtype = vec . dtype ) if _theplan is None : N1 , N2 = splay ( vec ) _thetransposeplan = plan_transpose ( N1 , N2 ) ftexecute ( _thetransposeplan , vec . ptr , outvec . ptr ) return outvec
def validate ( self , value : LocalizedValue , * _ ) : """Validates that the values has been filled in for all required languages Exceptions are raises in order to notify the user of invalid values . Arguments : value : The value to validate ."""
if self . null : return for lang in self . required : lang_val = getattr ( value , settings . LANGUAGE_CODE ) if lang_val is None : raise IntegrityError ( 'null value in column "%s.%s" violates ' 'not-null constraint' % ( self . name , lang ) )
def get_proficiencies_by_query ( self , proficiency_query ) : """Gets a list of ` ` Proficiencies ` ` matching the given proficiency query . arg : proficiency _ query ( osid . learning . ProficiencyQuery ) : the proficiency query return : ( osid . learning . ProficiencyList ) - the returned ` ` ProficiencyL...
# Implemented from template for # osid . resource . ResourceQuerySession . get _ resources _ by _ query and_list = list ( ) or_list = list ( ) for term in proficiency_query . _query_terms : if '$in' in proficiency_query . _query_terms [ term ] and '$nin' in proficiency_query . _query_terms [ term ] : and_li...
def hamiltonian ( edges , directed = False , constraint_generation = True ) : """Calculates shortest path that traverses each node exactly once . Convert Hamiltonian path problem to TSP by adding one dummy point that has a distance of zero to all your other points . Solve the TSP and get rid of the dummy poin...
edges = populate_edge_weights ( edges ) incident , nodes = node_to_edge ( edges , directed = False ) if not directed : # Make graph symmetric dual_edges = edges [ : ] for a , b , w in edges : dual_edges . append ( ( b , a , w ) ) edges = dual_edges DUMMY = "DUMMY" dummy_edges = edges + [ ( DUMMY , x...
def delete ( cls , bucket , key ) : """Delete an object . Technically works by creating a new version which works as a delete marker . : param bucket : The bucket ( instance or id ) to delete the object from . : param key : Key of object . : returns : Created delete marker object if key exists else ` ` No...
bucket_id = as_bucket_id ( bucket ) obj = cls . get ( bucket_id , key ) if obj : return cls . create ( as_bucket ( bucket ) , key ) return None
def minion_sign_in_payload ( self ) : '''Generates the payload used to authenticate with the master server . This payload consists of the passed in id _ and the ssh public key to encrypt the AES key sent back from the master . : return : Payload dictionary : rtype : dict'''
payload = { } payload [ 'cmd' ] = '_auth' payload [ 'id' ] = self . opts [ 'id' ] if 'autosign_grains' in self . opts : autosign_grains = { } for grain in self . opts [ 'autosign_grains' ] : autosign_grains [ grain ] = self . opts [ 'grains' ] . get ( grain , None ) payload [ 'autosign_grains' ] = a...
def _add_mixing_variable_names_to_individual_vars ( self ) : """Ensure that the model objects mixing variables are added to its list of individual variables ."""
assert isinstance ( self . ind_var_names , list ) # Note that if one estimates a mixed logit model , then the mixing # variables will be added to individual vars . And if one estimates # the model again ( perhaps from different starting values ) , then # an error will be raised when creating the coefs series because we...
def ReadDatabase ( self , database_link , options = None ) : """Reads a database . : param str database _ link : The link to the database . : param dict options : The request options for the request . : return : The Database that was read . : rtype : dict"""
if options is None : options = { } path = base . GetPathFromLink ( database_link ) database_id = base . GetResourceIdOrFullNameFromLink ( database_link ) return self . Read ( path , 'dbs' , database_id , None , options )
def k_means ( points , k , ** kwargs ) : """Find k centroids that attempt to minimize the k - means problem : https : / / en . wikipedia . org / wiki / Metric _ k - center Parameters points : ( n , d ) float Points in a space k : int Number of centroids to compute * * kwargs : dict Passed directly t...
from scipy . cluster . vq import kmeans from scipy . spatial import cKDTree points = np . asanyarray ( points , dtype = np . float64 ) points_std = points . std ( axis = 0 ) whitened = points / points_std centroids_whitened , distortion = kmeans ( whitened , k , ** kwargs ) centroids = centroids_whitened * points_std #...
def create ( self ) : """Create multi - line widget for editing"""
# add various pointers to those editing vent _ cfg if self . vent_cfg : self . add ( npyscreen . Textfield , value = '# when configuring external' ' services make sure to do so' , editable = False ) self . add ( npyscreen . Textfield , value = '# in the form of Service = {"setting": "value"}' , editable = False...
def deep_merge ( base , extra ) : """Deeply merge two dictionaries , overriding existing keys in the base . : param base : The base dictionary which will be merged into . : param extra : The dictionary to merge into the base . Keys from this dictionary will take precedence ."""
if extra is None : return for key , value in extra . items ( ) : if value is None : if key in base : del base [ key ] # If the key represents a dict on both given dicts , merge the sub - dicts elif isinstance ( base . get ( key ) , dict ) and isinstance ( value , dict ) : dee...
def max_dimension ( cellmap , sheet = None ) : """This function calculates the maximum dimension of the workbook or optionally the worksheet . It returns a tupple of two integers , the first being the rows and the second being the columns . : param cellmap : all the cells that should be used to calculate the ma...
cells = list ( cellmap . values ( ) ) rows = 0 cols = 0 for cell in cells : if sheet is None or cell . sheet == sheet : rows = max ( rows , int ( cell . row ) ) cols = max ( cols , int ( col2num ( cell . col ) ) ) return ( rows , cols )
def run ( self ) : '''Work on jobs'''
# Register signal handlers self . signals ( ) # Start listening with self . listener ( ) : try : generator = self . jobs ( ) while not self . shutdown : self . pool . wait_available ( ) job = next ( generator ) if job : # For whatever reason , doing imports within...
def account_key ( self , account ) : """Get the public key for * * account * * : param account : Account to get public key for : type account : str : raises : : py : exc : ` nano . rpc . RPCException ` > > > rpc . account _ key ( . . . account = " xrb _ 1e5aqegc1jb7qe964u4adzmcezyo6o146zb8hm6dft8tkp79za3s...
account = self . _process_value ( account , 'account' ) payload = { "account" : account } resp = self . call ( 'account_key' , payload ) return resp [ 'key' ]
def mutation ( self , strength = 0.1 ) : '''Single gene mutation'''
mutStrengthReal = strength mutMaxSizeReal = self . gLength / 2 mutSizeReal = int ( numpy . random . random_integers ( 1 , mutMaxSizeReal ) ) mutationPosReal = int ( numpy . random . random_integers ( 0 + mutSizeReal - 1 , self . y . shape [ 0 ] - 1 - mutSizeReal ) ) mutationSignReal = pl . rand ( ) mutationReal = pl . ...
def set_hostname ( new_hostname , pretty_hostname = None ) : """Sets this hosts hostname This method updates / etc / sysconfig / network and calls the hostname command to set a hostname on a Linux system . : param new _ hostname : ( str ) New hostname : param pretty _ hostname : ( str ) new pretty hostname ...
log = logging . getLogger ( mod_logger + '.set_hostname' ) # Ensure the hostname is a str if not isinstance ( new_hostname , basestring ) : msg = 'new_hostname argument must be a string' raise CommandError ( msg ) # Update the network config file network_file = '/etc/sysconfig/network' if os . path . isfile ( n...
def link ( self ) : """str : full path of the linked file entry ."""
if not self . IsLink ( ) : return '' location = getattr ( self . path_spec , 'location' , None ) if location is None : return '' return self . _file_system . GetDataByPath ( location )
def add_analysis ( self , component , group_name , attrs , config = None ) : """Add a new analysis group to the file . : param component : The component name . : param group _ name : The name to use for the group . Must not already exist in the file e . g . ' Test _ 000 ' . : param attrs : A dictionary cont...
self . assert_writeable ( ) group = 'Analyses/{}' . format ( group_name ) cfg_group = '{}/Configuration' . format ( group ) group_attrs = attrs . copy ( ) group_attrs [ 'component' ] = component self . _add_group ( group , group_attrs ) self . handle [ group ] . create_group ( 'Summary' ) self . handle [ group ] . crea...
def parameterized_expectations ( model , verbose = False , initial_dr = None , pert_order = 1 , with_complementarities = True , grid = { } , distribution = { } , maxit = 100 , tol = 1e-8 , inner_maxit = 100 , direct = False ) : '''Find global solution for ` ` model ` ` via parameterized expectations . Controls mu...
def vprint ( t ) : if verbose : print ( t ) g = model . functions [ 'transition' ] h = model . functions [ 'expectation' ] f = model . functions [ 'arbitrage_exp' ] # f ( s , x , z , p , out ) parms = model . calibration [ 'parameters' ] if direct is True : d = model . functions [ 'direct_response' ] ap...
def use_theme ( theme , directory = None ) : """Switches to the specified theme . This returns False if switching to the already active theme ."""
repo = require_repo ( directory ) if theme not in list_themes ( directory ) : raise ThemeNotFoundError ( theme ) old_theme = set_value ( repo , 'theme' , theme ) return old_theme != theme
def configure_logging ( emit_list ) : """Configure logging to send log records to the master ."""
if 'sphinx' in sys . modules : module_base = 'resolwe.flow.executors' else : module_base = 'executors' logging_config = dict ( version = 1 , formatters = { 'json_formatter' : { '()' : JSONFormatter } , } , handlers = { 'redis' : { 'class' : module_base + '.logger.RedisHandler' , 'formatter' : 'json_formatter' ,...
def _get_config_file_in_folder ( cls , path ) : """Look for a configuration file in ` path ` . If exists return its full path , otherwise None ."""
if os . path . isfile ( path ) : path = os . path . dirname ( path ) for fn in cls . PROJECT_CONFIG_FILES : config = RawConfigParser ( ) full_path = os . path . join ( path , fn ) if config . read ( full_path ) and cls . _get_section_name ( config ) : return full_path
def colorbar ( self , mappable = None , cax = None , ax = None , fraction = 0. , label = None , emit = True , ** kwargs ) : """Add a colorbar to the current ` Plot ` A colorbar must be associated with an ` Axes ` on this ` Plot ` , and an existing mappable element ( e . g . an image ) . Parameters mappable ...
# pre - process kwargs mappable , kwargs = gcbar . process_colorbar_kwargs ( self , mappable , ax , cax = cax , fraction = fraction , ** kwargs ) # generate colour bar cbar = super ( Plot , self ) . colorbar ( mappable , ** kwargs ) self . colorbars . append ( cbar ) if label : # mpl < 1.3 doesn ' t accept label in Col...
def check_aggregate ( self , variable , components = None , exclude_on_fail = False , multiplier = 1 , ** kwargs ) : """Check whether a timeseries matches the aggregation of its components Parameters variable : str variable to be checked for matching aggregation of sub - categories components : list of str ...
# compute aggregate from components , return None if no components df_components = self . aggregate ( variable , components ) if df_components is None : return # filter and groupby data , use ` pd . Series . align ` for matching index rows = self . _apply_filters ( variable = variable ) df_variable , df_components ...
def call_binop ( self , context , operator , left , right ) : """For intercepted binary operator calls ( : meth : ` intercepted _ binops ` ) this function is executed instead of the builtin operator . This can be used to fine tune the behavior of certain operators . . . versionadded : : 2.6"""
return self . binop_table [ operator ] ( left , right )
def update ( self , catalog = None , dependencies = None , allow_overwrite = False ) : '''Convenience method to update this Di instance with the specified contents . : param catalog : ICatalog supporting class or mapping : type catalog : ICatalog or collections . Mapping : param dependencies : Mapping of depe...
if catalog : self . _providers . update ( catalog , allow_overwrite = allow_overwrite ) if dependencies : self . _dependencies . update ( dependencies )
def _is_mutated ( self ) : """: return : A boolean - if the sequence or any children ( recursively ) have been mutated"""
mutated = self . _mutated if self . children is not None : for child in self . children : if isinstance ( child , Sequence ) or isinstance ( child , SequenceOf ) : mutated = mutated or child . _is_mutated ( ) return mutated
def complete_offset_upload ( self , chunk_num ) : # type : ( Descriptor , int ) - > None """Complete the upload for the offset : param Descriptor self : this : param int chunk _ num : chunk num completed"""
with self . _meta_lock : self . _outstanding_ops -= 1 # save resume state if self . is_resumable : # only set resumable completed if all replicas for this # chunk are complete if blobxfer . util . is_not_empty ( self . _dst_ase . replica_targets ) : if chunk_num not in self . _replic...
def _get_total_sigma ( self , C , std_intra , std_inter ) : """Returns the total sigma term for the arbitrary horizontal component of ground motion defined by equation 18 , page 150"""
return np . sqrt ( std_intra ** 2. + std_inter ** 2. + C [ 'c_lny' ] ** 2. )
def add_task ( self , func , * args , ** kargs ) : """Add a task to the queue"""
self . tasks_queue . put ( ( func , args , kargs ) )
def get_mapping ( self , index , doc_type = None ) : """Get mapping for index . : param index : index name"""
mapping = self . es . indices . get_mapping ( index = index , doc_type = doc_type ) return next ( iter ( mapping . values ( ) ) )
def static_workflow_declaration ( job , config , normal_bam , normal_bai , tumor_bam , tumor_bai ) : """Statically declare workflow so sections can be modularly repurposed : param JobFunctionWrappingJob job : passed automatically by Toil : param Namespace config : Argparse Namespace object containing argument i...
# Mutation and indel tool wiring memory = '1G' if config . ci_test else '10G' disk = '1G' if config . ci_test else '75G' mutect_results , pindel_results , muse_results = None , None , None if config . run_mutect : mutect_results = job . addChildJobFn ( run_mutect , normal_bam , normal_bai , tumor_bam , tumor_bai , ...
def get_jids_filter ( count , filter_find_job = True ) : '''Return a list of all job ids : param int count : show not more than the count of most recent jobs : param bool filter _ find _ jobs : filter out ' saltutil . find _ job ' jobs'''
with _get_serv ( ret = None , commit = True ) as cur : sql = '''SELECT * FROM ( SELECT DISTINCT `jid` ,`load` FROM `jids` {0} ORDER BY `jid` DESC limit {1} ) `tmp` ORDER BY `jid`;''' where = '''WHERE `load` NOT ...
def perform_align ( input_list , ** kwargs ) : """Main calling function . Parameters input _ list : list List of one or more IPPSSOOTs ( rootnames ) to align . archive : Boolean Retain copies of the downloaded files in the astroquery created sub - directories ? clobber : Boolean Download and overwrite...
filteredTable = Table ( ) run_align ( input_list , result = filteredTable , ** kwargs ) return filteredTable
def to_native_units ( self , motor ) : """Return the native speed measurement required to achieve desired degrees - per - second"""
assert abs ( self . degrees_per_second ) <= motor . max_dps , "invalid degrees-per-second: {} max DPS is {}, {} was requested" . format ( motor , motor . max_dps , self . degrees_per_second ) return self . degrees_per_second / motor . max_dps * motor . max_speed
def getdirs ( self , section , option , raw = False , vars = None , fallback = [ ] ) : """A convenience method which coerces the option in the specified section to a list of directories ."""
globs = self . getlist ( section , option , fallback = [ ] ) return [ f for g in globs for f in glob . glob ( g ) if os . path . isdir ( f ) ]