signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def finish_statistics ( self ) : """Prepare / modify data for plotting"""
# params = self . stat . setup _ params ( self . data ) self . stat . finish_layer ( self . data , self . stat . params )
def get_data ( self , size = None , addr = None ) : '''Gets data for incoming stream'''
# readback memory offset if addr is None : addr = self . _mem_bytes if size and self . _mem_bytes < size : raise ValueError ( 'Size is too big' ) if size is None : return self . _intf . read ( self . _conf [ 'base_addr' ] + self . _spi_mem_offset + addr , self . _mem_bytes ) else : return self . _intf ....
def _single_load ( self , addr , offset , size , inspect = True , events = True ) : """Performs a single load ."""
try : d = self . _contents [ addr ] except KeyError : d = self . _handle_uninitialized_read ( addr , inspect = inspect , events = events ) self . _contents [ addr ] = d if offset == 0 and size == self . width : return d else : return d . get_bytes ( offset , size )
def load ( raw_bytes ) : """given a bytes object , should return a base python data structure that represents the object ."""
try : return yaml . load ( raw_bytes ) except yaml . scanner . ScannerError as e : raise SerializationException ( str ( e ) )
def copy ( self ) : """Make a deep copy of this object . Example : : > > > c2 = c . copy ( )"""
vec1 = np . copy ( self . scoef1 . _vec ) vec2 = np . copy ( self . scoef2 . _vec ) return VectorCoefs ( vec1 , vec2 , self . nmax , self . mmax )
def patch_namespaced_role ( self , name , namespace , body , ** kwargs ) : """partially update the specified Role This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . patch _ namespaced _ role ( name , namespace , ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . patch_namespaced_role_with_http_info ( name , namespace , body , ** kwargs ) else : ( data ) = self . patch_namespaced_role_with_http_info ( name , namespace , body , ** kwargs ) return data
def copy ( self ) : """Get a deep copy of this comparision line . : return : The leaf ( " downmost " ) object of the copy ."""
orig = self . all_up result = copy ( orig ) # copy top level while orig is not None : result . additional = copy ( orig . additional ) if orig . down is not None : # copy and create references to the following level # copy following level result . down = copy ( orig . down ) if orig . t1_chi...
def __get_conn ( ** kwargs ) : '''Detects what type of dom this node is and attempts to connect to the correct hypervisor via libvirt . : param connection : libvirt connection URI , overriding defaults : param username : username to connect with , overriding defaults : param password : password to connect w...
# This has only been tested on kvm and xen , it needs to be expanded to # support all vm layers supported by libvirt # Connection string works on bhyve , but auth is not tested . username = kwargs . get ( 'username' , None ) password = kwargs . get ( 'password' , None ) conn_str = kwargs . get ( 'connection' , None ) i...
def tostr ( self , object , indent = - 2 ) : """get s string representation of object"""
history = [ ] return self . process ( object , history , indent )
def list_all ( self , per_page = 10 , omit = None ) : """List all groups . Since the order of groups is determined by recent activity , this is the recommended way to obtain a list of all groups . See : func : ` ~ groupy . api . groups . Groups . list ` for details about ` ` omit ` ` . : param int per _ pag...
return self . list ( per_page = per_page , omit = omit ) . autopage ( )
def delete_downloads ( ) : """Delete all downloaded examples to free space or update the files"""
shutil . rmtree ( vtki . EXAMPLES_PATH ) os . makedirs ( vtki . EXAMPLES_PATH ) return True
async def upload ( self , files : Sequence [ Union [ str , Path ] ] , basedir : Union [ str , Path ] = None , show_progress : bool = False ) : '''Uploads the given list of files to the compute session . You may refer them in the batch - mode execution or from the code executed in the server afterwards . : par...
params = { } if self . owner_access_key : params [ 'owner_access_key' ] = self . owner_access_key base_path = ( Path . cwd ( ) if basedir is None else Path ( basedir ) . resolve ( ) ) files = [ Path ( file ) . resolve ( ) for file in files ] total_size = 0 for file_path in files : total_size += file_path . stat...
def channels_unarchive ( self , room_id , ** kwargs ) : """Unarchives a channel ."""
return self . __call_api_post ( 'channels.unarchive' , roomId = room_id , kwargs = kwargs )
def raise_ ( exception = ABSENT , * args , ** kwargs ) : """Raise ( or re - raises ) an exception . : param exception : Exception object to raise , or an exception class . In the latter case , remaining arguments are passed to the exception ' s constructor . If omitted , the currently handled exception is r...
if exception is ABSENT : raise else : if inspect . isclass ( exception ) : raise exception ( * args , ** kwargs ) else : if args or kwargs : raise TypeError ( "can't pass arguments along with " "exception object to raise_()" ) raise exception
def encrypt ( self , pubkey : str , nonce : Union [ str , bytes ] , text : Union [ str , bytes ] ) -> str : """Encrypt message text with the public key of the recipient and a nonce The nonce must be a 24 character string ( you can use libnacl . utils . rand _ nonce ( ) to get one ) and unique for each encrypted...
text_bytes = ensure_bytes ( text ) nonce_bytes = ensure_bytes ( nonce ) recipient_pubkey = PublicKey ( pubkey ) crypt_bytes = libnacl . public . Box ( self , recipient_pubkey ) . encrypt ( text_bytes , nonce_bytes ) return Base58Encoder . encode ( crypt_bytes [ 24 : ] )
def flattened ( self ) : """Returns a flattened version of the parsed whois data"""
parsed = self [ 'parsed_whois' ] flat = OrderedDict ( ) for key in ( 'domain' , 'created_date' , 'updated_date' , 'expired_date' , 'statuses' , 'name_servers' ) : value = parsed [ key ] flat [ key ] = ' | ' . join ( value ) if type ( value ) in ( list , tuple ) else value registrar = parsed . get ( 'registrar' ...
def get_adaptive_threshold ( threshold_method , image , threshold , mask = None , adaptive_window_size = 10 , ** kwargs ) : """Given a global threshold , compute a threshold per pixel Break the image into blocks , computing the threshold per block . Afterwards , constrain the block threshold to . 7 T < t < 1.5 ...
# for the X and Y direction , find the # of blocks , given the # size constraints image_size = np . array ( image . shape [ : 2 ] , dtype = int ) nblocks = image_size // adaptive_window_size # Use a floating point block size to apportion the roundoff # roughly equally to each block increment = ( np . array ( image_size...
def parse_template ( self , template , ** context ) : """To parse a template and return all the blocks"""
required_blocks = [ "subject" , "body" ] optional_blocks = [ "text_body" , "html_body" , "return_path" , "format" ] if self . template_context : context = dict ( self . template_context . items ( ) + context . items ( ) ) blocks = self . template . render_blocks ( template , ** context ) for rb in required_blocks :...
def text_color ( self , value ) : """Setter for * * self . _ _ text _ color * * attribute . : param value : Attribute value . : type value : int or QColor"""
if value is not None : assert type ( value ) in ( Qt . GlobalColor , QColor ) , "'{0}' attribute: '{1}' type is not 'int' or 'QColor'!" . format ( "text_color" , value ) self . __text_color = value
def bind_tcp_socket ( address ) : """Takes ( host , port ) and returns ( socket _ object , ( host , port ) ) . If the passed - in port is None , bind an unused port and return it ."""
host , port = address for res in set ( socket . getaddrinfo ( host , port , socket . AF_INET , socket . SOCK_STREAM , 0 , socket . AI_PASSIVE ) ) : family , socktype , proto , _ , sock_addr = res sock = socket . socket ( family , socktype , proto ) if os . name != 'nt' : sock . setsockopt ( socket ....
def delta_e_cie1994 ( lab_color_vector , lab_color_matrix , K_L = 1 , K_C = 1 , K_H = 1 , K_1 = 0.045 , K_2 = 0.015 ) : """Calculates the Delta E ( CIE1994 ) of two colors . K _ l : 0.045 graphic arts 0.048 textiles K _ 2: 0.015 graphic arts 0.014 textiles K _ L : 1 default 2 textiles"""
C_1 = numpy . sqrt ( numpy . sum ( numpy . power ( lab_color_vector [ 1 : ] , 2 ) ) ) C_2 = numpy . sqrt ( numpy . sum ( numpy . power ( lab_color_matrix [ : , 1 : ] , 2 ) , axis = 1 ) ) delta_lab = lab_color_vector - lab_color_matrix delta_L = delta_lab [ : , 0 ] . copy ( ) delta_C = C_1 - C_2 delta_lab [ : , 0 ] = de...
def default_to_hashed_rows ( self , default = None ) : """Gets the current setting with no parameters , sets it if a boolean is passed in : param default : the value to set : return : the current value , or new value if default is set to True or False"""
if default is not None : self . _default_to_hashed_rows = ( default is True ) return self . _default_to_hashed_rows
def MaxSpeed ( self , speed ) : 'Setup of maximum speed'
spi . SPI_write_byte ( self . CS , 0x07 ) # Max Speed setup spi . SPI_write_byte ( self . CS , 0x00 ) spi . SPI_write_byte ( self . CS , speed )
def _get_log_rho_metropolis_hastings ( self , proposed_point , proposed_eval ) : """calculate log ( metropolis ratio times hastings factor )"""
return self . _get_log_rho_metropolis ( proposed_point , proposed_eval ) - self . proposal . evaluate ( proposed_point , self . current ) + self . proposal . evaluate ( self . current , proposed_point )
def get ( self , name_or_klass ) : """Get a extension by name ( or class ) . : param name _ or _ klass : The name or the class of the extension to get : type name _ or _ klass : str or type : rtype : spyder . api . mode . EditorExtension"""
if not isinstance ( name_or_klass , str ) : name_or_klass = name_or_klass . __name__ return self . _extensions [ name_or_klass ]
def setFontFamily ( self , family ) : """Sets the current font family to the inputed family . : param family | < str >"""
self . blockSignals ( True ) self . editor ( ) . setFontFamily ( family ) self . blockSignals ( False )
def getNode ( self , name , ** context ) : """Return tree node found by name"""
if name == self . name : return self else : return self . getBranch ( name , ** context ) . getNode ( name , ** context )
def rating ( self ) : """Returns the Place ' s rating , from 0.0 to 5.0 , based on user reviews . This method will return None for places that have no rating ."""
if self . _rating == '' and self . details != None and 'rating' in self . details : self . _rating = self . details [ 'rating' ] return self . _rating
def fetch_logs ( self , max_rows = 1024 , orientation = None ) : """Mocked . Retrieve the logs produced by the execution of the query . Can be called multiple times to fetch the logs produced after the previous call . : returns : list < str > : raises : ` ` ProgrammingError ` ` when no query has been starte...
from pyhive import hive from TCLIService import ttypes from thrift import Thrift orientation = orientation or ttypes . TFetchOrientation . FETCH_NEXT try : req = ttypes . TGetLogReq ( operationHandle = self . _operationHandle ) logs = self . _connection . client . GetLog ( req ) . log return logs # raised i...
def send_iq_and_wait_for_reply ( self , iq , * , timeout = None ) : """Send an IQ stanza ` iq ` and wait for the response . If ` timeout ` is not : data : ` None ` , it must be the time in seconds for which to wait for a response . If the response is a ` ` " result " ` ` IQ , the value of the : attr : ` ~ a...
warnings . warn ( r"send_iq_and_wait_for_reply is deprecated and will be removed in" r" 1.0" , DeprecationWarning , stacklevel = 1 , ) return ( yield from self . send ( iq , timeout = timeout ) )
def linkage ( self ) : """Return the linkage of this cursor ."""
if not hasattr ( self , '_linkage' ) : self . _linkage = conf . lib . clang_getCursorLinkage ( self ) return LinkageKind . from_id ( self . _linkage )
def get_uncond_agent ( agent ) : """Construct the unconditional state of an Agent . The unconditional Agent is a copy of the original agent but without any bound conditions and modification conditions . Mutation conditions , however , are preserved since they are static ."""
agent_uncond = ist . Agent ( _n ( agent . name ) , mutations = agent . mutations ) return agent_uncond
def CallNtpdate ( logger ) : """Sync clock using ntpdate . Args : logger : logger object , used to write to SysLog and serial port ."""
ntpd_inactive = subprocess . call ( [ 'service' , 'ntpd' , 'status' ] ) try : if not ntpd_inactive : subprocess . check_call ( [ 'service' , 'ntpd' , 'stop' ] ) subprocess . check_call ( 'ntpdate `awk \'$1=="server" {print $2}\' /etc/ntp.conf`' , shell = True ) if not ntpd_inactive : subproc...
def iterateCreateFromSeqs ( startingColumn , fmStarts , fmDeltas , allFirstCounts , allBwtCounts , cOffset , totalCounts , numValidChars , mergedFN , seqFNPrefix , offsetFN , insertFNs , numProcs , areUniform , depth , logger ) : '''This function is the actual series of iterations that a BWT creation will perform ....
bwt = np . load ( mergedFN , 'r+' ) column = startingColumn newInserts = True while newInserts : st = time . time ( ) # iterate through the sorted keys keySort = sorted ( fmStarts . keys ( ) ) for i , key in enumerate ( keySort ) : # all deltas get copied for c2 in xrange ( 0 , numValidChars ) :...
def render_local_template ( service_name , environment , repo_root , template_file ) : """Render a given service ' s template for a given environment and return it"""
cmd = 'cd {} && ef-cf {} {} --devel --verbose' . format ( repo_root , template_file , environment ) p = subprocess . Popen ( cmd , shell = True , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) stdout , stderr = p . communicate ( ) if p . returncode != 0 : stderr = indentify ( '\n{}' . format ( stderr ) )...
def bind ( self , data_shapes , label_shapes = None , for_training = True , inputs_need_grad = False , force_rebind = False , shared_module = None , grad_req = 'write' ) : """Binding for a ` BucketingModule ` means setting up the buckets and binding the executor for the default bucket key . Executors correspondin...
# in case we already initialized params , keep it if self . params_initialized : arg_params , aux_params = self . get_params ( ) # force rebinding is typically used when one want to switch from # training to prediction phase . if force_rebind : self . _reset_bind ( ) if self . binded : self . logger . warni...
def request_location ( cls , text , * , resize = None , single_use = None , selective = None ) : """Creates a new button that will request the user ' s location upon being clicked . ` ` resize ` ` , ` ` single _ use ` ` and ` ` selective ` ` are documented in ` text ` ."""
return cls ( types . KeyboardButtonRequestGeoLocation ( text ) , resize = resize , single_use = single_use , selective = selective )
def is_critical_flow ( P1 , P2 , k ) : r'''Determines if a flow of a fluid driven by pressure gradient P1 - P2 is critical , for a fluid with the given isentropic coefficient . This function calculates critical flow pressure , and checks if this is larger than P2 . If so , the flow is critical and choked . ...
Pcf = P_critical_flow ( P1 , k ) return Pcf > P2
def get_projected_plot ( self , selection , mode = 'rgb' , interpolate_factor = 4 , circle_size = 150 , projection_cutoff = 0.001 , zero_to_efermi = True , ymin = - 6. , ymax = 6. , width = None , height = None , vbm_cbm_marker = False , ylabel = 'Energy (eV)' , dpi = 400 , plt = None , dos_plotter = None , dos_options...
if mode == 'rgb' and len ( selection ) > 3 : raise ValueError ( 'Too many elements/orbitals specified (max 3)' ) elif mode == 'solo' and dos_plotter : raise ValueError ( 'Solo mode plotting with DOS not supported' ) if dos_plotter : plt = pretty_subplot ( 1 , 2 , width , height , sharex = False , dpi = dpi ...
def __delete_action ( self , revision ) : """Handle a delete action to a partiular master id via the revision . : param dict revision : : return :"""
delete_response = yield self . collection . delete ( revision . get ( "master_id" ) ) if delete_response . get ( "n" ) == 0 : raise DocumentRevisionDeleteFailed ( )
def _check_if_zipped ( self , path ) : """Checks if the filename shows a tar / zip file"""
filename = get_file ( path ) . split ( '.' ) if filename [ - 1 ] in [ 'bz' , 'bz2' , 'gz' ] : return True return False
def create_utilities ( self ) : """Create utitilies stack ."""
self . create_stack ( self . utilities_name , 'amazon-utilities.yaml' , parameters = define_parameters ( Subnets = self . subnet_ids , NodeSecurityGroup = self . node_security_group ) )
def enable_fundamental_type_wrappers ( self ) : """If a type is a int128 , a long _ double _ t or a void , some placeholders need to be in the generated code to be valid ."""
# 2015-01 reactivating header templates # log . warning ( ' enable _ fundamental _ type _ wrappers deprecated - replaced by generate _ headers ' ) # return # FIXME ignore self . enable_fundamental_type_wrappers = lambda : True import pkgutil headers = pkgutil . get_data ( 'ctypeslib' , 'data/fundamental_type_name.tpl' ...
def _get_val ( self , soln , r , c ) : """Return the string value for a solution coordinate ."""
for v in range ( 1 , 10 ) : if soln [ self . X [ r , c , v ] ] : return DIGITS [ v - 1 ] return "X"
def absolute_redirect_n_times ( n ) : """Absolutely 302 Redirects n times . tags : - Redirects parameters : - in : path name : n type : int produces : - text / html responses : 302: description : A redirection ."""
assert n > 0 if n == 1 : return redirect ( url_for ( "view_get" , _external = True ) ) return _redirect ( "absolute" , n , True )
def _set_debug_level ( self , debug_level ) : """: type debug _ level : int , between 0-2 : param debug _ level : configure verbosity of log"""
mapping = { 0 : logging . ERROR , 1 : logging . INFO , 2 : logging . DEBUG , } self . setLevel ( mapping [ min ( debug_level , 2 ) ] , )
def id_request ( self , device_id ) : """Get the device for the ID . ID request can return device type ( cat / subcat ) , firmware ver , etc . Cat is status [ ' is _ high ' ] , sub cat is status [ ' id _ mid ' ]"""
self . logger . info ( "\nid_request for device %s" , device_id ) device_id = device_id . upper ( ) self . direct_command ( device_id , '10' , '00' ) sleep ( 2 ) status = self . get_buffer_status ( device_id ) if not status : sleep ( 1 ) status = self . get_buffer_status ( device_id ) return status
def get_disease ( self , disease_name = None , disease_id = None , definition = None , parent_ids = None , tree_numbers = None , parent_tree_numbers = None , slim_mapping = None , synonym = None , alt_disease_id = None , limit = None , as_df = False ) : """Get diseases : param bool as _ df : if set to True result...
q = self . session . query ( models . Disease ) if disease_name : q = q . filter ( models . Disease . disease_name . like ( disease_name ) ) if disease_id : q = q . filter ( models . Disease . disease_id == disease_id ) if definition : q = q . filter ( models . Disease . definition . like ( definition ) ) i...
def Grashof ( L , beta , T1 , T2 = 0 , rho = None , mu = None , nu = None , g = g ) : r'''Calculates Grashof number or ` Gr ` for a fluid with the given properties , temperature difference , and characteristic length . . . math : : Gr = \ frac { g \ beta ( T _ s - T _ \ infty ) L ^ 3 } { \ nu ^ 2} = \ frac ...
if rho and mu : nu = mu / rho elif not nu : raise Exception ( 'Either density and viscosity, or dynamic viscosity, \ is needed' ) return g * beta * abs ( T2 - T1 ) * L ** 3 / nu ** 2
def plot_joint ( data , var_names = None , coords = None , figsize = None , textsize = None , kind = "scatter" , gridsize = "auto" , contour = True , fill_last = True , joint_kwargs = None , marginal_kwargs = None , ) : """Plot a scatter or hexbin of two variables with their respective marginals distributions . P...
valid_kinds = [ "scatter" , "kde" , "hexbin" ] if kind not in valid_kinds : raise ValueError ( ( "Plot type {} not recognized." "Plot type must be in {}" ) . format ( kind , valid_kinds ) ) data = convert_to_dataset ( data , group = "posterior" ) if coords is None : coords = { } var_names = _var_names ( var_nam...
def opensignals_kwargs ( obj ) : """Brief Function used to automatically apply the OpenSignals graphical style to the toolbar of Bokeh grid plots . Description Bokeh grid plots have numerous options in order to personalise the visual aspect and functionalities of plots . OpenSignals uses a specific graphica...
out = None if obj == "figure" : out = { } elif obj == "gridplot" : out = { "toolbar_options" : { "logo" : None } , "sizing_mode" : 'scale_width' } elif obj == "line" : out = { "line_width" : 2 , "line_color" : opensignals_color_pallet ( ) } return out
def make_block_same_class ( self , values , placement = None , ndim = None , dtype = None ) : """Wrap given values in a block of same type as self ."""
if dtype is not None : # issue 19431 fastparquet is passing this warnings . warn ( "dtype argument is deprecated, will be removed " "in a future release." , DeprecationWarning ) if placement is None : placement = self . mgr_locs return make_block ( values , placement = placement , ndim = ndim , klass = self . _...
def pretty_str ( p , decimal_places = 2 , print_zero = True , label_columns = False ) : '''Pretty - print a matrix or vector .'''
if len ( p . shape ) == 1 : return vector_str ( p , decimal_places , print_zero ) if len ( p . shape ) == 2 : return matrix_str ( p , decimal_places , print_zero , label_columns ) raise Exception ( 'Invalid array with shape {0}' . format ( p . shape ) )
def cal_pth ( self , v , temp ) : """calculate thermal pressure : param v : unit - cell volume in A ^ 3 : param temp : temperature in K : return : thermal pressure in GPa"""
if ( self . eqn_th is None ) or ( self . params_th is None ) : return np . zeros_like ( v ) params = self . _set_params ( self . params_th ) return func_th [ self . eqn_th ] ( v , temp , * params , self . n , self . z , t_ref = self . t_ref , three_r = self . three_r )
def cacheOnSameArgs ( timeout = None ) : """Caches the return of the function until the the specified time has elapsed or the arguments change . If timeout is None it will not be considered ."""
if isinstance ( timeout , int ) : timeout = datetime . timedelta ( 0 , timeout ) def decorator ( f ) : _cache = [ None ] def wrapper ( * args , ** kwargs ) : if _cache [ 0 ] is not None : cached_ret , dt , cached_args , cached_kwargs = _cache [ 0 ] if ( timeout is not None an...
def main ( ) : """Main entry point - used for command line call"""
args = _parse_arg ( CountryConverter ( ) . valid_class ) coco = CountryConverter ( additional_data = args . additional_data ) converted_names = coco . convert ( names = args . names , src = args . src , to = args . to , enforce_list = False , not_found = args . not_found ) print ( args . output_sep . join ( [ str ( etr...
def filter_not_empty_values ( value ) : """Returns a list of non empty values or None"""
if not value : return None data = [ x for x in value if x ] if not data : return None return data
def find_insertion_line ( self , code ) : """Guess at what line the new import should be inserted"""
match = re . search ( r'^(def|class)\s+' , code ) if match is not None : code = code [ : match . start ( ) ] try : pymodule = libutils . get_string_module ( self . project , code ) except exceptions . ModuleSyntaxError : return 1 testmodname = '__rope_testmodule_rope' importinfo = importutils . NormalImport...
def show_item_bottom_border ( self , item_text , flag ) : """Sets a flag that will show a bottom border for an item with the specified text . : param item _ text : the text property of the item : param flag : boolean specifying if the border should be shown ."""
if flag : self . __bottom_border_dict [ item_text ] = True else : self . __bottom_border_dict . pop ( item_text , None )
def gap_subset ( self , interval : Interval , flexibility : int = 2 ) -> "IntervalList" : """Returns an IntervalList that ' s a subset of this one , only containing * gaps * between intervals that meet the interval criterion . See : meth : ` subset ` for the meaning of parameters ."""
return self . gaps ( ) . subset ( interval , flexibility )
def save ( self , * args , ** kwargs ) : """* * uid * * : : code : ` division _ cycle _ ballotmeasure : { number } `"""
self . uid = '{}_{}_ballotmeasure:{}' . format ( self . division . uid , self . election_day . uid , self . number ) super ( BallotMeasure , self ) . save ( * args , ** kwargs )
def start_capture ( self , adapter_number , port_number , output_file , data_link_type = "DLT_EN10MB" ) : """Starts a packet capture . : param adapter _ number : adapter number : param port _ number : port number : param output _ file : PCAP destination file for the capture : param data _ link _ type : PCAP...
try : adapter = self . _adapters [ adapter_number ] except IndexError : raise IOUError ( 'Adapter {adapter_number} does not exist on IOU "{name}"' . format ( name = self . _name , adapter_number = adapter_number ) ) if not adapter . port_exists ( port_number ) : raise IOUError ( "Port {port_number} does not...
def get_form ( self , request , obj = None , ** kwargs ) : """Use special form during user creation"""
defaults = { } if obj is None : defaults [ 'form' ] = self . add_form defaults . update ( kwargs ) return super ( SettingsAdmin , self ) . get_form ( request , obj , ** defaults )
def append ( self , vals : list , index = None ) : """Append a row to the main dataframe : param vals : list of the row values to add : type vals : list : param index : index key , defaults to None : param index : any , optional : example : ` ` ds . append ( [ 0 , 2 , 2 , 3 , 4 ] ) ` `"""
try : self . df = self . df . loc [ len ( self . df . index ) ] = vals except Exception as e : self . err ( e , self . append , "Can not append row" ) return self . ok ( "Row added to dataframe" )
def call ( self , params ) : """Make an API call to the wiki . * params * is a dictionary of query string arguments . For example , to get basic information about the wiki , run : > > > wiki . call ( { ' action ' : ' query ' , ' meta ' : ' siteinfo ' } ) which would make a call to ` ` http : / / domain / w ...
return json . loads ( self . _fetch_http ( self . _api_url , params ) )
def as_status ( cls , obj ) : """Convert obj into Status ."""
if obj is None : return None return obj if isinstance ( obj , cls ) else cls . from_string ( obj )
def send ( self , command , message = None ) : '''Send a command over the socket with length endcoded'''
if message : joined = command + constants . NL + util . pack ( message ) else : joined = command + constants . NL if self . _blocking : for sock in self . socket ( ) : sock . sendall ( joined ) else : self . _pending . append ( joined )
def set_current_mount ( hardware , session ) : """Choose the pipette in which to execute commands . If there is no pipette , or it is uncommissioned , the pipette is not mounted . : attached _ pipettes attached _ pipettes : Information obtained from the current pipettes attached to the robot . This looks like...
pipette = None right_channel = None left_channel = None right_pipette , left_pipette = get_pipettes ( hardware ) if right_pipette : if not feature_flags . use_protocol_api_v2 ( ) : right_channel = right_pipette . channels else : right_channel = right_pipette . get ( 'channels' ) right_pi...
def modules_get ( url_tpl , per_page , css , max_modules = 2000 , pagination_type = PT . normal ) : """Gets a list of modules . Note that this function can also be used to get themes . @ param url _ tpl : a string such as https : / / drupal . org / project / project _ module ? page = % s . % s will be replace...
page = 0 elements = False done_so_far = 0 max_potential_pages = max_modules / per_page print ( "Maximum pages: %s." % max_potential_pages ) stop = False while elements == False or len ( elements ) == per_page : url = url_tpl % page r = requests . get ( url ) bs = BeautifulSoup ( r . text , 'lxml' ) elem...
def local_machine ( ) : """Option to do something on local machine ."""
common_conf ( ) env . machine = 'local' env . pg_admin_role = settings . LOCAL_PG_ADMIN_ROLE env . db_backup_dir = settings . DJANGO_PROJECT_ROOT env . media_backup_dir = settings . DJANGO_PROJECT_ROOT # Not sure what this is good for . Not used in our fabfile . # env . media _ root = settings . DJANGO _ MEDIA _ ROOT #...
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_admin_status ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) fcoe_get_interface = ET . Element ( "fcoe_get_interface" ) config = fcoe_get_interface output = ET . SubElement ( fcoe_get_interface , "output" ) fcoe_intf_list = ET . SubElement ( output , "fcoe-intf-list" ) fcoe_intf_fcoe_port_id_key = ET . SubElement ( fcoe_intf_list , "fcoe-intf-f...
def zpipe ( ctx ) : """build inproc pipe for talking to threads mimic pipe used in czmq zthread _ fork . Returns a pair of PAIRs connected via inproc"""
a = ctx . socket ( zmq . PAIR ) a . linger = 0 b = ctx . socket ( zmq . PAIR ) b . linger = 0 socket_set_hwm ( a , 1 ) socket_set_hwm ( b , 1 ) iface = "inproc://%s" % binascii . hexlify ( os . urandom ( 8 ) ) a . bind ( iface ) b . connect ( iface ) return a , b
def find_file ( name , directory ) : """Searches up from a directory looking for a file"""
path_bits = directory . split ( os . sep ) for i in range ( 0 , len ( path_bits ) - 1 ) : check_path = path_bits [ 0 : len ( path_bits ) - i ] check_file = "%s%s%s" % ( os . sep . join ( check_path ) , os . sep , name ) if os . path . exists ( check_file ) : return abspath ( check_file ) return None
def VerifyStructure ( self , parser_mediator , line ) : """Verify that this file is a Mac AppFirewall log file . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . line ( str ) : line from a text file . Returns : bool : ...
self . _last_month = 0 self . _year_use = parser_mediator . GetEstimatedYear ( ) try : structure = self . FIREWALL_LINE . parseString ( line ) except pyparsing . ParseException as exception : logger . debug ( ( 'Unable to parse file as a Mac AppFirewall log file with error: ' '{0!s}' ) . format ( exception ) ) ...
def trial_ls ( args ) : '''List trial'''
nni_config = Config ( get_config_filename ( args ) ) rest_port = nni_config . get_config ( 'restServerPort' ) rest_pid = nni_config . get_config ( 'restServerPid' ) if not detect_process ( rest_pid ) : print_error ( 'Experiment is not running...' ) return running , response = check_rest_server_quick ( rest_port...
def analyse ( file , length = None ) : """Analyse application layer packets . Keyword arguments : * file - - bytes or file - like object , packet to be analysed * length - - int , length of the analysing packet Returns : * Analysis - - an Analysis object from ` pcapkit . analyser `"""
if isinstance ( file , bytes ) : file = io . BytesIO ( file ) io_check ( file ) int_check ( length or sys . maxsize ) return analyse2 ( file , length )
def read_loop ( self ) : """Infinite loop that reads messages off of the socket while not closed . When a message is received its corresponding pending Future is set to have the message as its result . This is never used directly and is fired as a separate callback on the I / O loop via the ` connect ( ) ` ...
while not self . closing : try : xid , zxid , response = yield self . read_response ( ) except iostream . StreamClosedError : return except Exception : log . exception ( "Error reading response." ) self . abort ( ) return payload_log . debug ( "[RECV] (xid: %s) %s...
def add_from_child ( self , resource , ** kwargs ) : """Add a resource with its all children resources to the current resource ."""
new_resource = self . add ( resource . member_name , resource . collection_name , ** kwargs ) for child in resource . children : new_resource . add_from_child ( child , ** kwargs )
def getVariances ( self ) : """Returns the estimated variances as a n _ terms x P matrix each row of the output represents a term and its P values represent the variance corresponding variance in each trait"""
if self . P > 1 : RV = SP . zeros ( ( self . n_terms , self . P ) ) for term_i in range ( self . n_terms ) : RV [ term_i , : ] = self . vd . getTerm ( term_i ) . getTraitCovar ( ) . K ( ) . diagonal ( ) else : RV = self . getScales ( ) ** 2 return RV
def getattr_in ( obj , name ) : """Finds an in @ obj via a period - delimited string @ name . @ obj : ( # object ) @ name : ( # str ) | . | - separated keys to search @ obj in obj . deep . attr = ' deep value ' getattr _ in ( obj , ' obj . deep . attr ' ) | ' deep value ' |"""
for part in name . split ( '.' ) : obj = getattr ( obj , part ) return obj
def deployed ( name , sourcepath , apppool = '' , hostheader = '' , ipaddress = '*' , port = 80 , protocol = 'http' , preload = '' ) : '''Ensure the website has been deployed . . . note : This function only validates against the site name , and will return True even if the site already exists with a different...
ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' } current_sites = __salt__ [ 'win_iis.list_sites' ] ( ) if name in current_sites : ret [ 'comment' ] = 'Site already present: {0}' . format ( name ) ret [ 'result' ] = True elif __opts__ [ 'test' ] : ret [ 'comment' ] = 'Site will be...
def jsonHook ( encoded ) : """Custom JSON decoder that allows construction of a new ` ` Ci ` ` instance from a decoded JSON object . : param encoded : a JSON decoded object literal ( a dict ) : returns : " encoded " or one of the these objects : : class : ` Ci ` , : class : ` MzmlProduct ` , : class : ` Mzm...
if '__Ci__' in encoded : return Ci . _fromJSON ( encoded [ '__Ci__' ] ) elif '__MzmlProduct__' in encoded : return MzmlProduct . _fromJSON ( encoded [ '__MzmlProduct__' ] ) elif '__MzmlPrecursor__' in encoded : return MzmlPrecursor . _fromJSON ( encoded [ '__MzmlPrecursor__' ] ) else : return encoded
def site_percolation ( ij , occupied_sites ) : r"""Calculates the site and bond occupancy status for a site percolation process given a list of occupied sites . Parameters ij : array _ like An N x 2 array of [ site _ A , site _ B ] connections . If two connected sites are both occupied they are part of th...
from collections import namedtuple Np = sp . size ( occupied_sites ) occupied_bonds = sp . all ( occupied_sites [ ij ] , axis = 1 ) adj_mat = sprs . csr_matrix ( ( occupied_bonds , ( ij [ : , 0 ] , ij [ : , 1 ] ) ) , shape = ( Np , Np ) ) adj_mat . eliminate_zeros ( ) clusters = csgraph . connected_components ( csgraph...
def run_display_app_output ( self , out ) : """Print any App output . Args : out ( str ) : One or more lines of output messages ."""
if not self . profile . get ( 'quiet' ) and not self . args . quiet : print ( 'App Output:' ) for o in out . decode ( 'utf-8' ) . split ( '\n' ) : print ( ' {}{}{}' . format ( c . Style . BRIGHT , c . Fore . CYAN , o ) ) self . log . debug ( '[tcrun] App output: {}' . format ( o ) )
def _make_jwt ( self ) : """Make a signed JWT . Returns : Tuple [ bytes , datetime ] : The encoded JWT and the expiration ."""
now = _helpers . utcnow ( ) lifetime = datetime . timedelta ( seconds = self . _token_lifetime ) expiry = now + lifetime payload = { 'iss' : self . _issuer , 'sub' : self . _subject , 'iat' : _helpers . datetime_to_secs ( now ) , 'exp' : _helpers . datetime_to_secs ( expiry ) , 'aud' : self . _audience , } payload . up...
def upload ( apikey , picture , resize = None , rotation = '00' , noexif = False , callback = None ) : """prepares post for regular upload : param str apikey : Apikey needed for Autentication on picflash . : param str / tuple / list picture : Path to picture as str or picture data . If data a tuple or list with...
if isinstance ( picture , str ) : with open ( picture , 'rb' ) as file_obj : picture_name = picture data = file_obj . read ( ) elif isinstance ( picture , ( tuple , list ) ) : picture_name = picture [ 0 ] data = picture [ 1 ] else : raise TypeError ( "The second argument must be str or l...
def walkfiles ( startdir , regex = None , recurse = True ) : """Yields the absolute paths of files found within the given start directory . Can optionally filter paths using a regex pattern ."""
for r , _ , fs in os . walk ( startdir ) : if not recurse and startdir != r : return for f in fs : path = op . abspath ( op . join ( r , f ) ) if regex and not _is_match ( regex , path ) : continue if op . isfile ( path ) : yield path
def is_path_like_object ( obj , marker = '*' ) : """Is given object ' obj ' a path string , a pathlib . Path , a file / file - like ( stream ) or IOInfo namedtuple object ? : param obj : a path string , pathlib . Path object , a file / file - like or ' IOInfo ' object : return : True if ' obj ' is a pat...
return ( ( is_path ( obj ) and marker not in obj ) or ( is_path_obj ( obj ) and marker not in obj . as_posix ( ) ) or is_file_stream ( obj ) or is_ioinfo ( obj ) )
def _download_repodata ( self , checked_repos ) : """Dowload repodata ."""
self . _files_downloaded = [ ] self . _repodata_files = [ ] self . __counter = - 1 if checked_repos : for repo in checked_repos : path = self . _repo_url_to_path ( repo ) self . _files_downloaded . append ( path ) self . _repodata_files . append ( path ) worker = self . download_asyn...
def delete_object ( self , object_name ) : """Remove an object from this bucket . : param str object _ name : The object to remove ."""
self . _client . remove_object ( self . _instance , self . name , object_name )
def validate_checkpoint_files ( checkpoint_file , backup_file ) : """Checks if the given checkpoint and / or backup files are valid . The checkpoint file is considered valid if : * it passes all tests run by ` ` check _ integrity ` ` ; * it has at least one sample written to it ( indicating at least one che...
# check if checkpoint file exists and is valid try : check_integrity ( checkpoint_file ) checkpoint_valid = True except ( ValueError , KeyError , IOError ) : checkpoint_valid = False # backup file try : check_integrity ( backup_file ) backup_valid = True except ( ValueError , KeyError , IOError ) : ...
def _doc_method ( klass , func ) : """Generate the docstring of a method ."""
argspec = inspect . getfullargspec ( func ) # Remove first ' self ' argument . if argspec . args and argspec . args [ 0 ] == 'self' : del argspec . args [ 0 ] args = inspect . formatargspec ( * argspec ) header = "{klass}.{name}{args}" . format ( klass = klass . __name__ , name = _name ( func ) , args = args , ) do...
def list_member_groups ( self , member_id ) : '''a method to retrieve a list of meetup groups member belongs to : param member _ id : integer with meetup member id : return : dictionary with list of group details in [ json ] group _ details = self . objects . group _ profile . schema'''
# https : / / www . meetup . com / meetup _ api / docs / members / : member _ id / # get title = '%s.list_member_groups' % self . __class__ . __name__ # validate inputs input_fields = { 'member_id' : member_id } for key , value in input_fields . items ( ) : if value : object_title = '%s(%s=%s)' % ( title , ...
def warp_pointer ( self , x , y , src_window = X . NONE , src_x = 0 , src_y = 0 , src_width = 0 , src_height = 0 , onerror = None ) : """Move the pointer relative its current position by the offsets ( x , y ) . However , if src _ window is a window the pointer is only moved if the specified rectangle in src _ w...
request . WarpPointer ( display = self . display , onerror = onerror , src_window = src_window , dst_window = X . NONE , src_x = src_x , src_y = src_y , src_width = src_width , src_height = src_height , dst_x = x , dst_y = y )
def dynacRepresentation ( self ) : """Return the Dynac representation of this accelerating gap instance ."""
details = [ self . gapID . val , self . energy . val , self . beta . val , self . L . val , self . TTF . val , self . TTFprime . val , self . S . val , self . SP . val , self . quadLength . val , self . quadStrength . val , self . EField . val , self . phase . val , self . accumLen . val , self . TTFprimeprime . val , ...
def set_assessment ( self , assessment_id ) : """Sets the assessment . arg : assessment _ id ( osid . id . Id ) : the new assessment raise : InvalidArgument - ` ` assessment _ id ` ` is invalid raise : NoAccess - ` ` assessment _ id ` ` cannot be modified raise : NullArgument - ` ` assessment _ id ` ` is ` ...
# Implemented from template for osid . resource . ResourceForm . set _ avatar _ template if self . get_assessment_metadata ( ) . is_read_only ( ) : raise errors . NoAccess ( ) if not self . _is_valid_id ( assessment_id ) : raise errors . InvalidArgument ( ) self . _my_map [ 'assessmentId' ] = str ( assessment_i...
def inputhook_wx3 ( ) : """Run the wx event loop by processing pending events only . This is like inputhook _ wx1 , but it keeps processing pending events until stdin is ready . After processing all pending events , a call to time . sleep is inserted . This is needed , otherwise , CPU usage is at 100 % . Th...
# We need to protect against a user pressing Control - C when IPython is # idle and this is running . We trap KeyboardInterrupt and pass . try : app = wx . GetApp ( ) # @ UndefinedVariable if app is not None : assert wx . Thread_IsMain ( ) # @ UndefinedVariable # The import of wx on ...
def get_task_actions ( current ) : """List task types for current user . . code - block : : python # request : ' view ' : ' _ zops _ get _ task _ actions ' , ' key ' : key , # response : ' key ' : key , ' actions ' : [ { " title " : ' : ' Action Title ' , " wf " : " workflow _ name " } , ]"""
task_inv = TaskInvitation . objects . get ( current . input [ 'key' ] ) actions = [ { "title" : __ ( u"Assign Someone Else" ) , "wf" : "assign_same_abstract_role" } , { "title" : __ ( u"Suspend" ) , "wf" : "suspend_workflow" } , { "title" : __ ( u"Postpone" ) , "wf" : "postpone_workflow" } ] if task_inv . instance . cu...
def tx_id ( properties ) : """Gets the tx _ id for a message from a rabbit queue , using the message properties . Will raise KeyError if tx _ id is missing from message headers . : param properties : Message properties : returns : tx _ id of survey response : rtype : str"""
tx_id = properties . headers [ 'tx_id' ] logger . info ( "Retrieved tx_id from message properties: tx_id={}" . format ( tx_id ) ) return tx_id
def cublasDestroy ( handle ) : """Release CUBLAS resources . Releases hardware resources used by CUBLAS . Parameters handle : void _ p CUBLAS context ."""
status = _libcublas . cublasDestroy_v2 ( ctypes . c_void_p ( handle ) ) cublasCheckStatus ( status )