signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def dropEvent ( self , event ) : """Listens for query ' s being dragged and dropped onto this tree . : param event | < QDropEvent >"""
# overload the current filtering options data = event . mimeData ( ) if data . hasFormat ( 'application/x-orb-table' ) and data . hasFormat ( 'application/x-orb-query' ) : tableName = self . tableTypeName ( ) if nstr ( data . data ( 'application/x-orb-table' ) ) == tableName : data = nstr ( data . data ...
def from_csv ( cls , path , sep = ',' , parse_dates = True , header = None , index_col = 0 , encoding = None , infer_datetime_format = False ) : """Read CSV file . . . deprecated : : 0.21.0 Use : func : ` pandas . read _ csv ` instead . It is preferable to use the more powerful : func : ` pandas . read _ csv ...
# We ' re calling ` DataFrame . from _ csv ` in the implementation , # which will propagate a warning regarding ` from _ csv ` deprecation . from pandas . core . frame import DataFrame df = DataFrame . from_csv ( path , header = header , index_col = index_col , sep = sep , parse_dates = parse_dates , encoding = encodin...
def cancel ( self ) : """Cancel a running : meth : ` iterconsume ` session ."""
for consumer_tag in self . _open_consumers . values ( ) : try : self . backend . cancel ( consumer_tag ) except KeyError : pass self . _open_consumers . clear ( )
def _helper ( result , graph , number_edges_remaining : int , node_blacklist : Set [ BaseEntity ] , invert_degrees : Optional [ bool ] = None , ) : """Help build a random graph . : type result : networkx . Graph : type graph : networkx . Graph"""
original_node_count = graph . number_of_nodes ( ) log . debug ( 'adding remaining %d edges' , number_edges_remaining ) for _ in range ( number_edges_remaining ) : source , possible_step_nodes , c = None , set ( ) , 0 while not source or not possible_step_nodes : source = get_random_node ( result , node_...
def nvmlDeviceGetClockInfo ( handle , type ) : r"""* Retrieves the current clock speeds for the device . * For Fermi & tm ; or newer fully supported devices . * See \ ref nvmlClockType _ t for details on available clock information . * @ param device The identifier of the target device * @ param type Identi...
c_clock = c_uint ( ) fn = _nvmlGetFunctionPointer ( "nvmlDeviceGetClockInfo" ) ret = fn ( handle , _nvmlClockType_t ( type ) , byref ( c_clock ) ) _nvmlCheckReturn ( ret ) return bytes_to_str ( c_clock . value )
def LookupNamespace ( self , prefix ) : """Resolves a namespace prefix in the scope of the current element ."""
ret = libxml2mod . xmlTextReaderLookupNamespace ( self . _o , prefix ) return ret
def PartialDynamicSystem ( self , ieq , variable ) : """returns dynamical system blocks associated to output variable"""
if ieq == 0 : # U1 = 0 if variable == self . physical_nodes [ 0 ] . variable : v = Step ( 'Ground' , 0 ) return [ Gain ( v , variable , 1 ) ]
def scopes_multi_checkbox ( field , ** kwargs ) : """Render multi checkbox widget ."""
kwargs . setdefault ( 'type' , 'checkbox' ) field_id = kwargs . pop ( 'id' , field . id ) html = [ u'<div class="row">' ] for value , label , checked in field . iter_choices ( ) : choice_id = u'%s-%s' % ( field_id , value ) options = dict ( kwargs , name = field . name , value = value , id = choice_id , class_ ...
def get_border_phase ( self , idn = 0 , idr = 0 ) : """Return one of nine border fields Parameters idn : int Index for refractive index . One of - 1 ( left ) , 0 ( center ) , 1 ( right ) idr : int Index for radius . One of - 1 ( left ) , 0 ( center ) , 1 ( right )"""
assert idn in [ - 1 , 0 , 1 ] assert idr in [ - 1 , 0 , 1 ] n = self . sphere_index + self . dn * idn r = self . radius + self . dr * idr # convert to array indices idn += 1 idr += 1 # find out whether we need to compute a new border field if self . _n_border [ idn , idr ] == n and self . _r_border [ idn , idr ] == r :...
def convert_camel_case_keys ( original_dict : Dict [ str , Any ] ) -> Dict [ str , Any ] : """Converts all keys of a dict from camel case to snake case , recursively"""
new_dict = dict ( ) for key , val in original_dict . items ( ) : if isinstance ( val , dict ) : # Recurse new_dict [ convert_camel_case_string ( key ) ] = convert_camel_case_keys ( val ) else : new_dict [ convert_camel_case_string ( key ) ] = val return new_dict
def list_wegobjecten_by_straat ( self , straat ) : '''List all ` wegobjecten ` in a : class : ` Straat ` : param straat : The : class : ` Straat ` for which the ` wegobjecten ` are wanted . : rtype : A : class : ` list ` of : class : ` Wegobject `'''
try : id = straat . id except AttributeError : id = straat def creator ( ) : res = crab_gateway_request ( self . client , 'ListWegobjectenByStraatnaamId' , id ) try : return [ Wegobject ( r . IdentificatorWegobject , r . AardWegobject ) for r in res . WegobjectItem ] except AttributeError : ...
def delete_fabric_fw_internal ( self , tenant_id , fw_dict , is_fw_virt , result ) : """Internal routine to delete the fabric configuration . This runs the SM and deletes the entries from DB and local cache ."""
if not self . auto_nwk_create : LOG . info ( "Auto network creation disabled" ) return False try : tenant_name = fw_dict . get ( 'tenant_name' ) fw_name = fw_dict . get ( 'fw_name' ) if tenant_id not in self . service_attr : LOG . error ( "Service obj not created for tenant %s" , tenant_name...
def flush ( self ) : """Commit cached writes to the file handle . Does not flush libc buffers or notifies the kernel , so these changes may not immediately be visible to other processes . Updates the fingerprints whena writes happen , so successive ` ` flush ( ) ` ` invocations are no - ops . It is not ne...
garbage = [ ] for i , ( x , signature ) in self . refs . items ( ) : if sys . getrefcount ( x ) == 3 : garbage . append ( i ) if fingerprint ( x ) == signature : continue self . filehandle . puttr ( i , x ) signature = fingerprint ( x ) # to avoid too many resource leaks , when this dict...
def _get_stddevs ( self , C , mag , stddev_types , sites ) : """Return standard deviation as defined on page 29 in equation 8a , b , c and 9."""
num_sites = sites . vs30 . size sigma_intra = np . zeros ( num_sites ) # interevent stddev tau = sigma_intra + C [ 'tau' ] # intraevent std ( equations 8a - 8c page 29) if mag < 5.0 : sigma_intra += C [ 'sigmaM6' ] - C [ 'sigSlope' ] elif 5.0 <= mag < 7.0 : sigma_intra += C [ 'sigmaM6' ] + C [ 'sigSlope' ] * ( ...
def list_packages_in_eups_table ( table_text ) : """List the names of packages that are required by an EUPS table file . Parameters table _ text : ` str ` The text content of an EUPS table file . Returns names : ` list ` [ ` str ` ] List of package names that are required byy the EUPS table file ."""
logger = logging . getLogger ( __name__ ) # This pattern matches required product names in EUPS table files . pattern = re . compile ( r'setupRequired\((?P<name>\w+)\)' ) listed_packages = [ m . group ( 'name' ) for m in pattern . finditer ( table_text ) ] logger . debug ( 'Packages listed in the table file: %r' , list...
def find_program ( basename ) : """Find program in PATH and return absolute path Try adding . exe or . bat to basename on Windows platforms ( return None if not found )"""
names = [ basename ] if os . name == 'nt' : # Windows platforms extensions = ( '.exe' , '.bat' , '.cmd' ) if not basename . endswith ( extensions ) : names = [ basename + ext for ext in extensions ] + [ basename ] for name in names : path = is_program_installed ( name ) if path : return ...
def __shpFileLength ( self ) : """Calculates the file length of the shp file ."""
# Remember starting position start = self . shp . tell ( ) # Calculate size of all shapes self . shp . seek ( 0 , 2 ) size = self . shp . tell ( ) # Calculate size as 16 - bit words size //= 2 # Return to start self . shp . seek ( start ) return size
def get_accelerometer_raw ( self ) : """Accelerometer x y z raw data in Gs"""
raw = self . _get_raw_data ( 'accelValid' , 'accel' ) if raw is not None : self . _last_accel_raw = raw return deepcopy ( self . _last_accel_raw )
def next_data ( ) : "simulated data"
t0 = time . time ( ) lt = time . localtime ( t0 ) tmin , tsec = lt [ 4 ] , lt [ 5 ] u = np . random . random ( ) v = np . random . random ( ) x = np . sin ( ( u + tsec ) / 3.0 ) + tmin / 30. + v / 5.0 return t0 , x
def move ( srcpath , dstpath , overwrite = True ) : """Moves the file or directory at ` srcpath ` to ` dstpath ` . Returns True if successful , False otherwise ."""
# TODO : ( JRR @ 201612230924 ) Consider adding smarter checks to prevent files ending up with directory names ; e . g . if dstpath directory does not exist . if not op . exists ( srcpath ) : return False if srcpath == dstpath : return True if op . isfile ( srcpath ) and op . isdir ( dstpath ) : verfunc = o...
def reload ( self ) : """Reloads the current model ' s data from the underlying database record , updating it in - place ."""
self . emit ( 'will_reload' ) self . populate ( self . collection . find_one ( type ( self ) . _id_spec ( self [ '_id' ] ) ) ) self . emit ( 'did_reload' )
def get_glob ( path ) : """Process the input path , applying globbing and formatting . Do note that this will returns files AND directories that match the glob . No tilde expansion is done , but * , ? , and character ranges expressed with [ ] will be correctly matched . Escape all special characters ( ' ? '...
if isinstance ( path , str ) : return glob . glob ( path , recursive = True ) if isinstance ( path , os . PathLike ) : # hilariously enough , glob doesn ' t like path - like . Gotta be str . return glob . glob ( str ( path ) , recursive = True ) elif isinstance ( path , ( list , tuple ) ) : # each glob returns ...
def load_views ( self ) : """Loads the views for this project from the project directory structure ."""
view_path = os . path . join ( self . path , StatikProject . VIEWS_DIR ) logger . debug ( "Loading views from: %s" , view_path ) if not os . path . isdir ( view_path ) : raise MissingProjectFolderError ( StatikProject . VIEWS_DIR ) view_files = list_files ( view_path , [ 'yml' , 'yaml' ] ) logger . debug ( "Found %...
def deselect_all ( self ) : """Clear all selected entries . This is only valid when the SELECT supports multiple selections . throws NotImplementedError If the SELECT does not support multiple selections"""
if not self . is_multiple : raise NotImplementedError ( "You may only deselect all options of a multi-select" ) for opt in self . options : self . _unsetSelected ( opt )
def lowshelf ( self , gain = - 20.0 , frequency = 100 , slope = 0.5 ) : """lowshelf takes 3 parameters : a signed number for gain or attenuation in dB , filter frequency in Hz and slope ( default = 0.5 , maximum = 1.0 ) . Beware of Clipping when using positive gain ."""
self . command . append ( 'bass' ) self . command . append ( gain ) self . command . append ( frequency ) self . command . append ( slope ) return self
def _get_configured_module ( option_name , known_modules = None ) : """Get the module specified by the value of option _ name . The value of the configuration option will be used to load the module by name from the known module list or treated as a path if not found in known _ modules . Args : option _ name...
from furious . job_utils import path_to_reference config = get_config ( ) option_value = config [ option_name ] # If no known _ modules were give , make it an empty dict . if not known_modules : known_modules = { } module_path = known_modules . get ( option_value ) or option_value return path_to_reference ( module_...
def _store_entry ( self , entry ) : """Stores a new log entry and notifies listeners : param entry : A LogEntry object"""
# Get the logger and log the message self . __logs . append ( entry ) # Notify listeners for listener in self . __listeners . copy ( ) : try : listener . logged ( entry ) except Exception as ex : # Create a new log entry , without using logging nor notifying # listener ( to avoid a recursion ) ...
def get_current_thread_id ( thread ) : '''Note : the difference from get _ current _ thread _ id to get _ thread _ id is that for the current thread we can get the thread id while the thread . ident is still not set in the Thread instance .'''
try : # Fast path without getting lock . tid = thread . __pydevd_id__ if tid is None : # Fix for https : / / www . brainwy . com / tracker / PyDev / 645 # if _ _ pydevd _ id _ _ is None , recalculate it . . . also , use an heuristic # that gives us always the same id for the thread ( using thread . iden...
def block ( self , * blocks , ** kwargs ) -> "CodeBlock" : """Build a basic code block . Positional arguments should be instances of CodeBlock or strings . All code blocks passed as positional arguments are added at indentation level 0. None blocks are skipped ."""
assert "name" not in kwargs kwargs . setdefault ( "code" , self ) code = CodeBlock ( ** kwargs ) for block in blocks : if block is not None : code . _blocks . append ( ( 0 , block ) ) return code
def add_tags ( self , * tags ) : """Add a list of strings to the statement as tags . ( Overrides the method from StatementMixin )"""
for _tag in tags : self . tags . get_or_create ( name = _tag )
def output_size ( self ) -> Tuple [ Sequence [ Shape ] , Sequence [ Shape ] , Sequence [ Shape ] , int ] : '''Returns the simulation output size .'''
return self . _cell . output_size
def build_job_configs ( self , args ) : """Hook to build job configurations"""
job_configs = { } components = Component . build_from_yamlfile ( args [ 'comp' ] ) NAME_FACTORY . update_base_dict ( args [ 'data' ] ) ret_dict = make_catalog_comp_dict ( sources = args [ 'library' ] , basedir = '.' ) comp_info_dict = ret_dict [ 'comp_info_dict' ] for split_ver , split_dict in comp_info_dict . items ( ...
def getroot ( self ) : """Return the root element of the figure . The root element is a group of elements after stripping the toplevel ` ` < svg > ` ` tag . Returns GroupElement All elements of the figure without the ` ` < svg > ` ` tag ."""
if 'class' in self . root . attrib : attrib = { 'class' : self . root . attrib [ 'class' ] } else : attrib = None return GroupElement ( self . root . getchildren ( ) , attrib = attrib )
def only_manager ( self ) : """Convience accessor for tests and contexts with sole manager ."""
assert len ( self . managers ) == 1 , MULTIPLE_MANAGERS_MESSAGE return list ( self . managers . values ( ) ) [ 0 ]
def set_freq ( self , fout , freq ) : """Sets new output frequency , required parameters are real current frequency at output and new required frequency ."""
hsdiv_tuple = ( 4 , 5 , 6 , 7 , 9 , 11 ) # possible dividers n1div_tuple = ( 1 , ) + tuple ( range ( 2 , 129 , 2 ) ) fdco_min = 5670.0 # set maximum as minimum hsdiv = self . get_hs_div ( ) # read curent dividers n1div = self . get_n1_div ( ) if abs ( ( freq - fout ) * 1e6 / fout ) > 3500 : # Large change of frequency ...
def run ( self ) : """Run operations ."""
for op in self . ops : if isinstance ( op , Operation ) : LOGGER . info ( "%s %s" , op . method , op . args ) op . run ( ) else : op ( ) self . clean ( )
def validate_blob_uri_contents ( contents : bytes , blob_uri : str ) -> None : """Raises an exception if the sha1 hash of the contents does not match the hash found in te blob _ uri . Formula for how git calculates the hash found here : http : / / alblue . bandlem . com / 2011/08 / git - tip - of - week - objec...
blob_path = parse . urlparse ( blob_uri ) . path blob_hash = blob_path . split ( "/" ) [ - 1 ] contents_str = to_text ( contents ) content_length = len ( contents_str ) hashable_contents = "blob " + str ( content_length ) + "\0" + contents_str hash_object = hashlib . sha1 ( to_bytes ( text = hashable_contents ) ) if ha...
def _rts_smoother_update_step ( k , p_m , p_P , p_m_pred , p_P_pred , p_m_prev_step , p_P_prev_step , p_dynamic_callables ) : """Rauch – Tung – Striebel ( RTS ) update step Input : k : int Iteration No . Starts at 0 . Total number of iterations equal to the number of measurements . p _ m : matrix of size ...
A = p_dynamic_callables . Ak ( k , p_m , p_P ) # state transition matrix ( or Jacobian ) tmp = np . dot ( A , p_P . T ) if A . shape [ 0 ] == 1 : # 1D states G = tmp . T / p_P_pred # P [ : , : , k ] is symmetric else : try : LL , islower = linalg . cho_factor ( p_P_pred ) G = linalg . cho_so...
def _copyDPToClipboard ( self ) : """Callback for item menu ."""
dp = self . _dp_menu_on if dp and dp . archived : path = dp . fullpath . replace ( " " , "\\ " ) QApplication . clipboard ( ) . setText ( path , QClipboard . Clipboard ) QApplication . clipboard ( ) . setText ( path , QClipboard . Selection )
def _header_message_type_update ( obj , attr ) : """Update the message type on the header . Set the message _ type of the header according to the message _ type of the parent class ."""
old_enum = obj . message_type new_header = attr [ 1 ] new_enum = new_header . __class__ . message_type . enum_ref # : This ' if ' will be removed on the future with an # : improved version of _ _ init _ subclass _ _ method of the # : GenericMessage class if old_enum : msg_type_name = old_enum . name new_type = ...
def talkerIndication ( ) : """TALKER INDICATION Section 9.1.44"""
a = TpPd ( pd = 0x6 ) b = MessageType ( mesType = 0x11 ) # 00010001 c = MobileStationClassmark2 ( ) d = MobileId ( ) packet = a / b / c / d return packet
def handle_batch_requests ( request , * args , ** kwargs ) : '''A view function to handle the overall processing of batch requests .'''
batch_start_time = datetime . now ( ) try : # Get the Individual WSGI requests . wsgi_requests = get_wsgi_requests ( request ) except BadBatchRequest as brx : return HttpResponseBadRequest ( content = brx . message ) # Fire these WSGI requests , and collect the response for the same . response = execute_request...
def _load_point ( tokens , string ) : """: param tokens : A generator of string tokens for the input WKT , begining just after the geometry type . The geometry type is consumed before we get to here . For example , if : func : ` loads ` is called with the input ' POINT ( 0.0 1.0 ) ' , ` ` tokens ` ` would g...
if not next ( tokens ) == '(' : raise ValueError ( INVALID_WKT_FMT % string ) coords = [ ] try : for t in tokens : if t == ')' : break else : coords . append ( float ( t ) ) except tokenize . TokenError : raise ValueError ( INVALID_WKT_FMT % string ) return dict ( typ...
def get_elements ( self , filter_cls , elem_id = None ) : """Get a list of elements from the result and filter the element type by a class . : param filter _ cls : : param elem _ id : ID of the object : type elem _ id : Integer : return : List of available elements : rtype : List"""
result = [ ] if elem_id is not None : try : result = [ self . _class_collection_map [ filter_cls ] [ elem_id ] ] except KeyError : result = [ ] else : for e in self . _class_collection_map [ filter_cls ] . values ( ) : result . append ( e ) return result
def _index_filter ( index_data , filter_value , filter_operator , field_converter = None ) : """Post Filter Args : index _ data ( dictionary ) : The indexed data for the provided field . field ( string ) : The field to filter on . filter _ value ( string | list ) : The value to match . filter _ operator (...
filtered_data = [ ] if filter_operator == operator . eq : if field_converter is not None : filter_value = field_converter ( filter_value ) # for data _ obj in index _ data : # yield data _ obj . data filtered_data = index_data . get ( filter_value ) else : for field , data_obj_list in index_...
def when_equal ( self , key : Hashable , value : Any , ** when_kwargs ) -> StateWatcher : """Block until ` ` state [ key ] = = value ` ` , and then return a copy of the state . . . include : : / api / state / get _ when _ equality . rst"""
def _ ( snapshot ) : try : return snapshot [ key ] == value except KeyError : return False return self . when ( _ , ** when_kwargs )
def rpc_get_definition ( self , filename , source , offset ) : """Get the location of the definition for the symbol at the offset ."""
return self . _call_backend ( "rpc_get_definition" , None , filename , get_source ( source ) , offset )
def MakeZip ( self , input_dir , output_file ) : """Creates a ZIP archive of the files in the input directory . Args : input _ dir : the name of the input directory . output _ file : the name of the output ZIP archive without extension ."""
logging . info ( "Generating zip template file at %s" , output_file ) zf = zipfile . ZipFile ( output_file , "w" ) oldwd = os . getcwd ( ) os . chdir ( input_dir ) for path in [ "debian" , "rpmbuild" , "fleetspeak" ] : for root , _ , files in os . walk ( path ) : for f in files : zf . write ( os...
def _reconstruct_relative_url ( self , environ ) : """Reconstruct the relative URL of this request . This is based on the URL reconstruction code in Python PEP 333: http : / / www . python . org / dev / peps / pep - 0333 / # url - reconstruction . Rebuild the URL from the pieces available in the environment ....
url = urllib . quote ( environ . get ( 'SCRIPT_NAME' , '' ) ) url += urllib . quote ( environ . get ( 'PATH_INFO' , '' ) ) if environ . get ( 'QUERY_STRING' ) : url += '?' + environ [ 'QUERY_STRING' ] return url
def store ( self , value , context = None ) : """Converts the value to one that is safe to store on a record within the record values dictionary : param value | < variant > : return < variant >"""
if isinstance ( value , ( str , unicode ) ) : value = self . valueFromString ( value ) # store the internationalized property if self . testFlag ( self . Flags . I18n ) : if not isinstance ( value , dict ) : context = context or orb . Context ( ) return { context . locale : value } else : ...
def get_class_from_settings_from_apps ( settings_key ) : """Try and get a class from a settings path by lookin in installed apps ."""
cls_path = getattr ( settings , settings_key , None ) if not cls_path : raise NotImplementedError ( ) try : app_label = cls_path . split ( '.' ) [ - 2 ] model_name = cls_path . split ( '.' ) [ - 1 ] except ValueError : raise ImproperlyConfigured ( "{0} must be of the form " "'app_label.model_name'" . fo...
def build_footprint ( node : ast . AST , first_line_no : int ) -> Set [ int ] : """Generates a list of lines that the passed node covers , relative to the marked lines list - i . e . start of function is line 0."""
return set ( range ( get_first_token ( node ) . start [ 0 ] - first_line_no , get_last_token ( node ) . end [ 0 ] - first_line_no + 1 , ) )
def density_2d ( self , x , y , Rs , rho0 , center_x = 0 , center_y = 0 ) : """projected two dimenstional NFW profile ( kappa * Sigma _ crit ) : param R : radius of interest : type R : float / numpy array : param Rs : scale radius : type Rs : float : param rho0 : density normalization ( characteristic den...
x_ = x - center_x y_ = y - center_y R = np . sqrt ( x_ ** 2 + y_ ** 2 ) x = R / Rs Fx = self . F_ ( x ) return 2 * rho0 * Rs * Fx
def read_stat ( ) : """Mocks read _ stat as this is a Linux - specific operation ."""
return [ { "times" : { "user" : random . randint ( 0 , 999999999 ) , "nice" : random . randint ( 0 , 999999999 ) , "sys" : random . randint ( 0 , 999999999 ) , "idle" : random . randint ( 0 , 999999999 ) , "irq" : random . randint ( 0 , 999999999 ) , } } ]
def iuwt_decomposition ( in1 , scale_count , scale_adjust = 0 , mode = 'ser' , core_count = 2 , store_smoothed = False , store_on_gpu = False ) : """This function serves as a handler for the different implementations of the IUWT decomposition . It allows the different methods to be used almost interchangeably . ...
if mode == 'ser' : return ser_iuwt_decomposition ( in1 , scale_count , scale_adjust , store_smoothed ) elif mode == 'mp' : return mp_iuwt_decomposition ( in1 , scale_count , scale_adjust , store_smoothed , core_count ) elif mode == 'gpu' : return gpu_iuwt_decomposition ( in1 , scale_count , scale_adjust , s...
def _contents ( self ) : """The raw contents of the URL as fetched , this is done lazily . For non - lazy fetching this is accessed in the object constructor ."""
if self . __urldata__ is Ellipsis or self . __cache_request__ is False : if self . _file_data : # Special - case : do a multipart upload if there ' s file data self . __post__ = True boundary = "-" * 12 + str ( uuid . uuid4 ( ) ) + "$" multipart_data = '' for k , v in cgi . parse_qs ...
def ckw02 ( handle , begtim , endtim , inst , ref , segid , nrec , start , stop , quats , avvs , rates ) : """Write a type 2 segment to a C - kernel . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ckw02 _ c . html : param handle : Handle of an open CK file . : type handle : i...
handle = ctypes . c_int ( handle ) begtim = ctypes . c_double ( begtim ) endtim = ctypes . c_double ( endtim ) inst = ctypes . c_int ( inst ) ref = stypes . stringToCharP ( ref ) segid = stypes . stringToCharP ( segid ) start = stypes . toDoubleVector ( start ) stop = stypes . toDoubleVector ( stop ) rates = stypes . t...
def altitudes_encode ( self , time_boot_ms , alt_gps , alt_imu , alt_barometric , alt_optical_flow , alt_range_finder , alt_extra ) : '''The altitude measured by sensors and IMU time _ boot _ ms : Timestamp ( milliseconds since system boot ) ( uint32 _ t ) alt _ gps : GPS altitude in meters , expressed as * 100...
return MAVLink_altitudes_message ( time_boot_ms , alt_gps , alt_imu , alt_barometric , alt_optical_flow , alt_range_finder , alt_extra )
def rebuildSmooth ( self ) : """Rebuilds a smooth path based on the inputed points and set parameters for this item . : return < QPainterPath >"""
# collect the control points points = self . controlPoints ( ) # create the path path = QPainterPath ( ) if len ( points ) == 3 : x0 , y0 = points [ 0 ] x1 , y1 = points [ 1 ] xN , yN = points [ 2 ] path . moveTo ( x0 , y0 ) path . quadTo ( x1 , y1 , xN , yN ) elif len ( points ) == 4 : x0 , y0 ...
def list_courses ( self ) : """List enrolled courses . @ return : List of enrolled courses . @ rtype : [ str ]"""
reply = get_page ( self . _session , OPENCOURSE_MEMBERSHIPS , json = True ) course_list = reply [ 'linked' ] [ 'courses.v1' ] slugs = [ element [ 'slug' ] for element in course_list ] return slugs
def cache_busting_scan ( * prefixes ) : """( Re - ) generates the cache buster values for all files with the specified prefixes ."""
redis = oz . redis . create_connection ( ) pipe = redis . pipeline ( ) # Get all items that match any of the patterns . Put it in a set to # prevent duplicates . if oz . settings [ "s3_bucket" ] : bucket = oz . aws_cdn . get_bucket ( ) matches = set ( [ oz . aws_cdn . S3File ( key ) for prefix in prefixes for k...
def voice ( self ) : """: rtype : twilio . rest . pricing . v1 . voice . VoiceList"""
if self . _voice is None : self . _voice = VoiceList ( self ) return self . _voice
def create_model ( self , role = None , image = None , predictor_cls = None , serializer = None , deserializer = None , content_type = None , accept = None , vpc_config_override = vpc_utils . VPC_CONFIG_DEFAULT , ** kwargs ) : """Create a model to deploy . Args : role ( str ) : The ` ` ExecutionRoleArn ` ` IAM ...
if predictor_cls is None : def predict_wrapper ( endpoint , session ) : return RealTimePredictor ( endpoint , session , serializer , deserializer , content_type , accept ) predictor_cls = predict_wrapper role = role or self . role return Model ( self . model_data , image or self . train_image ( ) , role...
def add_sam2rnf_parser ( subparsers , subcommand , help , description , simulator_name = None ) : """Add another parser for a SAM2RNF - like command . Args : subparsers ( subparsers ) : File name of the genome from which read tuples are created ( FASTA file ) . simulator _ name ( str ) : Name of the simulator...
parser_sam2rnf = subparsers . add_parser ( subcommand , help = help , description = description ) parser_sam2rnf . set_defaults ( func = sam2rnf ) parser_sam2rnf . add_argument ( '-s' , '--sam' , type = str , metavar = 'file' , dest = 'sam_fn' , required = True , help = 'Input SAM/BAM with true (expected) alignments of...
def on_touch_up ( self , touch ) : """Return to ` ` pos _ start ` ` , but first , save my current ` ` pos ` ` into ` ` pos _ up ` ` , so that the layout knows where to put the real : class : ` board . Spot ` or : class : ` board . Pawn ` instance ."""
if touch is not self . _touch : return False self . pos_up = self . pos self . pos = self . pos_start self . _touch = None return True
def _parse_conference ( self , stats ) : """Parse the conference abbreviation for the player ' s team . The conference abbreviation is embedded within the conference name tag and should be special - parsed to extract it . Parameters stats : PyQuery object A PyQuery object containing the HTML from the play...
conference_tag = stats ( PLAYER_SCHEME [ 'conference' ] ) conference = re . sub ( r'.*/cbb/conferences/' , '' , str ( conference_tag ( 'a' ) ) ) conference = re . sub ( r'/.*' , '' , conference ) return conference
def check_command ( self , ** new_attributes ) : """Check if ' was passed a valid action in the command line and if so , executes it by passing parameters and returning the result . : return : ( Any ) Return the result of the called function , if provided , or None ."""
# let ' s parse arguments if we didn ' t before . if not self . _is_parsed : self . parse_args ( ) if not self . commands : # if we don ' t have commands raise an Exception raise exceptions . ArgParseInatorNoCommandsFound elif self . _single : # if we have a single function we get it directly func = self . ...
def _wait_for_save ( nb_name , timeout = 5 ) : """Waits for nb _ name to update , waiting up to TIMEOUT seconds . Returns True if a save was detected , and False otherwise ."""
modification_time = os . path . getmtime ( nb_name ) start_time = time . time ( ) while time . time ( ) < start_time + timeout : if ( os . path . getmtime ( nb_name ) > modification_time and os . path . getsize ( nb_name ) > 0 ) : return True time . sleep ( 0.2 ) return False
def _get_values_from_auxiliaryfile ( self , auxfile ) : """Try to return the parameter values from the auxiliary control file with the given name . Things are a little complicated here . To understand this method , you should first take a look at the | parameterstep | function ."""
try : frame = inspect . currentframe ( ) . f_back . f_back while frame : namespace = frame . f_locals try : subnamespace = { 'model' : namespace [ 'model' ] , 'focus' : self } break except KeyError : frame = frame . f_back else : raise Runt...
def delete ( self ) : """Deletes a specified courses Example Usage : : > > > import muddle > > > muddle . course ( 10 ) . delete ( )"""
params = { 'wsfunction' : 'core_course_delete_courses' , 'courseids[0]' : self . course_id } params . update ( self . request_params ) return requests . post ( self . api_url , params = params , verify = False )
def export_file ( file_path ) : """Prepend the given parameter with ` ` export ` `"""
if not os . path . isfile ( file_path ) : return error ( "Referenced file does not exist: '{}'." . format ( file_path ) ) return "export {}" . format ( file_path )
def get_pickle_protocol ( ) : """Allow configuration of the pickle protocol on a per - machine basis . This way , if you use multiple platforms with different versions of pickle , you can configure each of them to use the highest protocol supported by all of the machines that you want to be able to communic...
try : protocol_str = os . environ [ 'PYLEARN2_PICKLE_PROTOCOL' ] except KeyError : # If not defined , we default to 0 because this is the default # protocol used by cPickle . dump ( and because it results in # maximum portability ) protocol_str = '0' if protocol_str == 'pickle.HIGHEST_PROTOCOL' : return pic...
def _queryset_iterator ( qs ) : """Override default iterator to wrap returned items in a publishing sanity - checker " booby trap " to lazily raise an exception if DRAFT items are mistakenly returned and mis - used in a public context where only PUBLISHED items should be used . This booby trap is added when...
# Avoid double - processing draft items in our custom iterator when we # are in a ` PublishingQuerySet ` that is also a subclass of the # monkey - patched ` UrlNodeQuerySet ` if issubclass ( type ( qs ) , UrlNodeQuerySet ) : super_without_boobytrap_iterator = super ( UrlNodeQuerySet , qs ) else : super_without_...
def get_nowait ( self ) : """Returns a value from the queue without waiting . Raises ` ` QueueEmpty ` ` if no values are available right now ."""
new_get = Future ( ) with self . _lock : if not self . _get . done ( ) : raise QueueEmpty get , self . _get = self . _get , new_get hole = get . result ( ) if not hole . done ( ) : # Restore the unfinished hole . new_get . set_result ( hole ) raise QueueEmpty node = hole . result ( ) value = nod...
def save ( self , filename = None ) : """Saves the runtime configuration to disk . Parameters filename : str or None , default = None writeable path to configuration filename . If None , use default location and filename ."""
if not filename : filename = self . DEFAULT_CONFIG_FILE_NAME else : filename = str ( filename ) # try to extract the path from filename and use is as cfg _ dir head , tail = os . path . split ( filename ) if head : self . _cfg_dir = head # we are search for . cfg files in cfg _ dir so ma...
def locale ( qsetting = '' ) : """Get the name of the currently active locale . : param qsetting : String to specify the QSettings . By default , use empty string . : type qsetting : str : returns : Name of the locale e . g . ' id ' : rtype : str"""
override_flag = QSettings ( qsetting ) . value ( 'locale/overrideFlag' , True , type = bool ) default = 'en_US' if override_flag : locale_name = QSettings ( qsetting ) . value ( 'locale/userLocale' , default , type = str ) else : # noinspection PyArgumentList locale_name = QLocale . system ( ) . name ( ) if loc...
def field_to_dict ( fields ) : """Build dictionnary which dependancy for each field related to " root " fields = [ " toto " , " toto _ _ tata " , " titi _ _ tutu " ] dico = { " toto " : { EMPTY _ DICT , " tata " : EMPTY _ DICT " titi " : { " tutu " : EMPTY _ DICT EMPTY _ DICT is useful because we do...
field_dict = { } for field in fields : d_tmp = field_dict for part in field . split ( LOOKUP_SEP ) [ : - 1 ] : d_tmp = d_tmp . setdefault ( part , { } ) d_tmp = d_tmp . setdefault ( field . split ( LOOKUP_SEP ) [ - 1 ] , deepcopy ( EMPTY_DICT ) ) . update ( deepcopy ( EMPTY_DICT ) ) return field_dic...
def http_sa_http_server_http_vrf_cont_use_vrf_http_vrf_shutdown ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) http_sa = ET . SubElement ( config , "http-sa" , xmlns = "urn:brocade.com:mgmt:brocade-http" ) http = ET . SubElement ( http_sa , "http" ) server = ET . SubElement ( http , "server" ) http_vrf_cont = ET . SubElement ( server , "http-vrf-cont" ) use_vrf = ET . SubElement ( http_vrf_con...
def add_content_ratings ( self , app_id , submission_id , security_code ) : """Add content ratings to the web app identified by by ` ` app _ id ` ` , using the specified submission id and security code . : returns : HttpResponse : * status _ code ( int ) 201 is successful"""
url = self . url ( 'content_ratings' ) % app_id return self . conn . fetch ( 'POST' , url , { 'submission_id' : '%s' % submission_id , 'security_code' : '%s' % security_code } )
def get_jsapi_signature ( self , noncestr , ticket , timestamp , url ) : """获取 JSAPI 签名 https : / / work . weixin . qq . com / api / doc # 90001/90144/90539 / 签名算法 / : param noncestr : nonce string : param ticket : JS - SDK ticket : param timestamp : 时间戳 : param url : URL : return : 签名"""
data = [ 'noncestr={noncestr}' . format ( noncestr = noncestr ) , 'jsapi_ticket={ticket}' . format ( ticket = ticket ) , 'timestamp={timestamp}' . format ( timestamp = timestamp ) , 'url={url}' . format ( url = url ) , ] signer = WeChatSigner ( delimiter = b'&' ) signer . add_data ( * data ) return signer . signature
def list_streams ( self , types = [ ] , inactive = False ) : '''list user streams'''
req_hook = 'pod/v1/streams/list' json_query = { "streamTypes" : types , "includeInactiveStreams" : inactive } req_args = json . dumps ( json_query ) status_code , response = self . __rest__ . POST_query ( req_hook , req_args ) self . logger . debug ( '%s: %s' % ( status_code , response ) ) return status_code , response
def _get_dir ( toml_config_setting , sawtooth_home_dir , windows_dir , default_dir ) : """Determines the directory path based on configuration . Arguments : toml _ config _ setting ( str ) : The name of the config setting related to the directory which will appear in path . toml . sawtooth _ home _ dir ( st...
conf_file = os . path . join ( _get_config_dir ( ) , 'path.toml' ) if os . path . exists ( conf_file ) : with open ( conf_file ) as fd : raw_config = fd . read ( ) toml_config = toml . loads ( raw_config ) if toml_config_setting in toml_config : return toml_config [ toml_config_setting ] if ...
def randomize ( self ) : """Randomize this immediate to a legal value"""
self . value = randint ( self . min ( ) , self . max ( ) ) if self . lsb0 : self . value = self . value - ( self . value % 2 )
def wheels ( opts , whitelist = None , context = None ) : '''Returns the wheels modules'''
if context is None : context = { } return LazyLoader ( _module_dirs ( opts , 'wheel' ) , opts , tag = 'wheel' , whitelist = whitelist , pack = { '__context__' : context } , )
def files ( self ) : """Returns the URLs of all files attached to posts in the thread ."""
if self . topic . has_file : yield self . topic . file . file_url for reply in self . replies : if reply . has_file : yield reply . file . file_url
def create_login_profile ( user_name , password , region = None , key = None , keyid = None , profile = None ) : '''Creates a login profile for the specified user , give the user the ability to access AWS services and the AWS Management Console . . . versionadded : : 2015.8.0 CLI Example : . . code - block ...
user = get_user ( user_name , region , key , keyid , profile ) if not user : log . error ( 'IAM user %s does not exist' , user_name ) return False conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile ) try : info = conn . create_login_profile ( user_name , password ) log . ...
def jpgMin ( file , force = False ) : """Try to optimise a JPG file . The original will be saved at the same place with ' . original ' appended to its name . Once a . original exists the function will ignore this file unless force is True ."""
if not os . path . isfile ( file + '.original' ) or force : data = _read ( file , 'rb' ) _save ( file + '.original' , data , 'w+b' ) print 'Optmising JPG {} - {:.2f}kB' . format ( file , len ( data ) / 1024.0 ) , url = 'http://jpgoptimiser.com/optimise' parts , headers = encode_multipart ( { } , { '...
def pack_chunk ( tag , data ) : """Pack a PNG chunk for serializing to disk"""
to_check = tag + data return ( struct . pack ( b"!I" , len ( data ) ) + to_check + struct . pack ( b"!I" , zlib . crc32 ( to_check ) & 0xFFFFFFFF ) )
def plan_results ( self , project_key , plan_key , expand = None , favourite = False , clover_enabled = False , label = None , issue_key = None , start_index = 0 , max_results = 25 ) : """Get Plan results : param project _ key : : param plan _ key : : param expand : : param favourite : : param clover _ en...
return self . results ( project_key , plan_key , expand = expand , favourite = favourite , clover_enabled = clover_enabled , label = label , issue_key = issue_key , start_index = start_index , max_results = max_results )
def template_to_dict_iter_debug ( elm ) : """Print expanded element on stdout for debugging"""
if elm . text is not None : print ( " <%s>%s</%s>" % ( elm . tag , elm . text , elm . tag ) , end = '' ) if elm . tail is not None : print ( elm . tail ) else : print ( ) else : if elm . tail is not None : print ( " <%s>%s" % ( elm . tag , elm . tail ) ) else : ...
def get_attr_value ( self , name ) : '''Retrieve the ` ` value ` ` for the attribute ` ` name ` ` . The ` ` name ` ` can be nested following the : ref : ` double underscore < tutorial - underscore > ` notation , for example ` ` group _ _ name ` ` . If the attribute is not available it raises : class : ` Attri...
if name in self . _meta . dfields : return self . _meta . dfields [ name ] . get_value ( self ) elif not name . startswith ( '__' ) and JSPLITTER in name : bits = name . split ( JSPLITTER ) fname = bits [ 0 ] if fname in self . _meta . dfields : return self . _meta . dfields [ fname ] . get_valu...
def register_extension_method ( ext , base , * args , ** kwargs ) : """Register the given extension method as a public attribute of the given base . README : The expected protocol here is that the given extension method is an unbound function . It will be bound to the specified base as a method , and then set a...
bound_method = create_bound_method ( ext . plugin , base ) setattr ( base , ext . name . lstrip ( '_' ) , bound_method )
def secure ( view ) : """Authentication decorator for views . If DEBUG is on , we serve the view without authenticating . Default is ' django . contrib . auth . decorators . login _ required ' . Can also be ' django . contrib . admin . views . decorators . staff _ member _ required ' or a custom decorator ....
auth_decorator = import_class ( settings . AUTH_DECORATOR ) return ( view if project_settings . DEBUG else method_decorator ( auth_decorator , name = 'dispatch' ) ( view ) )
def ancestors ( self , recurs = True , context = None ) : """Iterate over the base classes in prefixed depth first order . : param recurs : Whether to recurse or return direct ancestors only . : type recurs : bool : returns : The base classes : rtype : iterable ( NodeNG )"""
# FIXME : should be possible to choose the resolution order # FIXME : inference make infinite loops possible here yielded = { self } if context is None : context = contextmod . InferenceContext ( ) if not self . bases and self . qname ( ) != "builtins.object" : yield builtin_lookup ( "object" ) [ 1 ] [ 0 ] ...
def write ( gctoo_object , out_file_name , convert_back_to_neg_666 = True , gzip_compression_level = 6 , max_chunk_kb = 1024 , matrix_dtype = numpy . float32 ) : """Writes a GCToo instance to specified file . Input : - gctoo _ object ( GCToo ) : A GCToo instance . - out _ file _ name ( str ) : file name to wr...
# make sure out file has a . gctx suffix gctx_out_name = add_gctx_to_out_name ( out_file_name ) # open an hdf5 file to write to hdf5_out = h5py . File ( gctx_out_name , "w" ) # write version write_version ( hdf5_out ) # write src write_src ( hdf5_out , gctoo_object , gctx_out_name ) # set chunk size for data matrix ele...
def ungroup_array2singles ( input , ** params ) : """Creates list of objects from array of singles : param input : list of strings or ints : param params : : return :"""
PARAM_FIELD_KEY = 'field.key' PARAM_FIELD_ARRAY = 'field.array' PARAM_FIELD_SINGLE = 'field.single' res = [ ] field_key = params . get ( PARAM_FIELD_KEY ) if PARAM_FIELD_KEY in params else None field_array = params . get ( PARAM_FIELD_ARRAY ) field_single = params . get ( PARAM_FIELD_SINGLE ) for row in input : if ...
def write_key ( self , name , value , comment = "" ) : """Write the input value to the header parameters name : string Name of keyword to write / update value : scalar Value to write , can be string float or integer type , including numpy scalar types . comment : string , optional An optional commen...
if value is None : self . _FITS . write_undefined_key ( self . _ext + 1 , str ( name ) , str ( comment ) ) elif isinstance ( value , bool ) : if value : v = 1 else : v = 0 self . _FITS . write_logical_key ( self . _ext + 1 , str ( name ) , v , str ( comment ) ) elif isinstance ( value , ...
def register_function ( self , specification , function , scope = None ) : """Shortcut for creating and registering a : py : class : ` wiring . providers . FunctionProvider ` ."""
self . register_provider ( specification , FunctionProvider ( function , scope = scope ) )
def read_wait_cell ( self ) : """Read the value of the cell holding the ' wait ' value , Returns the int value of whatever it has , or None if the cell doesn ' t exist ."""
table_state = self . bt_table . read_row ( TABLE_STATE , filter_ = bigtable_row_filters . ColumnRangeFilter ( METADATA , WAIT_CELL , WAIT_CELL ) ) if table_state is None : utils . dbg ( 'No waiting for new games needed; ' 'wait_for_game_number column not in table_state' ) return None value = table_state . cell_...
def _getBackend ( path = None , key = None ) : """key : a function ( backend - > bool ) signaling if the backend is suitable for a specific task example # Get available backends which can read in chunks > > > backend = _ getBackend ( ' file . flac ' , key = lambda backend : backend . can _ read _ chunked )"...
ext = _os . path . splitext ( path ) [ 1 ] . lower ( ) if path else None backends = _getBackends ( ) if key : backends = [ b for b in backends if key ( b ) ] if ext : backends = [ b for b in backends if ext in b . filetypes ] if backends : return min ( backends , key = lambda backend : backend . priority ) ...