signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_all_destinations ( self , server_id ) :
"""Return all listener destinations in a WBEM server .
This function contacts the WBEM server and retrieves the listener
destinations by enumerating the instances of CIM class
" CIM _ ListenerDestinationCIMXML " in the Interop namespace of the WBEM
server .
... | # Validate server _ id
server = self . _get_server ( server_id )
return server . conn . EnumerateInstances ( DESTINATION_CLASSNAME , namespace = server . interop_ns ) |
def getModulePath ( project_path , module_name , verbose ) :
'''Searches for module _ name in searchpath and returns the filepath .
If no filepath was found , returns None .''' | if not module_name :
return None
sys . path . append ( project_path )
try :
package = pkgutil . get_loader ( module_name )
except ImportError :
if verbose :
print ( "Parent module for " + module_name + " not found." )
return None
except :
if verbose :
print ( module_name + " not load... |
def _get_corenlp_version ( ) :
"Return the corenlp version pointed at by CORENLP _ HOME , or None" | corenlp_home = os . environ . get ( "CORENLP_HOME" )
if corenlp_home :
for fn in os . listdir ( corenlp_home ) :
m = re . match ( "stanford-corenlp-([\d.]+)-models.jar" , fn )
if m :
return m . group ( 1 ) |
def _all_resources ( self ) :
"""Return the complete collection of resources as a list of
dictionaries .
: rtype : : class : ` sandman2 . model . Model `""" | queryset = self . __model__ . query
args = { k : v for ( k , v ) in request . args . items ( ) if k not in ( 'page' , 'export' ) }
limit = None
if args :
filters = [ ]
order = [ ]
for key , value in args . items ( ) :
if value . startswith ( '%' ) :
filters . append ( getattr ( self . __... |
def is_cross_origin ( request ) :
"""Compare headers HOST and ORIGIN . Remove protocol prefix from ORIGIN , then
compare . Return true if they are not equal
example HTTP _ HOST : ' 127.0.0.1:5000'
example HTTP _ ORIGIN : ' http : / / 127.0.0.1:5000'""" | origin = request . environ . get ( "HTTP_ORIGIN" )
host = request . environ . get ( "HTTP_HOST" )
if origin is None : # origin is sometimes omitted by the browser when origin and host are equal
return False
if origin . startswith ( "http://" ) :
origin = origin . replace ( "http://" , "" )
elif origin . startsw... |
def reverseCommit ( self ) :
"""Re - insert the previously deleted line .""" | if self . markerPos is None :
return
# Remove the specified string from the same position in every line
# in between the mark and the cursor ( inclusive ) .
col = min ( ( self . markerPos [ 1 ] , self . cursorPos [ 1 ] ) )
for line in range ( self . markerPos [ 0 ] , self . cursorPos [ 0 ] + 1 ) :
self . qteWid... |
def get_ids_from_folder ( path , part_name ) :
"""Return all ids from the given folder , which have a corresponding beamformedSignal file .""" | valid_ids = set ( { } )
for xml_file in glob . glob ( os . path . join ( path , '*.xml' ) ) :
idx = os . path . splitext ( os . path . basename ( xml_file ) ) [ 0 ]
if idx not in BAD_FILES [ part_name ] :
valid_ids . add ( idx )
return valid_ids |
def _compute_mean ( map1 , map2 ) :
"""Make a map that is the mean of two maps""" | data = ( map1 . data + map2 . data ) / 2.
return HpxMap ( data , map1 . hpx ) |
def lines_intersect ( pt1_p , pt2_p , pt1_q , pt2_q ) :
'''Return true if two line segments intersect
pt1 _ p , pt2 _ p - endpoints of first line segment
pt1 _ q , pt2 _ q - endpoints of second line segment''' | # The idea here is to do the cross - product of the vector from
# point 1 to point 2 of one segment against the cross products from
# both points of the other segment . If any of the cross products are zero ,
# the point is colinear with the line . If the cross products differ in
# sign , then one point is on one side ... |
def _qname ( self , name ) :
"""Convert name to an XML QName
e . g . pdf : Producer - > { http : / / ns . adobe . com / pdf / 1.3 / } Producer""" | if isinstance ( name , QName ) :
return name
if not isinstance ( name , str ) :
raise TypeError ( "{} must be str" . format ( name ) )
if name == '' :
return name
if name . startswith ( '{' ) :
return name
prefix , tag = name . split ( ':' , maxsplit = 1 )
uri = self . NS [ prefix ]
return QName ( uri ,... |
def remove_user ( self , user_name , role ) :
"""Calls CF ' s remove user with org""" | role_uri = self . _get_role_uri ( role = role )
return self . api . delete ( path = role_uri , data = { 'username' : user_name } ) |
def file_w_create_directories ( filepath ) :
"""Recursively create some directories if needed so that the directory where
@ filepath must be written exists , then open it in " w " mode and return the
file object .""" | dirname = os . path . dirname ( filepath )
if dirname and dirname != os . path . curdir and not os . path . isdir ( dirname ) :
os . makedirs ( dirname )
return open ( filepath , 'w' ) |
def do_get ( self , line ) :
"""get < peer >
eg . get sw1""" | def f ( p , args ) :
print ( p . get ( ) )
self . _request ( line , f ) |
def search_normalize ( self , results ) :
"""Append host id to search results to be able to initialize found
: class : ` Interface ` successfully""" | for interface in results :
interface [ u'host_id' ] = self . host . id
# pylint : disable = no - member
return super ( Interface , self ) . search_normalize ( results ) |
def get_report ( self , value ) :
"""Return provided field Python value formatted for use in report filter""" | if self . multiselect :
value = value or [ ]
children = [ ]
for child in value :
children . append ( self . cast_to_report ( child ) )
return children
return self . cast_to_report ( value ) |
def union ( self , other ) :
"""OR together version ranges .
Calculates the union of this range with one or more other ranges .
Args :
other : VersionRange object ( or list of ) to OR with .
Returns :
New VersionRange object representing the union .""" | if not hasattr ( other , "__iter__" ) :
other = [ other ]
bounds = self . bounds [ : ]
for range in other :
bounds += range . bounds
bounds = self . _union ( bounds )
range = VersionRange ( None )
range . bounds = bounds
return range |
def installed ( name , nodataset = False , brand_opts = None ) :
'''Ensure zone is installed
name : string
name of the zone
nodataset : boolean
do not create a ZFS file system
brand _ opts : boolean
brand specific options to pass''' | ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' }
zones = __salt__ [ 'zoneadm.list' ] ( installed = True , configured = True )
if name in zones :
if zones [ name ] [ 'state' ] == 'configured' :
if __opts__ [ 'test' ] :
res_install = { 'status' : True }
else :
... |
def similarities ( self , rank ) :
"""Returns similarity scores for models with specified rank .""" | self . _check_rank ( rank )
return [ result . similarity for result in self . results [ rank ] ] |
def update ( cls , domain , source , dest_add , dest_del ) :
"""Update a domain mail forward destinations .""" | result = None
if dest_add or dest_del :
current_destinations = cls . get_destinations ( domain , source )
fwds = current_destinations [ : ]
if dest_add :
for dest in dest_add :
if dest not in fwds :
fwds . append ( dest )
if dest_del :
for dest in dest_del :
... |
def to_dict ( self ) :
"""Get a dictionary representation of this item , formatted for Elasticsearch""" | out = { }
fields = self . __class__ . search_objects . mapping . properties . properties
for key in fields : # TODO : What if we ' ve mapped the property to a different name ? Will we allow that ?
attribute = getattr ( self , key )
field = fields [ key ]
# I believe this should take the highest priority .
... |
def get_predicate_indices ( tags : List [ str ] ) -> List [ int ] :
"""Return the word indices of a predicate in BIO tags .""" | return [ ind for ind , tag in enumerate ( tags ) if 'V' in tag ] |
def register_halfmaxes ( self , telescope , band , lower , upper ) :
"""Register precomputed half - max points .""" | if ( telescope , band ) in self . _halfmaxes :
raise AlreadyDefinedError ( 'half-max points for %s/%s already ' 'defined' , telescope , band )
self . _note ( telescope , band )
self . _halfmaxes [ telescope , band ] = ( lower , upper )
return self |
def _handle_hidden_tables ( self , tbl_list , attr_name ) :
"""Return list of tables , potentially removing hidden elements
Parameters
tbl _ list : list of node - like
Type of list elements will vary depending upon parser used
attr _ name : str
Name of the accessor for retrieving HTML attributes
Returns... | if not self . displayed_only :
return tbl_list
return [ x for x in tbl_list if "display:none" not in getattr ( x , attr_name ) . get ( 'style' , '' ) . replace ( " " , "" ) ] |
def copy ( self , source_table , dest_table , create_disposition = CreateDisposition . CREATE_IF_NEEDED , write_disposition = WriteDisposition . WRITE_TRUNCATE ) :
"""Copies ( or appends ) a table to another table .
: param source _ table :
: type source _ table : BQTable
: param dest _ table :
: type dest ... | job = { "configuration" : { "copy" : { "sourceTable" : { "projectId" : source_table . project_id , "datasetId" : source_table . dataset_id , "tableId" : source_table . table_id , } , "destinationTable" : { "projectId" : dest_table . project_id , "datasetId" : dest_table . dataset_id , "tableId" : dest_table . table_id ... |
def dump_results ( self , success ) :
"""Dump simulation results to ` ` dat ` ` and ` ` lst ` ` files
Returns
None""" | system = self . system
t , _ = elapsed ( )
if success and ( not system . files . no_output ) : # system . varout . dump ( )
system . varout . dump_np_vars ( )
_ , s = elapsed ( t )
logger . info ( 'Simulation data dumped in {:s}.' . format ( s ) ) |
def add_permute ( self , name , dim , input_name , output_name ) :
"""Add a permute layer . Assumes that the input has dimensions in the order [ Seq , C , H , W ]
Parameters
name : str
The name of this layer .
dim : tuple
The order in which to permute the input dimensions = [ seq , C , H , W ] .
Must ha... | spec = self . spec
nn_spec = self . nn_spec
# Add a new layer
spec_layer = nn_spec . layers . add ( )
spec_layer . name = name
spec_layer . input . append ( input_name )
spec_layer . output . append ( output_name )
spec_layer_params = spec_layer . permute
spec_layer_params . axis . extend ( list ( dim ) )
if len ( dim ... |
def split_url ( url ) :
"""Split the given URL ` ` base # anchor ` ` into ` ` ( base , anchor ) ` ` ,
or ` ` ( base , None ) ` ` if no anchor is present .
In case there are two or more ` ` # ` ` characters ,
return only the first two tokens : ` ` a # b # c = > ( a , b ) ` ` .
: param string url : the url
... | if url is None :
return ( None , None )
array = url . split ( "#" )
if len ( array ) == 1 :
array . append ( None )
return tuple ( array [ 0 : 2 ] ) |
def with_result_cache ( func ) :
"""Decorator specifically for is _ active . If self . result _ cache is set to a { }
the is _ active results will be cached for each set of params .""" | def inner ( self , * args , ** kwargs ) :
dic = self . result_cache
cache_key = None
if dic is not None :
cache_key = ( args , tuple ( kwargs . items ( ) ) )
try :
result = dic . get ( cache_key )
except TypeError as e : # not hashable
log . debug ( 'Switchboa... |
def _OpenFilesForRead ( self , metadata_value_pairs , token ) :
"""Open files all at once if necessary .""" | aff4_paths = [ result . AFF4Path ( metadata . client_urn ) for metadata , result in metadata_value_pairs ]
fds = aff4 . FACTORY . MultiOpen ( aff4_paths , mode = "r" , token = token )
fds_dict = dict ( [ ( fd . urn , fd ) for fd in fds ] )
return fds_dict |
def __stopOpenThread ( self ) :
"""stop OpenThread stack
Returns :
True : successful to stop OpenThread stack and thread interface down
False : fail to stop OpenThread stack""" | print 'call stopOpenThread'
try :
if self . __sendCommand ( 'thread stop' ) [ 0 ] == 'Done' :
return self . __sendCommand ( 'ifconfig down' ) [ 0 ] == 'Done'
else :
return False
except Exception , e :
ModuleHelper . WriteIntoDebugLogger ( "stopOpenThread() Error: " + str ( e ) ) |
def fix_360_to_0 ( self ) :
'''Sometimes we have to create an arc using from _ angle and to _ angle computed numerically .
If from _ angle = = to _ angle , it may sometimes happen that a tiny discrepancy will make from _ angle > to _ angle , and instead of
getting a 0 - length arc we end up with a 360 - degree ... | if abs ( self . from_angle - self . to_angle ) < tol :
self . from_angle = self . to_angle |
def _parse_caption ( self , node , state ) :
"""Parse a Caption of the node .
: param node : The lxml node to parse
: param state : The global state necessary to place the node in context
of the document as a whole .""" | if node . tag not in [ "caption" , "figcaption" ] : # captions used in Tables
return state
# Add a Caption
parent = state [ "parent" ] [ node ]
stable_id = ( f"{state['document'].name}" f"::" f"{'caption'}" f":" f"{state['caption']['idx']}" )
# Set name for Section
name = node . attrib [ "name" ] if "name" in node ... |
def event_doctree_resolved ( app , doctree , _ ) :
"""Called by Sphinx after phase 3 ( resolving ) .
* Replace Imgur text nodes with data from the Sphinx cache .
* Call finalizer for ImgurImageNode nodes .
: param sphinx . application . Sphinx app : Sphinx application object .
: param docutils . nodes . doc... | album_cache = app . builder . env . imgur_album_cache
image_cache = app . builder . env . imgur_image_cache
for node in doctree . traverse ( ImgurTextNode ) :
cache = album_cache if node . album else image_cache
if node . name == 'imgur-description' :
text = cache [ node . imgur_id ] . description
e... |
def insert ( self , parent , position , row = None ) :
"""insert ( parent , position , row = None )
: param parent :
A valid : obj : ` Gtk . TreeIter ` , or : obj : ` None `
: type parent : : obj : ` Gtk . TreeIter ` or : obj : ` None `
: param position :
position to insert the new row , or - 1 for last
... | return self . _do_insert ( parent , position , row ) |
def next_time_open ( location ) :
"""Returns the next possible opening hours object , or ( False , None )
if location is currently open or there is no such object
I . e . when is the company open for the next time ?""" | if not is_open ( location ) :
now = get_now ( )
now_time = datetime . time ( now . hour , now . minute , now . second )
found_opening_hours = False
for i in range ( 8 ) :
l_weekday = ( now . isoweekday ( ) + i ) % 7
ohs = OpeningHours . objects . filter ( company = location , weekday = l... |
def type_complexity ( type_ ) :
"""Computes an indicator for the complexity of ` type _ ` .
If the return value is 0 , the supplied type is not parameterizable .
Otherwise , set bits in the return value denote the following features :
- bit 0 : The type could be parameterized but is not .
- bit 1 : The type... | if ( not typing or not isinstance ( type_ , ( typing . TypingMeta , GenericWrapperMeta ) ) or type_ is AnyType ) :
return 0
if issubclass ( type_ , typing . Union ) :
return reduce ( operator . or_ , map ( type_complexity , type_ . __union_params__ ) )
if issubclass ( type_ , typing . Tuple ) :
if type_ . _... |
def get_exclusions ( path ) :
"""Generates exclusion patterns from a ` ` . dockerignore ` ` file located in the given path . Returns ` ` None ` ` if the
file does not exist .
: param path : Path to look up the ` ` . dockerignore ` ` in .
: type path : unicode | str
: return : List of patterns , that can be ... | if not os . path . isdir ( path ) :
return None
dockerignore_file = os . path . join ( path , '.dockerignore' )
if not os . path . isfile ( dockerignore_file ) :
return None
with open ( dockerignore_file , 'rb' ) as dif :
return list ( preprocess_matches ( dif . readlines ( ) ) ) |
def allinstances ( cls ) :
"""Return all instances that inherit from JB _ Gui
: returns : all instances that inherit from JB _ Gui
: rtype : list
: raises : None""" | JB_Gui . _allinstances = weakref . WeakSet ( [ i for i in cls . _allinstances if shiboken . isValid ( i ) ] )
return list ( cls . _allinstances ) |
def speed_heading ( msg ) :
"""Get speed and ground track ( or heading ) from the velocity message
( handles both airborne or surface message )
Args :
msg ( string ) : 28 bytes hexadecimal message string
Returns :
( int , float ) : speed ( kt ) , ground track or heading ( degree )""" | spd , trk_or_hdg , rocd , tag = velocity ( msg )
return spd , trk_or_hdg |
def __gen_struct_anno_files ( self , top_level_layer ) :
"""A struct annotation file contains node ( struct ) attributes ( of
non - token nodes ) . It is e . g . used to annotate the type of a syntactic
category ( NP , VP etc . ) .
See also : _ _ gen _ hierarchy _ file ( )""" | paula_id = '{0}.{1}.{2}_{3}_struct' . format ( top_level_layer , self . corpus_name , self . name , top_level_layer )
E , tree = gen_paula_etree ( paula_id )
base_paula_id = self . paulamap [ 'hierarchy' ] [ top_level_layer ]
mflist = E ( 'multiFeatList' , { XMLBASE : base_paula_id + '.xml' } )
for node_id in select_no... |
def stop ( self ) :
"""Tell the SocketIO thread to terminate .""" | if self . _thread :
_LOGGER . info ( "Stopping SocketIO thread..." )
# pylint : disable = W0212
self . _running = False
if self . _exit_event :
self . _exit_event . set ( )
self . _thread . join ( ) |
def format_status_json ( self ) :
"""Convert a Status object to json format .""" | status_json = { }
status_json [ 'code' ] = self . code
status_json [ 'message' ] = self . message
if self . details is not None :
status_json [ 'details' ] = self . details
return status_json |
def _deprecated_kwargs ( kwargs , arg_newarg ) :
"""arg _ newarg is a list of tuples , where each tuple has a pair of strings .
( ' old _ arg ' , ' new _ arg ' )
A DeprecationWarning is raised for the arguments that need to be
replaced .""" | warn_for = [ ]
for ( arg , new_kw ) in arg_newarg :
if arg in kwargs . keys ( ) :
val = kwargs . pop ( arg )
kwargs [ new_kw ] = val
warn_for . append ( ( arg , new_kw ) )
if len ( warn_for ) > 0 :
if len ( warn_for ) == 1 :
warnings . warn ( "Argument '{}' is deprecated. Use {} ... |
def _parse_distro_release_content ( line ) :
"""Parse a line from a distro release file .
Parameters :
* line : Line from the distro release file . Must be a unicode string
or a UTF - 8 encoded byte string .
Returns :
A dictionary containing all information items .""" | if isinstance ( line , bytes ) :
line = line . decode ( 'utf-8' )
matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN . match ( line . strip ( ) [ : : - 1 ] )
distro_info = { }
if matches : # regexp ensures non - None
distro_info [ 'name' ] = matches . group ( 3 ) [ : : - 1 ]
if matches . group ( 2 ) :
... |
def add ( self , event , message = None ) :
"""[ Decorator ] Add handler method .
: param event : Specify a kind of Event which you want to handle
: type event : T < = : py : class : ` linebot . models . events . Event ` class
: param message : ( optional ) If event is MessageEvent ,
specify kind of Message... | def decorator ( func ) :
if isinstance ( message , ( list , tuple ) ) :
for it in message :
self . __add_handler ( func , event , message = it )
else :
self . __add_handler ( func , event , message = message )
return func
return decorator |
def size ( self , time ) :
"""Gets the size of the object at a given time .
Args :
time : Time value being queried .
Returns :
size of the object in pixels""" | if self . start_time <= time <= self . end_time :
return self . masks [ time - self . start_time ] . sum ( )
else :
return 0 |
def append_value_continuation ( self , linenum , indent , continuation ) :
""": param linenum : The line number of the frame .
: type linenum : int
: param indent : The indentation level of the frame .
: type indent : int
: param continuation :
: type continuation : str""" | frame = self . current_frame ( )
assert isinstance ( frame , FieldFrame ) or isinstance ( frame , ValueContinuationFrame )
if isinstance ( frame , FieldFrame ) :
assert frame . indent < indent and frame . container . contains ( ROOT_PATH , frame . field_name )
if isinstance ( frame , ValueContinuationFrame ) :
... |
def transform ( self , data ) :
""": param data :
: type data : dict
: return :
: rtype :""" | out = [ ]
keys = sorted ( data . keys ( ) )
for k in keys :
out . append ( "%s=%s" % ( k , data [ k ] ) )
return "\n" . join ( out ) |
def get_objs_from_record ( self , record , key ) :
"""Returns a mapping of UID - > object""" | uids = self . get_uids_from_record ( record , key )
objs = map ( self . get_object_by_uid , uids )
return dict ( zip ( uids , objs ) ) |
def _find_contpix_given_cuts ( f_cut , sig_cut , wl , fluxes , ivars ) :
"""Find and return continuum pixels given the flux and sigma cut
Parameters
f _ cut : float
the upper limit imposed on the quantity ( fbar - 1)
sig _ cut : float
the upper limit imposed on the quantity ( f _ sig )
wl : numpy ndarra... | f_bar = np . median ( fluxes , axis = 0 )
sigma_f = np . var ( fluxes , axis = 0 )
bad = np . logical_and ( f_bar == 0 , sigma_f == 0 )
cont1 = np . abs ( f_bar - 1 ) <= f_cut
cont2 = sigma_f <= sig_cut
contmask = np . logical_and ( cont1 , cont2 )
contmask [ bad ] = False
return contmask |
def access_specifier ( self ) :
"""Retrieves the access specifier ( if any ) of the entity pointed at by the
cursor .""" | if not hasattr ( self , '_access_specifier' ) :
self . _access_specifier = conf . lib . clang_getCXXAccessSpecifier ( self )
return AccessSpecifier . from_id ( self . _access_specifier ) |
def build_increments ( self ) :
"""experimental method to calculate parameter increments for use
in the finite difference pertubation calculations
Note
user beware !""" | self . enforce_bounds ( )
self . add_transform_columns ( )
par_groups = self . parameter_data . groupby ( "pargp" ) . groups
inctype = self . parameter_groups . groupby ( "inctyp" ) . groups
for itype , inc_groups in inctype . items ( ) :
pnames = [ ]
for group in inc_groups :
pnames . extend ( par_grou... |
async def create ( self , ** kwargs ) :
'''Corresponds to POST request without a resource identifier , inserting a document into the database''' | try : # create model
obj = self . _meta . object_class ( )
# deserialize data from request body
self . data . update ( kwargs )
await obj . deserialize ( self . data )
# create document in DB
await obj . insert ( db = self . db )
# serialize object for response
return await obj . seriali... |
def request ( func = None , timeout = 600 ) :
"""use to request an api call from a specific endpoint""" | if func is None :
return partial ( request , timeout = timeout )
@ wraps ( func )
def wrapper ( self , * args , ** kwargs ) :
params = func ( self , * args , ** kwargs )
self = params . pop ( 'self' , None )
entity = params . pop ( 'entity' , None )
app_name = params . pop ( 'app_name' , None )
... |
def get_language_settings ( language_code , site_id = None ) :
"""Return the language settings for the current site""" | # This method mainly exists for ease - of - use .
# the body is part of the settings , to allow third party packages
# to have their own variation of the settings with this method functionality included .
from parler import appsettings
return appsettings . PARLER_LANGUAGES . get_language ( language_code , site_id ) |
def _finalize_step ( self ) :
"""Finalize simulation step after all agents have acted for the current
step .""" | t = time . time ( )
if self . _callback is not None :
self . _callback ( self . age )
t2 = time . time ( )
self . _step_processing_time += t2 - t
self . _log ( logging . INFO , "Step {} run in: {:.3f}s ({:.3f}s of " "actual processing time used)" . format ( self . age , self . _step_processing_time , t2 - self . _s... |
def filter_devices ( ads , func ) :
"""Finds the AndroidDevice instances from a list that match certain
conditions .
Args :
ads : A list of AndroidDevice instances .
func : A function that takes an AndroidDevice object and returns True
if the device satisfies the filter condition .
Returns :
A list of... | results = [ ]
for ad in ads :
if func ( ad ) :
results . append ( ad )
return results |
def oauth_session ( request , state = None , token = None ) :
"""Constructs the OAuth2 session object .""" | if settings . DISCORD_REDIRECT_URI is not None :
redirect_uri = settings . DISCORD_REDIRECT_URI
else :
redirect_uri = request . build_absolute_uri ( reverse ( 'discord_bind_callback' ) )
scope = ( [ 'email' , 'guilds.join' ] if settings . DISCORD_EMAIL_SCOPE else [ 'identity' , 'guilds.join' ] )
return OAuth2Se... |
def parse_condition ( self , schema , name , v ) :
"""Parse name = ' value ' to condition
: param name : column name
: param schema : schema name
: param v : column value
: return :""" | S = schema
col = S . get_column ( name )
condition = None
if col is not None : # can create condition
if isinstance ( v , ( str , unicode ) ) :
if v . startswith ( '>=' ) :
condition = ( col >= eval ( v [ 2 : ] . strip ( ) ) )
elif v . startswith ( '>' ) :
condition = ( col >... |
def parse_args_and_run ( ) :
""": return : The parsed arguments""" | parser = argparse . ArgumentParser ( )
subparsers = parser . add_subparsers ( help = 'Docker-tag-naming sub-commands' , dest = 'subparser_name' )
# Forge
parser_forge = subparsers . add_parser ( 'forge' , help = 'Create a new version tag' )
parser_forge . add_argument ( '--version' , type = int , default = 1 , help = '... |
async def create_source_event_stream ( schema : GraphQLSchema , document : DocumentNode , root_value : Any = None , context_value : Any = None , variable_values : Dict [ str , Any ] = None , operation_name : str = None , field_resolver : GraphQLFieldResolver = None , ) -> Union [ AsyncIterable [ Any ] , ExecutionResult... | # If arguments are missing or incorrectly typed , this is an internal developer
# mistake which should throw an early error .
assert_valid_execution_arguments ( schema , document , variable_values )
# If a valid context cannot be created due to incorrect arguments , this will throw
# an error .
context = ExecutionConte... |
def parse_get_params ( request ) :
"""parse all url get params that contains dots in a representation of
serializer field names , for example : d . docs . limit to d _ docs _ limit .
that makes compatible an actual API client with django - rest - framework
serializers .
: param request :
: return : QueryD... | get = request . GET . copy ( )
new_get = request . GET . copy ( )
for key in get . iterkeys ( ) :
if key . count ( "." ) > 0 :
new_key = key . replace ( "." , "_" )
new_get [ new_key ] = get . get ( key )
del new_get [ key ]
return new_get |
def end_of_day ( val ) :
"""Return a new datetime . datetime object with values that represent
a end of a day .
: param val : Date to . . .
: type val : datetime . datetime | datetime . date
: rtype : datetime . datetime""" | if type ( val ) == date :
val = datetime . fromordinal ( val . toordinal ( ) )
return start_of_day ( val ) + timedelta ( days = 1 , microseconds = - 1 ) |
def process ( self , args = argv , input_file = stdin , output_file = stdout ) :
"""Processes search results as specified by command arguments .
: param args : Sequence of command arguments
: param input _ file : Pipeline input file
: param output _ file : Pipeline output file""" | self . logger . debug ( u'%s arguments: %s' , type ( self ) . __name__ , args )
self . _configuration = None
self . _output_file = output_file
try :
if len ( args ) >= 2 and args [ 1 ] == '__GETINFO__' :
ConfigurationSettings , operation , args , reader = self . _prepare ( args , input_file = None )
... |
def create_fuzzy_pattern ( pattern ) :
"""Convert a string into a fuzzy regular expression pattern .
: param pattern : The input pattern ( a string ) .
: returns : A compiled regular expression object .
This function works by adding ` ` . * ` ` between each of the characters in the
input pattern and compili... | return re . compile ( ".*" . join ( map ( re . escape , pattern ) ) , re . IGNORECASE ) |
def set_forbidden_alien ( self , alien ) :
"""Set all forbidden alien values
: param alienes : a list with forbidden alien values
: alien alienes : list
: returns : None
: ralien : None
: raises : None""" | if self . _forbidden_alien == alien :
return
self . _forbidden_alien = alien
self . invalidateFilter ( ) |
def submit_mail ( self , send_from , send_to , subject , body , unique_id = None ) :
"""Добавляем письмо в очередь на отправку
: param send _ from : Отправитель
: param send _ to : Получатель
: param subject : Тема письма
: param body : Тело письма . Можно с HTML
: param unique _ id : Уникальный идентифи... | self . __metadb . update ( """
INSERT INTO meta.mail("template", "from", "to", "subject", "body", "attachments", "unique_id")
VALUES ('meta', :send_from, :send_to, :subject, :body, null, :unique_id)
ON CONFLICT (unique_id) DO NOTHING
""" , { "send_from" : send_from , "send_to" : send_to ... |
def store_data ( name , data = None , delete = False , newname = None ) :
"""This function creates a " Tplot Variable " based on the inputs , and
stores this data in memory . Tplot Variables store all of the information
needed to generate a plot .
Parameters :
name : str
Name of the tplot variable that wi... | global tplot_num
create_time = datetime . datetime . now ( )
if delete is True :
del_data ( name )
return
if data is None and newname is None :
print ( 'Please provide data.' )
return
if newname is not None :
pytplot . tplot_rename ( name , newname )
return
if isinstance ( data , list ) :
ba... |
def POST ( self , ** kwargs ) :
'''Send one or more Salt commands in the request body
. . http : post : : /
: reqheader X - Auth - Token : | req _ token |
: reqheader Accept : | req _ accept |
: reqheader Content - Type : | req _ ct |
: resheader Content - Type : | res _ ct |
: status 200 : | 200 |
: ... | return { 'return' : list ( self . exec_lowstate ( token = cherrypy . session . get ( 'token' ) ) ) } |
def inverse_jacobian ( self , maps ) :
"""Returns the Jacobian for transforming mass1 and mass2 to
mchirp and eta .""" | m1 = maps [ parameters . mass1 ]
m2 = maps [ parameters . mass2 ]
mchirp = conversions . mchirp_from_mass1_mass2 ( m1 , m2 )
eta = conversions . eta_from_mass1_mass2 ( m1 , m2 )
return - 1. * mchirp / eta ** ( 6. / 5 ) |
def read_worker ( args , q_in , q_out ) :
"""Function that will be spawned to fetch the image
from the input queue and put it back to output queue .
Parameters
args : object
q _ in : queue
q _ out : queue""" | while True :
deq = q_in . get ( )
if deq is None :
break
i , item = deq
image_encode ( args , i , item , q_out ) |
def solve_equilibrium_point ( self , analyzer1 , analyzer2 , delu_dict = { } , delu_default = 0 , units = "nanometers" ) :
"""Gives the radial size of two particles where equilibrium is reached
between both particles . NOTE : the solution here is not the same
as the solution visualized in the plot because solvi... | # Set up
wulff1 = analyzer1 . wulff_from_chempot ( delu_dict = delu_dict , delu_default = delu_default , symprec = self . symprec )
wulff2 = analyzer2 . wulff_from_chempot ( delu_dict = delu_dict , delu_default = delu_default , symprec = self . symprec )
# Now calculate r
delta_gamma = wulff1 . weighted_surface_energy ... |
def onSelect_specimen ( self , event ) :
"""update figures and text when a new specimen is selected""" | self . selected_meas = [ ]
self . select_specimen ( str ( self . specimens_box . GetValue ( ) ) )
if self . ie_open :
self . ie . change_selected ( self . current_fit )
self . update_selection ( ) |
def ansi_format_iter ( self , x_start = 0 , y_start = 0 , width = None , height = None , frame = 0 , columns = 1 , downsample = 1 ) :
"""Return the ANSI escape sequence to render the image .
x _ start
Offset from the left of the image data to render from . Defaults to 0.
y _ start
Offset from the top of the... | image = self . get_image ( )
frames = [ ]
frame_count = 1 if not hasattr ( image , 'n_frames' ) else image . n_frames
if isinstance ( frame , int ) :
assert frame in range ( 0 , frame_count )
frames = [ frame ]
else :
frames = [ f for f in frame if f in range ( 0 , frame_count ) ]
if not width :
width =... |
def mkdir_p ( path_to_dir ) :
"""Make directory ( ies ) .
This function behaves like mkdir - p .
Args :
path _ to _ dir ( : obj : ` str ` ) : Path to the directory to make .""" | try :
os . makedirs ( path_to_dir )
except OSError as e : # Python > 2.5
if e . errno == EEXIST and os . path . isdir ( path_to_dir ) :
logger . debug ( "Directory %s already exists. Skipping." % path_to_dir )
else :
raise e |
def maximum_variation ( arr ) :
'''return np . max ( arr , axis = 0 ) - np . min ( arr , axis = 0)
If ` arr ` is a 1D array , a scalar is returned .
If ` arr ` is a 2D array ( N x M ) , an array of length M is returned .''' | return np . max ( arr , axis = 0 ) - np . min ( arr , axis = 0 ) |
def max_height ( self ) :
""": return : The max height of the rendered text ( across all images if an
animated renderer ) .""" | if len ( self . _plain_images ) <= 0 :
self . _convert_images ( )
if self . _max_height == 0 :
for image in self . _plain_images :
self . _max_height = max ( len ( image ) , self . _max_height )
return self . _max_height |
def _extract_t_indices ( self , X , X2 = None , dL_dK = None ) :
"""Extract times and output indices from the input matrix X . Times are ordered according to their index for convenience of computation , this ordering is stored in self . _ order and self . order2 . These orderings are then mapped back to the origina... | # TODO : some fast checking here to see if this needs recomputing ?
self . _t = X [ : , 0 ]
if not X . shape [ 1 ] == 2 :
raise ValueError ( 'Input matrix for ode1 covariance should have two columns, one containing times, the other output indices' )
self . _index = np . asarray ( X [ : , 1 ] , dtype = np . int )
# ... |
def set ( self , key , value , filepath ) :
"""Set configuration parameter .
Writes ' value ' on ' key ' to the configuration file given in
' filepath ' . Configuration parameter in ' key ' must follow the schema
< section > . < option > .
: param key : key to set
: param value : value to set
: param fi... | if not filepath :
raise RuntimeError ( "Configuration file not given" )
if not self . __check_config_key ( key ) :
raise RuntimeError ( "%s parameter does not exists or cannot be set" % key )
config = configparser . SafeConfigParser ( )
if os . path . isfile ( filepath ) :
config . read ( filepath )
section... |
def estimate_B ( xray_table , vhe_table , photon_energy_density = 0.261 * u . eV / u . cm ** 3 ) :
"""Estimate magnetic field from synchrotron to Inverse Compton luminosity
ratio
Estimate the magnetic field from the ratio of X - ray to gamma - ray emission
according to :
. . math : :
\\ frac { L _ \ mathr... | xray = validate_data_table ( xray_table , sed = False )
vhe = validate_data_table ( vhe_table , sed = False )
xray_lum = trapz_loglog ( xray [ "flux" ] * xray [ "energy" ] , xray [ "energy" ] )
vhe_lum = trapz_loglog ( vhe [ "flux" ] * vhe [ "energy" ] , vhe [ "energy" ] )
uph = ( photon_energy_density . to ( "erg/cm3"... |
def spawn_program ( self , name , arguments = [ ] , timeout = 30 , exclusive = False ) :
"""Spawns a program in the working directory .
This method allows the interaction with the running program ,
based on the returned RunningProgram object .
Args :
name ( str ) : The name of the program to be executed .
... | logger . debug ( "Spawning program for interaction ..." )
if exclusive :
kill_longrunning ( self . config )
return RunningProgram ( self , name , arguments , timeout ) |
def find_l50 ( contig_lengths_dict , genome_length_dict ) :
"""Calculate the L50 for each strain . L50 is defined as the number of contigs required to achieve the N50
: param contig _ lengths _ dict : dictionary of strain name : reverse - sorted list of all contig lengths
: param genome _ length _ dict : dictio... | # Initialise the dictionary
l50_dict = dict ( )
for file_name , contig_lengths in contig_lengths_dict . items ( ) :
currentlength = 0
# Initialise a variable to count how many contigs have been added to the currentlength variable
currentcontig = 0
for contig_length in contig_lengths :
currentlen... |
def draw ( self ) :
"""Draws the button in its current state .
Should be called every time through the main loop""" | if not self . visible :
return
# Blit the button ' s current appearance to the surface .
if self . isEnabled :
if self . mouseIsDown :
if self . mouseOverButton and self . lastMouseDownOverButton :
self . window . blit ( self . surfaceDown , self . loc )
else :
self . win... |
def __process_username_password ( self ) :
"""If indicated , process the username and password""" | if self . use_username_password_store is not None :
if self . args . clear_store :
with load_config ( sections = AUTH_SECTIONS ) as config :
config . remove_option ( AUTH_SECTION , 'username' )
if not self . args . username :
self . args . username = get_username ( use_store = self .... |
def register_view ( self , view ) :
"""Called when the View was registered""" | super ( ScopedVariableListController , self ) . register_view ( view )
view [ 'name_col' ] . add_attribute ( view [ 'name_text' ] , 'text' , self . NAME_STORAGE_ID )
if not isinstance ( self . model . state , LibraryState ) and self . model . state . get_next_upper_library_root_state ( ) is None :
view [ 'name_text... |
def _setup_simplejson ( self , responder ) :
"""We support serving simplejson for Python 2.4 targets on Ansible 2.3 , at
least so the package ' s own CI Docker scripts can run without external
help , however newer versions of simplejson no longer support Python
2.4 . Therefore override any installed / loaded ... | responder . whitelist_prefix ( 'simplejson' )
# issue # 536 : must be at end of sys . path , in case existing newer
# version is already loaded .
compat_path = os . path . join ( os . path . dirname ( __file__ ) , 'compat' )
sys . path . append ( compat_path )
for fullname , is_pkg , suffix in ( ( u'simplejson' , True ... |
def set_limit ( self , param ) :
"""Models " Limit Command " functionality of device .
Sets the target temperate to be reached .
: param param : Target temperature in C , multiplied by 10 , as a string . Can be negative .
: return : Empty string .""" | # TODO : Is not having leading zeroes / 4 digits an error ?
limit = int ( param )
if - 2000 <= limit <= 6000 :
self . device . temperature_limit = limit / 10.0
return "" |
def exclude_states ( omega , gamma , r , Lij , states , excluded_states ) :
"""Exclude states from matrices .
This function takes the matrices and excludes the states listed in
excluded _ states .""" | Ne = len ( omega )
excluded_indices = [ i for i in range ( Ne ) if states [ i ] in excluded_states ]
omega_new = [ ] ;
gamma_new = [ ] ;
r_new = [ [ ] , [ ] , [ ] ] ;
Lij_new = [ ]
for i in range ( Ne ) :
row_om = [ ] ;
row_ga = [ ] ;
row_L = [ ]
for j in range ( Ne ) :
if j not in excluded_indi... |
def generate_docs ( self ) :
"""Generates the output docstring""" | if self . dst . style [ 'out' ] == 'numpydoc' and self . dst . numpydoc . first_line is not None :
self . first_line = self . dst . numpydoc . first_line
self . _set_desc ( )
self . _set_params ( )
self . _set_return ( )
self . _set_raises ( )
self . _set_other ( )
self . _set_raw ( )
self . generated_docs = True |
def filter_sequences ( self , seq_type ) :
"""Return a DictList of only specified types in the sequences attribute .
Args :
seq _ type ( SeqProp ) : Object type
Returns :
DictList : A filtered DictList of specified object type only""" | return DictList ( x for x in self . sequences if isinstance ( x , seq_type ) ) |
def computeCovarianceOfSums ( self , d_ij , K , a ) :
"""We wish to calculate the variance of a weighted sum of free energy differences .
for example ` ` var ( \ sum a _ i df _ i ) ` ` .
We explicitly lay out the calculations for four variables ( where each variable
is a logarithm of a partition function ) , ... | # todo : vectorize this .
var_ij = np . square ( d_ij )
d2 = np . zeros ( [ K , K ] , float )
n = len ( a )
for i in range ( K ) :
for j in range ( K ) :
for k in range ( n ) :
d2 [ i , j ] += a [ k ] ** 2 * var_ij [ i + k * K , j + k * K ]
for l in range ( n ) :
d2 [... |
def _parse_hwtype ( self ) :
"""Convert the numerical hardware id to a chip name .""" | self . chip_name = KNOWN_HARDWARE_TYPES . get ( self . hw_type , "Unknown Chip (type=%d)" % self . hw_type ) |
def work_get ( self , wallet , account ) :
"""Retrieves work for * * account * * in * * wallet * *
. . enable _ control required
. . version 8.0 required
: param wallet : Wallet to get account work for
: type wallet : str
: param account : Account to get work for
: type account : str
: raises : : py :... | wallet = self . _process_value ( wallet , 'wallet' )
account = self . _process_value ( account , 'account' )
payload = { "wallet" : wallet , "account" : account }
resp = self . call ( 'work_get' , payload )
return resp [ 'work' ] |
def add_bond ( self , key1 , key2 , bond ) :
"""Set a bond . Existing bond will be overwritten .""" | self . graph . add_edge ( key1 , key2 , bond = bond ) |
def run_validators ( self , value ) :
"""validate value .
Uses document field ' s ` ` validate ( ) ` `""" | try :
self . model_field . validate ( value )
except MongoValidationError as e :
raise ValidationError ( e . message )
super ( DocumentField , self ) . run_validators ( value ) |
def java_timestamp ( timestamp = True ) :
""". . versionadded : : 0.2.0
Returns a timestamp in the format produced by | date _ tostring | _ , e . g . : :
Mon Sep 02 14:00:54 EDT 2016
If ` ` timestamp ` ` is ` True ` ( the default ) , the current date & time is
returned .
If ` ` timestamp ` ` is ` None ` o... | if timestamp is None or timestamp is False :
return ''
if isinstance ( timestamp , datetime ) and timestamp . tzinfo is not None :
timebits = timestamp . timetuple ( )
# Assumes ` timestamp . tzinfo . tzname ( ) ` is meaningful / useful
tzname = timestamp . tzname ( )
else :
if timestamp is True :
... |
def init_manual ( cls , pawn_value , knight_value , bishop_value , rook_value , queen_value , king_value ) :
"""Manual init method for external piece values
: type : PAWN _ VALUE : int
: type : KNIGHT _ VALUE : int
: type : BISHOP _ VALUE : int
: type : ROOK _ VALUE : int
: type : QUEEN _ VALUE : int""" | piece_values = cls ( )
piece_values . PAWN_VALUE = pawn_value
piece_values . KNIGHT_VALUE = knight_value
piece_values . BISHOP_VALUE = bishop_value
piece_values . ROOK_VALUE = rook_value
piece_values . QUEEN_VALUE = queen_value
piece_values . KING_VALUE = king_value
return piece_values |
def print_rows ( self , num_rows = 10 , num_columns = 40 , max_column_width = 30 , max_row_width = 80 , output_file = None ) :
"""Print the first M rows and N columns of the SFrame in human readable
format .
Parameters
num _ rows : int , optional
Number of rows to print .
num _ columns : int , optional
... | if output_file is None :
output_file = sys . stdout
max_row_width = max ( max_row_width , max_column_width + 1 )
printed_sf = self . _imagecols_to_stringcols ( num_rows )
row_of_tables = printed_sf . __get_pretty_tables__ ( wrap_text = False , max_rows_to_display = num_rows , max_columns = num_columns , max_column_... |
def _guess_concat ( data ) :
"""Guess concat function from given data""" | return { type ( u'' ) : u'' . join , type ( b'' ) : concat_bytes , } . get ( type ( data ) , list ) |
def set_main_and_cell_language ( metadata , cells , ext ) :
"""Set main language for the given collection of cells , and
use magics for cells that use other languages""" | main_language = ( metadata . get ( 'kernelspec' , { } ) . get ( 'language' ) or metadata . get ( 'jupytext' , { } ) . get ( 'main_language' ) or _SCRIPT_EXTENSIONS . get ( ext , { } ) . get ( 'language' ) )
if main_language is None :
languages = { 'python' : 0.5 }
for cell in cells :
if 'language' in ce... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.