signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _handler ( self , sender , setting , value , ** kwargs ) :
"""handler for ` ` setting _ changed ` ` signal .
@ see : ref : ` django : setting - changed ` _""" | if setting . startswith ( self . prefix ) :
self . _set_attr ( setting , value ) |
def add_root ( cls , ** kwargs ) :
"""Adds a root node to the tree .""" | if len ( kwargs ) == 1 and 'instance' in kwargs : # adding the passed ( unsaved ) instance to the tree
newobj = kwargs [ 'instance' ]
if newobj . pk :
raise NodeAlreadySaved ( "Attempted to add a tree node that is " "already in the database" )
else :
newobj = cls ( ** kwargs )
newobj . _cached_depth... |
def role_search ( auth = None , ** kwargs ) :
'''Search roles
CLI Example :
. . code - block : : bash
salt ' * ' keystoneng . role _ search
salt ' * ' keystoneng . role _ search name = role1
salt ' * ' keystoneng . role _ search domain _ id = b62e76fbeeff4e8fb77073f591cf211e''' | cloud = get_operator_cloud ( auth )
kwargs = _clean_kwargs ( ** kwargs )
return cloud . search_roles ( ** kwargs ) |
def is_period_arraylike ( arr ) :
"""Check whether an array - like is a periodical array - like or PeriodIndex .
Parameters
arr : array - like
The array - like to check .
Returns
boolean
Whether or not the array - like is a periodical array - like or
PeriodIndex instance .
Examples
> > > is _ peri... | if isinstance ( arr , ( ABCPeriodIndex , ABCPeriodArray ) ) :
return True
elif isinstance ( arr , ( np . ndarray , ABCSeries ) ) :
return is_period_dtype ( arr . dtype )
return getattr ( arr , 'inferred_type' , None ) == 'period' |
def bsrchd ( value , ndim , array ) :
"""Do a binary search for a key value within a double precision array ,
assumed to be in increasing order . Return the index of the matching
array entry , or - 1 if the key value is not found .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice ... | value = ctypes . c_double ( value )
ndim = ctypes . c_int ( ndim )
array = stypes . toDoubleVector ( array )
return libspice . bsrchd_c ( value , ndim , array ) |
def replace_headers ( source_pdb_content , target_pdb_content ) :
'''Takes the headers from source _ pdb _ content and adds them to target _ pdb _ content , removing any headers that
target _ pdb _ content had .
Only the content up to the first structural line are taken from source _ pdb _ content and only the ... | s = PDB ( source_pdb_content )
t = PDB ( target_pdb_content )
source_headers = [ ]
for l in s . lines :
if l [ : 6 ] . strip ( ) in non_header_records :
break
else :
source_headers . append ( l )
target_body = [ ]
in_header = True
for l in t . lines :
if l [ : 6 ] . strip ( ) in non_header_r... |
def _update_callbacks ( self , plot ) :
"""Iterates over all subplots and updates existing CustomJS
callbacks with models that were replaced when compositing
subplots into a CompositePlot and sets the plot id to match
the root level bokeh model .""" | subplots = self . traverse ( lambda x : x , [ GenericElementPlot ] )
merged_tools = { t : list ( plot . select ( { 'type' : TOOL_TYPES [ t ] } ) ) for t in self . _merged_tools }
for subplot in subplots :
for cb in subplot . callbacks :
for c in cb . callbacks :
for tool , objs in merged_tools .... |
def from_string ( address ) :
"""Return new object by the given MAC - address
: param address : address to convert
: return : WMACAddress""" | str_address = None
if WMACAddress . re_dash_format . match ( address ) :
str_address = "" . join ( address . split ( "-" ) )
elif WMACAddress . re_colon_format . match ( address ) :
str_address = "" . join ( address . split ( ":" ) )
elif WMACAddress . re_cisco_format . match ( address ) :
str_address = "" ... |
def fetch_all_objects_from_db_by_pklist ( self , cls : Type , table : str , fieldlist : Sequence [ str ] , pklist : Sequence [ Any ] , construct_with_pk : bool , * args ) -> List [ T ] :
"""Fetches all objects from a table , given a list of PKs .""" | objarray = [ ]
for pk in pklist :
if construct_with_pk :
obj = cls ( pk , * args )
# should do its own fetching
else :
obj = cls ( * args )
self . fetch_object_from_db_by_pk ( obj , table , fieldlist , pk )
objarray . append ( obj )
return objarray |
def clean_entity ( self , ent ) :
"""Strip out extra words that often get picked up by spaCy ' s NER .
To do : preserve info about what got stripped out to help with ES / Geonames
resolution later .
Parameters
ent : a spaCy named entity Span
Returns
new _ ent : a spaCy Span , with extra words stripped o... | dump_list = [ 'province' , 'the' , 'area' , 'airport' , 'district' , 'square' , 'town' , 'village' , 'prison' , "river" , "valley" , "provincial" , "prison" , "region" , "municipality" , "state" , "territory" , "of" , "in" , "county" , "central" ]
# maybe have ' city ' ? Works differently in different countries
# also ... |
def open_in_editor ( self , cli ) :
"""Open code in editor .
: param cli : : class : ` ~ prompt _ toolkit . interface . CommandLineInterface `
instance .""" | if self . read_only ( ) :
raise EditReadOnlyBuffer ( )
# Write to temporary file
descriptor , filename = tempfile . mkstemp ( self . tempfile_suffix )
os . write ( descriptor , self . text . encode ( 'utf-8' ) )
os . close ( descriptor )
# Open in editor
# ( We need to use ` cli . run _ in _ terminal ` , because no... |
def remove ( name = None , pkgs = None , ** kwargs ) :
'''Remove specified package . Accepts full or partial FMRI .
In case of multiple match , the command fails and won ' t modify the OS .
name
The name of the package to be deleted .
Multiple Package Options :
pkgs
A list of packages to delete . Must b... | targets = salt . utils . args . split_input ( pkgs ) if pkgs else [ name ]
if not targets :
return { }
if pkgs :
log . debug ( 'Removing these packages instead of %s: %s' , name , targets )
# Get a list of the currently installed pkgs .
old = list_pkgs ( )
# Remove the package ( s )
cmd = [ '/bin/pkg' , 'uninst... |
def _ParseIdentifierMappingRecord ( self , parser_mediator , table_name , esedb_record ) :
"""Extracts an identifier mapping from a SruDbIdMapTable record .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
table _ name ( s... | record_values = self . _GetRecordValues ( parser_mediator , table_name , esedb_record )
identifier = record_values . get ( 'IdIndex' , None )
if identifier is None :
parser_mediator . ProduceExtractionWarning ( 'IdIndex value missing from table: SruDbIdMapTable' )
return None , None
identifier_type = record_val... |
def _forwardImplementation ( self , inbuf , outbuf ) :
"""Proportional probability method .""" | assert self . module
propensities = self . module . getActionValues ( 0 )
summedProps = sum ( propensities )
probabilities = propensities / summedProps
action = eventGenerator ( probabilities )
# action = drawIndex ( probabilities )
outbuf [ : ] = scipy . array ( [ action ] ) |
def delete_license ( license_id ) :
"""Delete a License by ID""" | response = utils . checked_api_call ( pnc_api . licenses , 'delete' , id = license_id )
if response :
return utils . format_json ( response . content ) |
def update_supplier ( self , supplier_id , supplier_dict ) :
"""Updates a supplier
: param supplier _ id : the supplier id
: param supplier _ dict : dict
: return : dict""" | return self . _create_put_request ( resource = SUPPLIERS , billomat_id = supplier_id , send_data = supplier_dict ) |
def smart_search ( self , * arguments ) :
"""Perform a smart search on the given keywords or patterns .
: param arguments : The keywords or patterns to search for .
: returns : The matched password names ( a list of strings ) .
: raises : The following exceptions can be raised :
- : exc : ` . NoMatchingPass... | matches = self . simple_search ( * arguments )
if not matches :
logger . verbose ( "Falling back from substring search to fuzzy search .." )
matches = self . fuzzy_search ( * arguments )
if not matches :
if len ( self . filtered_entries ) > 0 :
raise NoMatchingPasswordError ( format ( "No passwords ... |
def parse_attr_signature ( sig ) :
"""Parse an attribute signature""" | match = ATTR_SIG_RE . match ( sig . strip ( ) )
if not match :
raise RuntimeError ( 'Attribute signature invalid, got ' + sig )
name , _ , params = match . groups ( )
if params is not None and params . strip ( ) != '' :
params = split_sig ( params )
params = [ parse_param_signature ( x ) for x in params ]
e... |
def create_audit_event ( self , code = 'AUDIT' ) :
"""Creates a generic auditing Event logging the changes between saves
and the initial data in creates .
Kwargs :
code ( str ) : The code to set the new Event to .
Returns :
Event : A new event with relevant info inserted into it""" | event = self . _meta . event_model ( code = code , model = self . __class__ . __name__ , )
# Use the logged in User , if possible
if current_user :
event . created_by = current_user . get_id ( )
self . copy_foreign_keys ( event )
self . populate_audit_fields ( event )
return event |
def createRoles ( self , configFiles , dateTimeFormat = None ) :
"""Parses a JSON configuration file to create roles .
Args :
configFiles ( list ) : A list of JSON files on disk containing
configuration data for creating roles .
dateTimeFormat ( str ) : A valid date formatting directive , as understood
by... | if dateTimeFormat is None :
dateTimeFormat = '%Y-%m-%d %H:%M'
scriptStartTime = datetime . datetime . now ( )
try :
print ( "********************Create Roles********************" )
print ( "Script started at %s" % scriptStartTime . strftime ( dateTimeFormat ) )
if self . securityhandler . valid == False... |
def get_assessment_ids_by_banks ( self , bank_ids ) :
"""Gets the list of ` ` Assessment Ids ` ` corresponding to a list of ` ` Banks ` ` .
arg : bank _ ids ( osid . id . IdList ) : list of bank ` ` Ids ` `
return : ( osid . id . IdList ) - list of bank ` ` Ids ` `
raise : NullArgument - ` ` bank _ ids ` ` is... | # Implemented from template for
# osid . resource . ResourceBinSession . get _ resource _ ids _ by _ bins
id_list = [ ]
for assessment in self . get_assessments_by_banks ( bank_ids ) :
id_list . append ( assessment . get_id ( ) )
return IdList ( id_list ) |
def get ( self , sid ) :
"""Constructs a EventContext
: param sid : The sid
: returns : twilio . rest . taskrouter . v1 . workspace . event . EventContext
: rtype : twilio . rest . taskrouter . v1 . workspace . event . EventContext""" | return EventContext ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , sid = sid , ) |
def walk ( obj , path = '' , skiphidden = True ) :
"""Returns a recursive iterator over all Nodes starting from
findnode ( obj , path ) .
If skiphidden is True ( the default ) then structure branches starting with
an underscore will be ignored .""" | node = findnode ( obj , path )
return walknode ( node , skiphidden ) |
def request ( self , * args , ** kwargs ) :
"""Issue the HTTP request capturing any errors that may occur .""" | try :
return self . _http . request ( * args , timeout = TIMEOUT , ** kwargs )
except Exception as exc :
raise RequestException ( exc , args , kwargs ) |
def pycache_clean ( context ) :
"Remove _ _ pycache _ _ directories" | # pylint : disable = unused - argument
dirs = set ( )
for root , dirnames , _ in os . walk ( os . curdir ) :
if '__pycache__' in dirnames :
dirs . add ( os . path . join ( root , '__pycache__' ) )
print ( "Removing __pycache__ directories" )
rmrf ( dirs , verbose = False ) |
def yum_install ( ** kwargs ) :
"""installs a yum package""" | if 'repo' in kwargs :
repo = kwargs [ 'repo' ]
for pkg in list ( kwargs [ 'packages' ] ) :
if is_package_installed ( distribution = 'el' , pkg = pkg ) is False :
if 'repo' in locals ( ) :
log_green ( "installing %s from repo %s ..." % ( pkg , repo ) )
sudo ( "yum install -y --qui... |
def table_name ( self ) :
"""Get slice name .
In case of 2D return cube name . In case of 3D , return the combination
of the cube name with the label of the corresponding slice
( nth label of the 0th dimension ) .""" | if self . _cube . ndim < 3 and not self . ca_as_0th :
return None
title = self . _cube . name
table_name = self . _cube . labels ( ) [ 0 ] [ self . _index ]
return "%s: %s" % ( title , table_name ) |
def dataset_exists ( self , dataset ) :
"""Returns whether the given dataset exists .
If regional location is specified for the dataset , that is also checked
to be compatible with the remote dataset , otherwise an exception is thrown .
: param dataset :
: type dataset : BQDataset""" | try :
response = self . client . datasets ( ) . get ( projectId = dataset . project_id , datasetId = dataset . dataset_id ) . execute ( )
if dataset . location is not None :
fetched_location = response . get ( 'location' )
if dataset . location != fetched_location :
raise Exception (... |
def closeEvent ( self , event ) :
"""Overloads the close event for this widget to make sure that the data is properly saved before exiting .
: param event | < QCloseEvent >""" | if ( not ( self . saveOnClose ( ) and self . checkForSave ( ) ) ) :
event . ignore ( )
else :
super ( XScintillaEdit , self ) . closeEvent ( event ) |
def post ( self ) :
''': ref : ` Authenticate < rest _ tornado - auth > ` against Salt ' s eauth system
. . http : post : : / login
: reqheader X - Auth - Token : | req _ token |
: reqheader Accept : | req _ accept |
: reqheader Content - Type : | req _ ct |
: form eauth : the eauth backend configured for... | try :
if not isinstance ( self . request_payload , dict ) :
self . send_error ( 400 )
return
creds = { 'username' : self . request_payload [ 'username' ] , 'password' : self . request_payload [ 'password' ] , 'eauth' : self . request_payload [ 'eauth' ] , }
# if any of the args are missing , its... |
def filter ( self , query , inplace = True ) :
"""Use a query statement to filter data . Note that you specify the data
to be removed !
Parameters
query : string
The query string to be evaluated . Is directly provided to
pandas . DataFrame . query
inplace : bool
if True , change the container datafram... | with LogDataChanges ( self , filter_action = 'filter' , filter_query = query ) :
result = self . data . query ( 'not ({0})' . format ( query ) , inplace = inplace , )
return result |
def patch_worker_factory ( ) :
"""Patches the ` ` luigi . interface . _ WorkerSchedulerFactory ` ` to include sandboxing information when
create a worker instance .""" | def create_worker ( self , scheduler , worker_processes , assistant = False ) :
worker = luigi . worker . Worker ( scheduler = scheduler , worker_processes = worker_processes , assistant = assistant , worker_id = os . getenv ( "LAW_SANDBOX_WORKER_ID" ) )
worker . _first_task = os . getenv ( "LAW_SANDBOX_WORKER_... |
def countByWindow ( self , windowDuration , slideDuration ) :
"""Return a new DStream in which each RDD has a single element generated
by counting the number of elements in a window over this DStream .
windowDuration and slideDuration are as defined in the window ( ) operation .
This is equivalent to window (... | return self . map ( lambda x : 1 ) . reduceByWindow ( operator . add , operator . sub , windowDuration , slideDuration ) |
def draw ( data , format = 'auto' , size = ( 400 , 300 ) , drawing_type = 'ball and stick' , camera_type = 'perspective' , shader = 'lambert' , display_html = True , element_properties = None , show_save = False ) :
"""Draws an interactive 3D visualization of the inputted chemical .
Args :
data : A string or fi... | # Catch errors on string - based input before getting js involved
draw_options = [ 'ball and stick' , 'wireframe' , 'space filling' ]
camera_options = [ 'perspective' , 'orthographic' ]
shader_options = [ 'toon' , 'basic' , 'phong' , 'lambert' ]
if drawing_type not in draw_options :
raise Exception ( "Invalid drawi... |
def loader_cls ( self ) :
"""Loader class used in ` JsonRef . replace _ refs ` .""" | cls = self . app . config [ 'JSONSCHEMAS_LOADER_CLS' ]
if isinstance ( cls , six . string_types ) :
return import_string ( cls )
return cls |
def genOutputs ( self , code , match ) :
"""Return a list out template outputs based on the triggers found in
the code and the template they create .""" | out = sorted ( ( k , match . output ( m ) ) for ( k , m ) in self . collectTriggers ( match . match , code ) . items ( ) )
out = list ( map ( lambda a : a [ 1 ] , out ) )
return out |
def lx4dec ( string , first ) :
"""Scan a string from a specified starting position for the
end of a decimal number .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / lx4dec _ c . html
: param string : Any character string .
: type string : str
: param first : First characte... | string = stypes . stringToCharP ( string )
first = ctypes . c_int ( first )
last = ctypes . c_int ( )
nchar = ctypes . c_int ( )
libspice . lx4dec_c ( string , first , ctypes . byref ( last ) , ctypes . byref ( nchar ) )
return last . value , nchar . value |
def expected_values ( self , beta ) :
"""Expected values of the function given the covariance matrix and hyperparameters
Parameters
beta : np . ndarray
Contains untransformed values for latent variables
Returns
The expected values of the function""" | parm = np . array ( [ self . latent_variables . z_list [ k ] . prior . transform ( beta [ k ] ) for k in range ( beta . shape [ 0 ] ) ] )
L = self . _L ( parm )
alpha = self . _alpha ( L )
return np . dot ( np . transpose ( self . kernel . K ( parm ) ) , alpha ) |
def destroy ( self ) :
"""Unregister up from untwisted reactor . It is needed
to call self . terminate ( ) first to kill the process .""" | core . gear . pool . remove ( self )
self . base . clear ( ) |
def process_stdin ( line ) :
'''handle commands from user''' | if line is None :
sys . exit ( 0 )
# allow for modules to override input handling
if mpstate . functions . input_handler is not None :
mpstate . functions . input_handler ( line )
return
line = line . strip ( )
if mpstate . status . setup_mode : # in setup mode we send strings straight to the master
if ... |
def start_session ( self , causal_consistency = True , default_transaction_options = None ) :
"""Start a logical session .
This method takes the same parameters as
: class : ` ~ pymongo . client _ session . SessionOptions ` . See the
: mod : ` ~ pymongo . client _ session ` module for details and examples .
... | return self . __start_session ( False , causal_consistency = causal_consistency , default_transaction_options = default_transaction_options ) |
def show_disk ( name = None , kwargs = None , call = None ) : # pylint : disable = W0613
'''Show the details of an existing disk .
CLI Example :
. . code - block : : bash
salt - cloud - a show _ disk myinstance disk _ name = mydisk
salt - cloud - f show _ disk gce disk _ name = mydisk''' | if not kwargs or 'disk_name' not in kwargs :
log . error ( 'Must specify disk_name.' )
return False
conn = get_conn ( )
return _expand_disk ( conn . ex_get_volume ( kwargs [ 'disk_name' ] ) ) |
def _not ( condition = None , ** kwargs ) :
"""Return the opposite of input condition .
: param condition : condition to process .
: result : not condition .
: rtype : bool""" | result = True
if condition is not None :
result = not run ( condition , ** kwargs )
return result |
def list_relations ( self ) :
'''list every relation in the database as ( src , relation , dst )''' | _ = self . _execute ( 'select * from relations' ) . fetchall ( )
for i in _ : # print ( i )
src , name , dst = i
src = self . deserialize ( next ( self . _execute ( 'select code from objects where id=?' , ( src , ) ) ) [ 0 ] )
dst = self . deserialize ( next ( self . _execute ( 'select code from objects whe... |
def msg_curse ( self , args = None , max_width = None ) :
"""Return the dict to display in the curse interface .""" | # Init the return message
ret = [ ]
# Only process if stats exist . . .
if not self . stats :
return ret
# Max size for the interface name
name_max_width = max_width - 12
# Header
msg = '{:{width}}' . format ( 'RAID disks' , width = name_max_width )
ret . append ( self . curse_add_line ( msg , "TITLE" ) )
msg = '{:... |
def parse ( fpath , ** kwargs ) :
"""parse file contents , via parser plugins , to dict like object
NB : the longest file regex will be used from plugins
Parameters
fpath : file _ like
string , object with ' open ' and ' name ' attributes , or
object with ' readline ' and ' name ' attributes
kwargs :
... | if isinstance ( fpath , basestring ) :
fname = fpath
elif hasattr ( fpath , 'open' ) and hasattr ( fpath , 'name' ) :
fname = fpath . name
elif hasattr ( fpath , 'readline' ) and hasattr ( fpath , 'name' ) :
fname = fpath . name
else :
raise ValueError ( 'fpath should be a str or file_like object: {}' .... |
def extract ( self , url = None , raw_html = None ) :
"""Main method to extract an article object from a URL ,
pass in a url and get back a Article""" | cc = CrawlCandidate ( self . config , url , raw_html )
return self . crawl ( cc ) |
def get_ip_scope ( auth , url , scopeid = None , ) :
"""function requires no inputs and returns all IP address scopes currently configured on the HPE
IMC server . If the optional scopeid parameter is included , this will automatically return
only the desired scope id .
: param scopeid : integer of the desired... | if scopeid is None :
get_ip_scope_url = "/imcrs/res/access/assignedIpScope"
else :
get_ip_scope_url = "/imcrs/res/access/assignedIpScope/ip?ipScopeId=" + str ( scopeid )
f_url = url + get_ip_scope_url
response = requests . get ( f_url , auth = auth , headers = HEADERS )
try :
if response . status_code == 20... |
def _parse_contract_headers ( self , table ) :
"""Parse the years on the contract .
The years are listed as the headers on the contract . The first header
contains ' Team ' which specifies the player ' s current team and should
not be included in the years .
Parameters
table : PyQuery object
A PyQuery o... | years = [ i . text ( ) for i in table ( 'th' ) . items ( ) ]
years . remove ( 'Team' )
return years |
def result_report_overall ( self ) :
"""Report overall results
Returns
str
result report in string format""" | results = self . results_overall_metrics ( )
output = self . ui . section_header ( 'Overall metrics (micro-average)' , indent = 2 ) + '\n'
if results [ 'f_measure' ] :
output += self . ui . line ( 'F-measure' , indent = 2 ) + '\n'
output += self . ui . data ( field = 'F-measure (F1)' , value = float ( results [... |
def _tls_P_hash ( secret , seed , req_len , hm ) :
"""Provides the implementation of P _ hash function defined in
section 5 of RFC 4346 ( and section 5 of RFC 5246 ) . Two
parameters have been added ( hm and req _ len ) :
- secret : the key to be used . If RFC 4868 is to be believed ,
the length must match ... | hash_len = hm . hash_alg . hash_len
n = ( req_len + hash_len - 1 ) // hash_len
seed = bytes_encode ( seed )
res = b""
a = hm ( secret ) . digest ( seed )
# A ( 1)
while n > 0 :
res += hm ( secret ) . digest ( a + seed )
a = hm ( secret ) . digest ( a )
n -= 1
return res [ : req_len ] |
def Security_setOverrideCertificateErrors ( self , override ) :
"""Function path : Security . setOverrideCertificateErrors
Domain : Security
Method name : setOverrideCertificateErrors
Parameters :
Required arguments :
' override ' ( type : boolean ) - > If true , certificate errors will be overridden .
... | assert isinstance ( override , ( bool , ) ) , "Argument 'override' must be of type '['bool']'. Received type: '%s'" % type ( override )
subdom_funcs = self . synchronous_command ( 'Security.setOverrideCertificateErrors' , override = override )
return subdom_funcs |
def move_item ( self , item , origin , destination ) :
"""Moves an item from one cluster to anoter cluster .
: param item : the item to be moved .
: param origin : the originating cluster .
: param destination : the target cluster .""" | if self . equality :
item_index = 0
for i , element in enumerate ( origin ) :
if self . equality ( element , item ) :
item_index = i
break
else :
item_index = origin . index ( item )
destination . append ( origin . pop ( item_index ) ) |
def load_commands ( cli , manage_dict ) :
"""Loads the commands defined in manage file""" | namespaced = manage_dict . get ( 'namespaced' )
# get click commands
commands = manage_dict . get ( 'click_commands' , [ ] )
for command_dict in commands :
root_module = import_string ( command_dict [ 'module' ] )
group = cli . manage_groups . get ( command_dict . get ( 'group' ) , cli )
if getattr ( root_m... |
def wr_title ( self , worksheet , row_idx = 0 ) :
"""Write title ( optional ) .""" | if self . vars . title is not None : # Title is one line
if isinstance ( self . vars . title , str ) :
return self . wr_row_mergeall ( worksheet , self . vars . title , self . fmt_hdr , row_idx )
# Title is multi - line
else :
ridx = row_idx
for title_line in self . vars . title :
... |
def compute ( self , inputVector , learn , activeArray ) :
"""This is the primary public method of the SpatialPooler class . This
function takes a input vector and outputs the indices of the active columns .
If ' learn ' is set to True , this method also updates the permanences of the
columns .
@ param inpu... | if not isinstance ( inputVector , numpy . ndarray ) :
raise TypeError ( "Input vector must be a numpy array, not %s" % str ( type ( inputVector ) ) )
if inputVector . size != self . _numInputs :
raise ValueError ( "Input vector dimensions don't match. Expecting %s but got %s" % ( inputVector . size , self . _nu... |
def tcp_receive ( self ) :
"""Receive data from TCP port .""" | data = self . conn . recv ( self . BUFFER_SIZE )
if type ( data ) != str : # Python 3 specific
data = data . decode ( "utf-8" )
return str ( data ) |
def downloads_per_day ( self ) :
"""Return the number of downloads per day , averaged over the past 7 days
of data .
: return : average number of downloads per day
: rtype : int""" | count , num_days = self . _downloads_for_num_days ( 7 )
res = ceil ( count / num_days )
logger . debug ( "Downloads per day = (%d / %d) = %d" , count , num_days , res )
return res |
def ossos_release_parser ( table = False , data_release = parameters . RELEASE_VERSION ) :
"""extra fun as this is space - separated so using CSV parsers is not an option""" | names = [ 'cl' , 'p' , 'j' , 'k' , 'sh' , 'object' , 'mag' , 'e_mag' , 'Filt' , 'Hsur' , 'dist' , 'e_dist' , 'Nobs' , 'time' , 'av_xres' , 'av_yres' , 'max_x' , 'max_y' , 'a' , 'e_a' , 'e' , 'e_e' , 'i' , 'e_i' , 'Omega' , 'e_Omega' , 'omega' , 'e_omega' , 'tperi' , 'e_tperi' , 'RAdeg' , 'DEdeg' , 'JD' , 'rate' ]
# , '... |
def update ( self , attributes = values . unset , assignment_status = values . unset , reason = values . unset , priority = values . unset , task_channel = values . unset ) :
"""Update the TaskInstance
: param unicode attributes : The user - defined JSON data describing the custom attributes of this task .
: pa... | data = values . of ( { 'Attributes' : attributes , 'AssignmentStatus' : assignment_status , 'Reason' : reason , 'Priority' : priority , 'TaskChannel' : task_channel , } )
payload = self . _version . update ( 'POST' , self . _uri , data = data , )
return TaskInstance ( self . _version , payload , workspace_sid = self . ... |
def action ( forwards = None , context_class = None ) :
"""Decorator to build functions .
This decorator can be applied to a function to build actions . The
decorated function becomes the ` ` forwards ` ` implementation of the action .
The first argument of the ` ` forwards ` ` implementation is a context obj... | context_class = context_class or dict
def decorator ( _forwards ) :
return ActionBuilder ( _forwards , context_class )
if forwards is not None :
return decorator ( forwards )
else :
return decorator |
def _build_ssh_config ( self , config ) :
"""build the ssh injection configuration""" | ssh_config_injection = ssh_config_template % { 'host' : config . get ( 'host' ) , 'hostname' : config . get ( 'hostname' ) , 'ssh_key_path' : config . get ( 'ssh_key_path' ) , 'user' : config . get ( 'user' ) }
if config . has ( 'port' ) :
ssh_config_injection += " Port {0}\n" . format ( config . get ( 'port' ) )
... |
def prettyprint ( self ) :
"""Return hypercat formatted prettily""" | return json . dumps ( self . asJSON ( ) , sort_keys = True , indent = 4 , separators = ( ',' , ': ' ) ) |
def getActiveCompactions ( self , login , tserver ) :
"""Parameters :
- login
- tserver""" | self . send_getActiveCompactions ( login , tserver )
return self . recv_getActiveCompactions ( ) |
def list_children ( self , ** kwargs ) : # type : ( str ) - > Generator
'''Generate a list of all of the file / directory objects in the
specified location on the ISO .
Parameters :
iso _ path - The absolute path on the ISO to list the children for .
rr _ path - The absolute Rock Ridge path on the ISO to li... | if not self . _initialized :
raise pycdlibexception . PyCdlibInvalidInput ( 'This object is not yet initialized; call either open() or new() to create an ISO' )
num_paths = 0
for key in kwargs :
if key in [ 'joliet_path' , 'rr_path' , 'iso_path' , 'udf_path' ] :
if kwargs [ key ] is not None :
... |
def target_key ( self , key ) :
"""Temporarily retarget the client for one call to route
specifically to the one host that the given key routes to . In
that case the result on the promise is just the one host ' s value
instead of a dictionary .
. . versionadded : : 1.3""" | router = self . connection_pool . cluster . get_router ( )
host_id = router . get_host_for_key ( key )
rv = self . target ( [ host_id ] )
rv . __resolve_singular_result = True
return rv |
def run ( self ) :
"""The main run loop for the sender thread .""" | log . debug ( "Starting Kafka producer I/O thread." )
# main loop , runs until close is called
while self . _running :
try :
self . run_once ( )
except Exception :
log . exception ( "Uncaught error in kafka producer I/O thread" )
log . debug ( "Beginning shutdown of Kafka producer I/O thread, se... |
def discover_master ( self , service_name ) :
"""Asks sentinel servers for the Redis master ' s address corresponding
to the service labeled ` ` service _ name ` ` .
Returns a pair ( address , port ) or raises MasterNotFoundError if no
master is found .""" | for sentinel_no , sentinel in enumerate ( self . sentinels ) :
try :
masters = sentinel . sentinel_masters ( )
except ( ConnectionError , TimeoutError ) :
continue
state = masters . get ( service_name )
if state and self . check_master_state ( state , service_name ) : # Put this sentinel... |
def create_user ( self , Name , EmailAddress , ** kwargs ) :
"""Create user ( undocumented API feature ) .
: param Name : User name ( login for privileged , required )
: param EmailAddress : Email address ( required )
: param kwargs : Optional fields to set ( see edit _ user )
: returns : ID of new user or ... | return self . edit_user ( 'new' , Name = Name , EmailAddress = EmailAddress , ** kwargs ) |
def update ( self , ** args ) :
"""Update this project version from the server . It is prior used to archive versions .""" | data = { }
for field in args :
data [ field ] = args [ field ]
super ( Version , self ) . update ( ** data ) |
def accept ( self ) :
"""Server - side UDP connection establishment
This method returns a server - side SSLConnection object , connected to
that peer most recently returned from the listen method and not yet
connected . If there is no such peer , then the listen method is invoked .
Return value : SSLConnect... | if not self . _pending_peer_address :
if not self . listen ( ) :
_logger . debug ( "Accept returning without connection" )
return
new_conn = SSLConnection ( self , self . _keyfile , self . _certfile , True , self . _cert_reqs , self . _ssl_version , self . _ca_certs , self . _do_handshake_on_connect... |
def export_data ( self , directory , filename , with_md5_hash = False ) :
"""Save model data in a JSON file .
Parameters
: param directory : string
The directory .
: param filename : string
The filename .
: param with _ md5 _ hash : bool
Whether to append the checksum to the filename or not .""" | model_data = { 'vectors' : self . estimator . support_vectors_ . tolist ( ) , 'coefficients' : self . estimator . dual_coef_ . tolist ( ) , 'intercepts' : self . estimator . _intercept_ . tolist ( ) , 'weights' : self . estimator . n_support_ . tolist ( ) , 'kernel' : self . kernel , 'gamma' : float ( self . gamma ) , ... |
def reload_including_local ( module ) :
"""Reload a module . If it isn " t found , try to include the local service
directory . This must be called from a thread that has acquired the import
lock .
: param module : the module to reload .""" | try :
reload ( module )
except ImportError : # This can happen if the module was loaded in the immediate script
# directory . Add the service path and try again .
if not hasattr ( cherrypy . thread_data , "modulepath" ) :
raise
path = os . path . abspath ( cherrypy . thread_data . modulepath )
r... |
def get_jids ( ) :
'''List all the jobs that we have . .''' | options = _get_options ( ret = None )
_response = _request ( "GET" , options [ 'url' ] + options [ 'db' ] + "/_all_docs?include_docs=true" )
# Make sure the ' total _ rows ' is returned . . if not error out .
if 'total_rows' not in _response :
log . error ( 'Didn\'t get valid response from requesting all docs: %s' ... |
def _pattern_match ( self , item , pattern ) :
"""Determine whether the item supplied is matched by the pattern .""" | if pattern . endswith ( '*' ) :
return item . startswith ( pattern [ : - 1 ] )
else :
return item == pattern |
def remove_decorators ( src ) :
"""Remove decorators from the source code""" | src = src . strip ( )
src_lines = src . splitlines ( )
multi_line = False
n_deleted = 0
for n in range ( len ( src_lines ) ) :
line = src_lines [ n - n_deleted ] . strip ( )
if ( line . startswith ( '@' ) and 'Benchmark' in line ) or multi_line :
del src_lines [ n - n_deleted ]
n_deleted += 1
... |
def send_msg ( self , connection , data ) :
"""Function to send messages
Parameters
connection : socket or connection
data : data that can be serialized to json""" | # serialize as JSON
msg = json . dumps ( data )
# Prefix each message with a 4 - byte length ( network byte order )
msg = struct . pack ( '>I' , len ( msg ) ) . decode ( ) + msg
connection . sendall ( msg . encode ( ) )
return |
def list_network_ip_availabilities ( self , retrieve_all = True , ** _params ) :
"""Fetches IP availibility information for all networks""" | return self . list ( 'network_ip_availabilities' , self . network_ip_availabilities_path , retrieve_all , ** _params ) |
def authenticateRequest ( self , service_request , username , password , ** kwargs ) :
"""Processes an authentication request . If no authenticator is supplied ,
then authentication succeeds .
@ return : C { Deferred } .
@ rtype : C { twisted . internet . defer . Deferred }""" | authenticator = self . getAuthenticator ( service_request )
if self . logger :
self . logger . debug ( 'Authenticator expands to: %r' % authenticator )
if authenticator is None :
return defer . succeed ( True )
args = ( username , password )
if hasattr ( authenticator , '_pyamf_expose_request' ) :
http_requ... |
def set_printoptions ( ** kwargs ) :
"""Set printing options .
These options determine the way JPEG 2000 boxes are displayed .
Parameters
short : bool , optional
When True , only the box ID , offset , and length are displayed . Useful
for displaying only the basic structure or skeleton of a JPEG 2000
fi... | warnings . warn ( 'Use set_option instead of set_printoptions.' , DeprecationWarning )
for key , value in kwargs . items ( ) :
if key not in [ 'short' , 'xml' , 'codestream' ] :
raise KeyError ( '"{0}" not a valid keyword parameter.' . format ( key ) )
set_option ( 'print.' + key , value ) |
def get_type_string ( item ) :
"""Return type string of an object .""" | if isinstance ( item , DataFrame ) :
return "DataFrame"
if isinstance ( item , Index ) :
return type ( item ) . __name__
if isinstance ( item , Series ) :
return "Series"
found = re . findall ( r"<(?:type|class) '(\S*)'>" , to_text_string ( type ( item ) ) )
if found :
return found [ 0 ] |
def decode ( self , hashid ) :
"""Restore a tuple of numbers from the passed ` hashid ` .
: param hashid The hashid to decode
> > > hashids = Hashids ( ' arbitrary salt ' , 16 , ' abcdefghijkl0123456 ' )
> > > hashids . decode ( ' 1d6216i30h53elk3 ' )
(1 , 23 , 456)""" | if not hashid or not _is_str ( hashid ) :
return ( )
try :
numbers = tuple ( _decode ( hashid , self . _salt , self . _alphabet , self . _separators , self . _guards ) )
return numbers if hashid == self . encode ( * numbers ) else ( )
except ValueError :
return ( ) |
def remove_query_parameters ( request , query_parameters_to_remove ) :
"""Wrap replace _ query _ parameters ( ) for API backward compatibility .""" | replacements = [ ( k , None ) for k in query_parameters_to_remove ]
return replace_query_parameters ( request , replacements ) |
def alterar ( self , id_brand , name ) :
"""Change Brand from by the identifier .
: param id _ brand : Identifier of the Brand . Integer value and greater than zero .
: param name : Brand name . String with a minimum 3 and maximum of 100 characters
: return : None
: raise InvalidParameterError : The identif... | if not is_valid_int_param ( id_brand ) :
raise InvalidParameterError ( u'The identifier of Brand is invalid or was not informed.' )
url = 'brand/' + str ( id_brand ) + '/'
brand_map = dict ( )
brand_map [ 'name' ] = name
code , xml = self . submit ( { 'brand' : brand_map } , 'PUT' , url )
return self . response ( c... |
def _QName ( self , typ , defNS ) :
"""Get fully qualified wsdl name ( prefix : name )""" | attr = ''
ns , name = GetQualifiedWsdlName ( typ )
if ns == defNS :
prefix = ''
else :
try :
prefix = self . nsMap [ ns ]
except KeyError : # We have not seen this ns before
prefix = ns . split ( ':' , 1 ) [ - 1 ]
attr = ' xmlns:{0}="{1}"' . format ( prefix , ns )
return attr , prefi... |
def parse_buffer_to_jpeg ( data ) :
"""Parse JPEG file bytes to Pillow Image""" | return [ Image . open ( BytesIO ( image_data + b'\xff\xd9' ) ) for image_data in data . split ( b'\xff\xd9' ) [ : - 1 ] # Last element is obviously empty
] |
def log_with_color ( level ) :
"""log with color by different level""" | def wrapper ( text ) :
color = log_colors_config [ level . upper ( ) ]
getattr ( logger , level . lower ( ) ) ( coloring ( text , color ) )
return wrapper |
def Wp ( self ) :
"""Total energy in protons above 1.22 GeV threshold ( erg ) .""" | from scipy . integrate import quad
Eth = 1.22e-3
with warnings . catch_warnings ( ) :
warnings . simplefilter ( "ignore" )
Wp = quad ( lambda x : x * self . _particle_distribution ( x ) , Eth , np . Inf ) [ 0 ]
return ( Wp * u . TeV ) . to ( "erg" ) |
def pop_frame ( self ) :
"""Remove and return the frame at the top of the stack .
: returns : The top frame
: rtype : Frame
: raises Exception : If there are no frames on the stack""" | self . frames . pop ( 0 )
if len ( self . frames ) == 0 :
raise Exception ( "stack is exhausted" )
return self . frames [ 0 ] |
def register_image ( self , name = None , description = None , image_location = None , architecture = None , kernel_id = None , ramdisk_id = None , root_device_name = None , block_device_map = None ) :
"""Register an image .
: type name : string
: param name : The name of the AMI . Valid only for EBS - based im... | params = { }
if name :
params [ 'Name' ] = name
if description :
params [ 'Description' ] = description
if architecture :
params [ 'Architecture' ] = architecture
if kernel_id :
params [ 'KernelId' ] = kernel_id
if ramdisk_id :
params [ 'RamdiskId' ] = ramdisk_id
if image_location :
params [ 'Im... |
def listen_tta ( self , target , timeout ) :
"""Listen * timeout * seconds for a Type A activation at 106 kbps . The
` ` sens _ res ` ` , ` ` sdd _ res ` ` , and ` ` sel _ res ` ` response data must
be provided and ` ` sdd _ res ` ` must be a 4 byte UID that starts
with ` ` 08h ` ` . Depending on ` ` sel _ re... | return super ( Device , self ) . listen_tta ( target , timeout ) |
def iterate ( maybe_iter , unless = ( string_types , dict ) ) :
"""Always return an iterable .
Returns ` ` maybe _ iter ` ` if it is an iterable , otherwise it returns a single
element iterable containing ` ` maybe _ iter ` ` . By default , strings and dicts
are treated as non - iterable . This can be overrid... | if is_iterable ( maybe_iter , unless = unless ) :
return maybe_iter
return [ maybe_iter ] |
def run ( self ) : # No " _ " in the name , but nevertheless , running in the backed
"""After the fork . Now the process starts running""" | self . preRun_ ( )
self . running = True
while ( self . running ) :
if ( self . active ) : # activated : shared mem client has been reserved
self . cycle_ ( )
else :
if ( self . verbose ) :
print ( self . pre , "sleep" )
time . sleep ( 0.2 )
self . handleSignal_ ( )
self ... |
def untldict_normalizer ( untl_dict , normalizations ) :
"""Normalize UNTL elements by their qualifier .
Takes a UNTL descriptive metadata dictionary and a dictionary of
the elements and the qualifiers for normalization :
{ ' element1 ' : [ ' qualifier1 ' , ' qualifier2 ' ] ,
' element2 ' : [ ' qualifier3 '... | # Loop through the element types in the UNTL metadata .
for element_type , element_list in untl_dict . items ( ) : # A normalization is required for that element type .
if element_type in normalizations : # Get the required normalizations for specific qualifiers list .
norm_qualifier_list = normalizations .... |
def _drop_privs ( self ) :
"""Reduces effective privileges for this process to that of the task
owner . The umask and environment variables are also modified to
recreate the environment of the user .""" | uid = self . _task . owner
# get pwd database info for task owner
try :
pwd_info = pwd . getpwuid ( uid )
except OSError :
pwd_info = None
# set secondary group ids for user , must come first
if pwd_info :
try :
gids = [ g . gr_gid for g in grp . getgrall ( ) if pwd_info . pw_name in g . gr_mem ]
... |
def max_entropy_distribution ( node_indices , number_of_nodes ) :
"""Return the maximum entropy distribution over a set of nodes .
This is different from the network ' s uniform distribution because nodes
outside ` ` node _ indices ` ` are fixed and treated as if they have only 1
state .
Args :
node _ ind... | distribution = np . ones ( repertoire_shape ( node_indices , number_of_nodes ) )
return distribution / distribution . size |
def set_blend_func ( self , srgb = 'one' , drgb = 'zero' , salpha = None , dalpha = None ) :
"""Specify pixel arithmetic for RGB and alpha
Parameters
srgb : str
Source RGB factor .
drgb : str
Destination RGB factor .
salpha : str | None
Source alpha factor . If None , ` ` srgb ` ` is used .
dalpha :... | salpha = srgb if salpha is None else salpha
dalpha = drgb if dalpha is None else dalpha
self . glir . command ( 'FUNC' , 'glBlendFuncSeparate' , srgb , drgb , salpha , dalpha ) |
def update_metadata ( self , resource , keys_vals ) :
"""Updates key - value pairs with the given resource .
Will attempt to update all key - value pairs even if some fail .
Keys must already exist .
Args :
resource ( intern . resource . boss . BossResource )
keys _ vals ( dictionary ) : Collection of key... | self . metadata_service . set_auth ( self . _token_metadata )
self . metadata_service . update ( resource , keys_vals ) |
def main ( ) :
"""NAME
core _ depthplot . py
DESCRIPTION
plots various measurements versus core _ depth or age . plots data flagged as ' FS - SS - C ' as discrete samples .
SYNTAX
core _ depthplot . py [ command line options ]
# or , for Anaconda users :
core _ depthplot _ anaconda [ command line opti... | args = sys . argv
if '-h' in args :
print ( main . __doc__ )
sys . exit ( )
dataframe = extractor . command_line_dataframe ( [ [ 'f' , False , 'measurements.txt' ] , [ 'fsum' , False , '' ] , [ 'fwig' , False , '' ] , [ 'fsa' , False , '' ] , [ 'fa' , False , '' ] , [ 'fsp' , False , '' ] , [ 'fres' , False , '... |
def validate ( cls , value ) :
"""Raise | ValueError | if * value * is not an assignable value .""" | if value not in cls . _valid_settings :
raise ValueError ( "%s not a member of %s enumeration" % ( value , cls . __name__ ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.