signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def name2marc ( self , key , value ) :
"""Populates the ` ` 100 ` ` field .
Also populates the ` ` 400 ` ` , ` ` 880 ` ` , and ` ` 667 ` ` fields through side
effects .""" | result = self . get ( '100' , { } )
result [ 'a' ] = value . get ( 'value' )
result [ 'b' ] = value . get ( 'numeration' )
result [ 'c' ] = value . get ( 'title' )
result [ 'q' ] = value . get ( 'preferred_name' )
if 'name_variants' in value :
self [ '400' ] = [ { 'a' : el } for el in value [ 'name_variants' ] ]
if... |
def unblock ( self , item : str ) -> None :
"""Unblock an item and / or reset it ' s fail count
: param str item : The item to unblock""" | assert item is not None
item = self . _encode_item ( item )
watchlist_key = self . __redis_conf [ 'watchlist_template' ] . format ( item )
blacklist_key = self . __redis_conf [ 'blacklist_template' ] . format ( item )
connection = self . __get_connection ( )
connection . delete ( watchlist_key )
connection . delete ( b... |
def p_autoscaling_setting_list ( p ) :
"""autoscaling _ setting _ list : autoscaling _ setting autoscaling _ setting _ list
| autoscaling _ setting""" | if len ( p ) == 3 :
p [ 0 ] = merge_map ( p [ 1 ] , p [ 2 ] )
elif len ( p ) == 2 :
p [ 0 ] = p [ 1 ]
else :
raise RuntimeError ( "Invalid production in 'autoscaling_setting_list'" ) |
def _set_default_vrf ( self , v , load = False ) :
"""Setter method for default _ vrf , mapped from YANG variable / rbridge _ id / router / router _ bgp / address _ family / ipv6 / ipv6 _ unicast / default _ vrf ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ se... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = default_vrf . default_vrf , is_container = 'container' , presence = False , yang_name = "default-vrf" , rest_name = "" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = T... |
def resolve_file_path_list ( pathlist , workdir , prefix = '' , randomize = False ) :
"""Resolve the path of each file name in the file ` ` pathlist ` ` and
write the updated paths to a new file .""" | files = [ ]
with open ( pathlist , 'r' ) as f :
files = [ line . strip ( ) for line in f ]
newfiles = [ ]
for f in files :
f = os . path . expandvars ( f )
if os . path . isfile ( f ) :
newfiles += [ f ]
else :
newfiles += [ os . path . join ( workdir , f ) ]
if randomize :
_ , tmppa... |
def update ( self , url = values . unset , method = values . unset , status = values . unset , fallback_url = values . unset , fallback_method = values . unset , status_callback = values . unset , status_callback_method = values . unset ) :
"""Update the CallInstance
: param unicode url : The absolute URL that re... | return self . _proxy . update ( url = url , method = method , status = status , fallback_url = fallback_url , fallback_method = fallback_method , status_callback = status_callback , status_callback_method = status_callback_method , ) |
def getEthernetLinkStatus ( self , wanInterfaceId = 1 , timeout = 1 ) :
"""Execute GetEthernetLinkStatus action to get the status of the ethernet link .
: param int wanInterfaceId : the id of the WAN device
: param float timeout : the timeout to wait for the action to be executed
: return : status of the ethe... | namespace = Wan . getServiceType ( "getEthernetLinkStatus" ) + str ( wanInterfaceId )
uri = self . getControlURL ( namespace )
results = self . execute ( uri , namespace , "GetEthernetLinkStatus" , timeout = timeout )
return results [ "NewEthernetLinkStatus" ] |
def GetLoggingLocation ( ) :
"""Search for and return the file and line number from the log collector .
Returns :
( pathname , lineno , func _ name ) The full path , line number , and function name
for the logpoint location .""" | frame = inspect . currentframe ( )
this_file = frame . f_code . co_filename
frame = frame . f_back
while frame :
if this_file == frame . f_code . co_filename :
if 'cdbg_logging_location' in frame . f_locals :
ret = frame . f_locals [ 'cdbg_logging_location' ]
if len ( ret ) != 3 :
... |
def get_project ( self ) -> str :
"""Get the ihc project and make sure controller is ready before""" | with IHCController . _mutex :
if self . _project is None :
if self . client . get_state ( ) != IHCSTATE_READY :
ready = self . client . wait_for_state_change ( IHCSTATE_READY , 10 )
if ready != IHCSTATE_READY :
return None
self . _project = self . client . get... |
def main ( ) :
"""NAME
dmag _ magic2 . py
DESCRIPTION
plots intensity decay curves for demagnetization experiments
SYNTAX
dmag _ magic - h [ command line options ]
INPUT
takes magic formatted magic _ measurements . txt files
OPTIONS
- h prints help message and quits
- f FILE : specify input file... | FIG = { }
# plot dictionary
FIG [ 'demag' ] = 1
# demag is figure 1
in_file , plot_key , LT = 'magic_measurements.txt' , 'er_location_name' , "LT-AF-Z"
XLP = ""
norm = 1
LT = 'LT-AF-Z'
units , dmag_key = 'T' , 'treatment_ac_field'
plot = 0
fmt = 'svg'
if len ( sys . argv ) > 1 :
if '-h' in sys . argv :
prin... |
def CountHuntResultsByType ( self , hunt_id , cursor = None ) :
"""Counts number of hunts results per type .""" | hunt_id_int = db_utils . HuntIDToInt ( hunt_id )
query = ( "SELECT type, COUNT(*) FROM flow_results " "WHERE hunt_id = %s GROUP BY type" )
cursor . execute ( query , [ hunt_id_int ] )
return dict ( cursor . fetchall ( ) ) |
def _get_items_from_page ( self , item_type , items_key , resource , ) :
""": type item _ type : type
: type items _ key : str
: type resource : Dict [ str , Any ]
: rtype : Union [ List [ Dashboard ] , List [ Issue ] ]""" | try :
return [ item_type ( self . _options , self . _session , raw_issue_json ) for raw_issue_json in ( resource [ items_key ] if items_key else resource ) ]
except KeyError as e : # improving the error text so we know why it happened
raise KeyError ( str ( e ) + " : " + json . dumps ( resource ) ) |
def range_filter ( field , start_date_math = None , end_date_math = None , ** kwargs ) :
"""Create a range filter .
: param field : Field name .
: param start _ date _ math : Starting date .
: param end _ date _ math : Ending date .
: param kwargs : Addition arguments passed to the Range query .
: returns... | def inner ( values ) :
if len ( values ) != 1 or values [ 0 ] . count ( '--' ) != 1 or values [ 0 ] == '--' :
raise RESTValidationError ( errors = [ FieldError ( field , 'Invalid range format.' ) ] )
range_ends = values [ 0 ] . split ( '--' )
range_args = dict ( )
ineq_opers = [ { 'strict' : 'gt... |
def f ( self , y ) :
"""Transform y with f using parameter vector psi
psi = [ [ a , b , c ] ]
: math : ` f = ( y * d ) + \\ sum _ { terms } a * tanh ( b * ( y + c ) ) `""" | d = self . d
mpsi = self . psi
z = d * y . copy ( )
for i in range ( len ( mpsi ) ) :
a , b , c = mpsi [ i ]
z += a * np . tanh ( b * ( y + c ) )
return z |
def launch_run ( self , command , project = None , entity = None , run_id = None ) :
"""Launch a run in the cloud .
Args :
command ( str ) : The command to run
program ( str ) : The file to run
project ( str ) : The project to scope the runs to
entity ( str , optional ) : The entity to scope this project ... | query = gql ( '''
mutation launchRun(
$entity: String
$model: String
$runId: String
$image: String
$command: String
$patch: String
$cwd: String
$datasets: [String]
) {
launchRun(input: {id: $runId... |
def locate ( cls ) :
"""Locates the active PEX bootstrap .
: rtype : : class : ` Bootstrap `""" | if cls . _INSTANCE is None :
bootstrap_path = __file__
module_import_path = __name__ . split ( '.' )
# For example , our _ _ file _ _ might be requests . pex / . bootstrap / pex / bootstrap . pyc and our import
# path pex . bootstrap ; so we walk back through all the module components of our import path... |
def get_gpu_requirements ( gpus_reqs ) :
"""Extracts the GPU from a dictionary requirements as list of GPURequirements .
: param gpus _ reqs : A dictionary { ' count ' : < count > } or a list [ { min _ vram : < min _ vram > } , { min _ vram : < min _ vram > } , . . . ]
: return : A list of GPURequirements""" | requirements = [ ]
if gpus_reqs :
if type ( gpus_reqs ) is dict :
count = gpus_reqs . get ( 'count' )
if count :
for i in range ( count ) :
requirements . append ( GPURequirement ( ) )
elif type ( gpus_reqs ) is list :
for gpu_req in gpus_reqs :
re... |
def private_vlan_type ( self , ** kwargs ) :
"""Set the PVLAN type ( primary , isolated , community ) .
Args :
name ( str ) : VLAN ID .
pvlan _ type ( str ) : PVLAN type ( primary , isolated , community )
callback ( function ) : A function executed upon completion of the
method . The only parameter passed... | name = kwargs . pop ( 'name' )
pvlan_type = kwargs . pop ( 'pvlan_type' )
callback = kwargs . pop ( 'callback' , self . _callback )
allowed_pvlan_types = [ 'isolated' , 'primary' , 'community' ]
if not pynos . utilities . valid_vlan_id ( name ) :
raise InvalidVlanId ( "Incorrect name value." )
if pvlan_type not in ... |
def to_event ( self , event_type , field_name = None , depth = None ) :
"""Constructs an IonEvent from this _ IonNature value .
Args :
event _ type ( IonEventType ) : The type of the resulting event .
field _ name ( Optional [ text ] ) : The field name associated with this value , if any .
depth ( Optional ... | if self . ion_event is None :
value = self
if isinstance ( self , IonPyNull ) :
value = None
self . ion_event = IonEvent ( event_type , ion_type = self . ion_type , value = value , field_name = field_name , annotations = self . ion_annotations , depth = depth )
return self . ion_event |
def collect_compare_into ( left , right , added , removed , altered , same ) :
"""collect the results of compare into the given lists ( or None if
you do not wish to collect results of that type . Returns a tuple
of ( added , removed , altered , same )""" | for event , filename in compare ( left , right ) :
if event == LEFT :
group = removed
elif event == RIGHT :
group = added
elif event == DIFF :
group = altered
elif event == BOTH :
group = same
else :
assert False
if group is not None :
group . appe... |
def _cytomine_parameter_name_synonyms ( name , prefix = "--" ) :
"""For a given parameter name , returns all the possible usual synonym ( and the parameter itself ) . Optionally , the
function can prepend a string to the found names .
If a parameters has no known synonyms , the function returns only the prefixe... | synonyms = [ [ "host" , "cytomine_host" ] , [ "public_key" , "publicKey" , "cytomine_public_key" ] , [ "private_key" , "privateKey" , "cytomine_private_key" ] , [ "base_path" , "basePath" , "cytomine_base_path" ] , [ "id_software" , "cytomine_software_id" , "cytomine_id_software" , "idSoftware" , "software_id" ] , [ "i... |
def distinct ( table , key = None , count = None , presorted = False , buffersize = None , tempdir = None , cache = True ) :
"""Return only distinct rows in the table .
If the ` count ` argument is not None , it will be used as the name for an
additional field , and the values of the field will be the number of... | return DistinctView ( table , key = key , count = count , presorted = presorted , buffersize = buffersize , tempdir = tempdir , cache = cache ) |
def movefastq ( self ) :
"""Find . fastq files for each sample and move them to an appropriately named folder""" | logging . info ( 'Moving FASTQ files' )
# Iterate through each sample
for sample in self . metadata . runmetadata . samples : # Retrieve the output directory
outputdir = os . path . join ( self . path , sample . name )
# Find any fastq files with the sample name
fastqfiles = sorted ( glob ( os . path . join... |
def create_file_from_stream ( self , share_name , directory_name , file_name , stream , count , content_settings = None , metadata = None , progress_callback = None , max_connections = 1 , max_retries = 5 , retry_wait = 1.0 , timeout = None ) :
'''Creates a new file from a file / stream , or updates the content of ... | _validate_not_none ( 'share_name' , share_name )
_validate_not_none ( 'file_name' , file_name )
_validate_not_none ( 'stream' , stream )
_validate_not_none ( 'count' , count )
if count < 0 :
raise TypeError ( _ERROR_VALUE_NEGATIVE . format ( 'count' ) )
self . create_file ( share_name , directory_name , file_name ,... |
def create_context_menu ( self , event , shape ) :
'''Parameters
event : gtk . gdk . Event
GTK mouse click event .
shape : str
Electrode shape identifier ( e . g . , ` " electrode028 " ` ) .
Returns
gtk . Menu
Context menu .
. . versionchanged : : 0.13
- Deprecate hard - coded commands ( e . g . ,... | routes = self . df_routes . loc [ self . df_routes . electrode_i == shape , 'route_i' ] . astype ( int ) . unique ( ) . tolist ( )
def _connect_callback ( menu_item , command_signal , group , command , data ) :
callback_called = threading . Event ( )
def _callback ( signal , widget , * args ) :
if callb... |
def modify ( ctx , schema , uuid , object_filter , field , value ) :
"""Modify field values of objects""" | database = ctx . obj [ 'db' ]
model = database . objectmodels [ schema ]
obj = None
if uuid :
obj = model . find_one ( { 'uuid' : uuid } )
elif object_filter :
obj = model . find_one ( literal_eval ( object_filter ) )
else :
log ( 'No object uuid or filter specified.' , lvl = error )
if obj is None :
lo... |
def trans ( self , key ) -> str :
"""Root Example :
Translator ( )
Translator . trans ( ' messages . hello ' )
resources / lang / en / messages . lang will be opened
and parsed for { ' hello ' : ' Some english text ' }
If language is fr ,
resources / lang / fr / messages . lang will be opened
and pars... | key_list = self . __list_key ( key )
try :
current_selection = current_app . config [ 'LANGUAGE_PACKS' ] [ self . module_name ] [ self . app_language ]
except KeyError as error :
if current_app . config [ 'DEBUG' ] :
raise error
return None
for parsed_dot_key in key_list :
try :
current_... |
async def get_data ( self , raw : bool = True ) -> AnyStr :
"""The request body data .""" | try :
body_future = asyncio . ensure_future ( self . body )
raw_data = await asyncio . wait_for ( body_future , timeout = self . body_timeout )
except asyncio . TimeoutError :
body_future . cancel ( )
from . . exceptions import RequestTimeout
# noqa Avoiding circular import
raise RequestTimeout ... |
def save_csv ( data , # type : Iterable [ Tuple [ Union [ str , int ] , . . . ] ]
headers , # type : Iterable [ str ]
file # type : TextIO
) : # type : ( . . . ) - > None
"""Output generated data to file as CSV with header .
: param data : An iterable of tuples containing raw data .
: param headers : Iterable o... | print ( ',' . join ( headers ) , file = file )
writer = csv . writer ( file )
writer . writerows ( data ) |
def clear ( self ) :
"""Clears all cells from a MOC .
> > > m = MOC ( 4 , ( 5 , 6 ) )
> > > m . clear ( )
> > > m . cells""" | for order in range ( 0 , MAX_ORDER + 1 ) :
self . _orders [ order ] . clear ( )
self . _normalized = True |
def find_checks ( argument_name ) :
"""Find all globally visible functions where the first argument name
starts with argument _ name .""" | checks = [ ]
function_type = type ( find_checks )
for name , function in globals ( ) . iteritems ( ) :
if type ( function ) is function_type :
args = inspect . getargspec ( function ) [ 0 ]
if len ( args ) >= 1 and args [ 0 ] . startswith ( argument_name ) :
checks . append ( ( name , fu... |
def find_link ( lid = None , sep_id = None , tep_id = None ) :
"""find link according to link ID .
: param lid : link id
: return : the link if found or None if not found""" | LOGGER . debug ( "LinkService.find_link" )
ret = None
if ( lid is None or not lid ) and ( sep_id is None or not sep_id ) and ( tep_id is None or not tep_id ) :
raise exceptions . ArianeCallParametersError ( 'id, source endpoint ID, target endpoint ID' )
if ( lid is not None and lid ) and ( ( sep_id is not None and ... |
def process_raw_data ( cls , raw_data ) :
"""Create a new model using raw API response .""" | properties = raw_data [ "properties" ]
ip_configurations = [ ]
raw_settings = properties . get ( "ipConfigurations" , [ ] )
for raw_configuration in raw_settings :
raw_configuration [ "parentResourceID" ] = raw_data [ "resourceId" ]
ip_configuration = IPConfiguration . from_raw_data ( raw_configuration )
ip... |
def get_service_marketplace ( self , available = True , unavailable = False , deprecated = False ) :
"""Returns a list of service names . Can return all services , just
those supported by PredixPy , or just those not yet supported by
PredixPy .
: param available : Return the services that are
available in P... | supported = set ( self . supported . keys ( ) )
all_services = set ( self . space . get_services ( ) )
results = set ( )
if available :
results . update ( supported )
if unavailable :
results . update ( all_services . difference ( supported ) )
if deprecated :
results . update ( supported . difference ( all... |
def hellinger_distance ( outputs , targets , derivative = False ) :
"""The output signals should be in the range [ 0 , 1]""" | root_difference = np . sqrt ( outputs ) - np . sqrt ( targets )
if derivative :
return root_difference / ( np . sqrt ( 2 ) * np . sqrt ( outputs ) )
else :
return np . mean ( np . sum ( np . power ( root_difference , 2 ) , axis = 1 ) / math . sqrt ( 2 ) ) |
def _accumulate ( lexitems ) :
"""Yield lists of tokens based on very simple parsing that checks the
level of nesting within a structure . This is probably much faster
than the LookaheadIterator method , but it is less safe ; an unclosed
list or AVM may cause it to build a list including the rest of the
fil... | data = [ ]
stack = [ ]
break_on = 10
in_def = False
for item in lexitems :
gid = item [ 0 ]
# only yield comments outside of definitions
if gid in ( 2 , 3 ) :
if len ( data ) == 0 :
yield [ item ]
else :
continue
elif gid == 20 :
assert len ( data ) == 0
... |
def predict ( self , data , param_list = None , return_long_probs = True , choice_col = None , num_draws = None , seed = None ) :
"""Parameters
data : string or pandas dataframe .
If string , data should be an absolute or relative path to a CSV
file containing the long format data for this choice model . Note... | # Get the dataframe of observations we ' ll be predicting on
dataframe = get_dataframe_from_data ( data )
# Determine the conditions under which we will add an intercept column
# to our long format dataframe .
add_intercept_to_dataframe ( self . specification , dataframe )
# Make sure the necessary columns are in the l... |
def wr_py_sections_new ( self , fout_py , doc = None ) :
"""Write the first sections file .""" | sections = self . grprobj . get_sections_2d ( )
return self . wr_py_sections ( fout_py , sections , doc ) |
def _set_system_mode ( self , v , load = False ) :
"""Setter method for system _ mode , mapped from YANG variable / rbridge _ id / system _ mode ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ system _ mode is considered as a private
method . Backends lo... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = system_mode . system_mode , is_container = 'container' , presence = False , yang_name = "system-mode" , rest_name = "system-mode" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , registe... |
def _colorbar_format ( minval , maxval ) :
"""Return the format string for the colorbar .""" | if not ( np . isfinite ( minval ) and np . isfinite ( maxval ) ) :
return str ( maxval )
else :
return '%.{}f' . format ( _digits ( minval , maxval ) ) |
def _committors ( sources , sinks , tprob ) :
"""Get the forward committors of the reaction sources - > sinks .
Parameters
sources : array _ like , int
The set of unfolded / reactant states .
sinks : array _ like , int
The set of folded / product states .
tprob : np . ndarray
Transition matrix
Retur... | n_states = np . shape ( tprob ) [ 0 ]
sources = np . array ( sources , dtype = int ) . reshape ( ( - 1 , 1 ) )
sinks = np . array ( sinks , dtype = int ) . reshape ( ( - 1 , 1 ) )
# construct the committor problem
lhs = np . eye ( n_states ) - tprob
for a in sources :
lhs [ a , : ] = 0.0
# np . zeros ( n )
... |
def update_cloud_integration ( self , id , ** kwargs ) : # noqa : E501
"""Update a specific cloud integration # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . update _ cloud _ inte... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . update_cloud_integration_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . update_cloud_integration_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def get_success_headers ( self , data ) :
"""As per the * Annotator * documentation regarding the
` create < http : / / docs . annotatorjs . org / en / v1.2 . x / storage . html # create > ` _
and
` update < http : / / docs . annotatorjs . org / en / v1.2 . x / storage . html # update > ` _
endpoints , we m... | headers = super ( AnnotationViewSet , self ) . get_success_headers ( data )
url = urlresolvers . reverse ( "annotations-detail" , kwargs = { "pk" : data [ "id" ] } )
headers . update ( { "Location" : self . request . build_absolute_uri ( url ) } )
return headers |
def point_distance_ellipsode ( point1 , point2 ) :
"""calculate the distance between two points on the ellipsode based on point1
Keyword arguments :
point1 - - point one geojson object
point2 - - point two geojson object
return distance""" | a = 6378137
f = 1 / 298.25722
b = a - a * f
e = math . sqrt ( ( a * a - b * b ) / ( a * a ) )
lon1 = point1 [ 'coordinates' ] [ 0 ]
lat1 = point1 [ 'coordinates' ] [ 1 ]
lon2 = point1 [ 'coordinates' ] [ 0 ]
lat2 = point2 [ 'coordinates' ] [ 1 ]
M = a * ( 1 - e * e ) * math . pow ( 1 - math . pow ( e * math . sin ( num... |
def adsr ( dur , a , d , s , r ) :
"""Linear ADSR envelope .
Parameters
dur :
Duration , in number of samples , including the release time .
" Attack " time , in number of samples .
" Decay " time , in number of samples .
" Sustain " amplitude level ( should be based on attack amplitude ) .
" Release ... | m_a = 1. / a
m_d = ( s - 1. ) / d
m_r = - s * 1. / r
len_a = int ( a + .5 )
len_d = int ( d + .5 )
len_r = int ( r + .5 )
len_s = int ( dur + .5 ) - len_a - len_d - len_r
for sample in xrange ( len_a ) :
yield sample * m_a
for sample in xrange ( len_d ) :
yield 1. + sample * m_d
for sample in xrange ( len_s ) :... |
def _offload ( self , args , ** extra_args ) :
"""Export is the entry point for exporting docker images .""" | if not isinstance ( args , argparse . Namespace ) :
raise Exception ( "args should of an instance of argparse.Namespace" )
# create new freight forwarder object
freight_forwarder = FreightForwarder ( )
# create commercial invoice this is the contact given to freight forwarder dispatch containers and images
commerci... |
def input_dir ( self , dirname ) :
"""Check all files in this directory and all subdirectories .""" | dirname = dirname . rstrip ( '/' )
if self . excluded ( dirname ) :
return 0
counters = self . options . report . counters
verbose = self . options . verbose
filepatterns = self . options . filename
runner = self . runner
for root , dirs , files in os . walk ( dirname ) :
if verbose :
print ( 'directory... |
def convert_to_influx ( mac , payload ) :
'''Convert data into RuuviCollector naming schme and scale
returns :
Object to be written to InfluxDB''' | dataFormat = payload [ "data_format" ] if ( 'data_format' in payload ) else None
fields = { }
fields [ "temperature" ] = payload [ "temperature" ] if ( 'temperature' in payload ) else None
fields [ "humidity" ] = payload [ "humidity" ] if ( 'humidity' in payload ) else None
fields [ "pressure" ] = payload [ "pressure" ... |
def duplicate ( self , contributor = None ) :
"""Duplicate ( make a copy ) .""" | duplicate = Collection . objects . get ( id = self . id )
duplicate . pk = None
duplicate . slug = None
duplicate . name = 'Copy of {}' . format ( self . name )
duplicate . duplicated = now ( )
if contributor :
duplicate . contributor = contributor
duplicate . save ( force_insert = True )
assign_contributor_permiss... |
def rel_path_to ( self , dest ) :
"""Builds a relative path leading from this one to another .
Note that these paths might be both relative , in which case they ' ll be
assumed to be considered starting from the same directory .
Contrary to : class : ` ~ rpaths . AbstractPath ` ' s version , this will also
... | return super ( Path , self . absolute ( ) ) . rel_path_to ( Path ( dest ) . absolute ( ) ) |
def login ( self ) :
"""Logs into the Splunk instance referred to by the : class : ` Context `
object .
Unless a ` ` Context ` ` is created with an explicit authentication token
( probably obtained by logging in from a different ` ` Context ` ` object )
you must call : meth : ` login ` before you can issue ... | if self . has_cookies ( ) and ( not self . username and not self . password ) : # If we were passed session cookie ( s ) , but no username or
# password , then login is a nop , since we ' re automatically
# logged in .
return
if self . token is not _NoAuthenticationToken and ( not self . username and not self . pas... |
def create_dcnm_out_part ( self , tenant_id , fw_dict , is_fw_virt = False ) :
"""Create the DCNM OUT partition and update the result .""" | res = fw_const . DCNM_OUT_PART_CREATE_SUCCESS
tenant_name = fw_dict . get ( 'tenant_name' )
ret = True
try :
self . _create_out_partition ( tenant_id , tenant_name )
except Exception as exc :
LOG . error ( "Create of Out Partition failed for tenant " "%(tenant)s ,Exception %(exc)s" , { 'tenant' : tenant_id , 'e... |
def merge ( cls , components ) :
"""Merges components into a single component , applying their actions appropriately .
This operation is associative : M ( M ( a , b ) , c ) = = M ( a , M ( b , c ) ) = = M ( a , b , c ) .
: param list components : an iterable of instances of ListValueComponent .
: return : An ... | # Note that action of the merged component is MODIFY until the first REPLACE is encountered .
# This guarantees associativity .
action = cls . MODIFY
appends = [ ]
filters = [ ]
for component in components :
if component . _action is cls . REPLACE :
appends = component . _appends
filters = component... |
def _load_polygon ( tokens , string ) :
"""Has similar inputs and return value to to : func : ` _ load _ point ` , except is
for handling POLYGON geometry .
: returns :
A GeoJSON ` dict ` Polygon representation of the WKT ` ` string ` ` .""" | open_parens = next ( tokens ) , next ( tokens )
if not open_parens == ( '(' , '(' ) :
raise ValueError ( INVALID_WKT_FMT % string )
# coords contains a list of rings
# each ring contains a list of points
# each point is a list of 2-4 values
coords = [ ]
ring = [ ]
on_ring = True
try :
pt = [ ]
for t in toke... |
def retrieve ( self , identifier , * criterion ) :
"""Retrieve a model by primary key and zero or more other criteria .
: raises ` NotFound ` if there is no existing model""" | return self . _retrieve ( self . model_class . id == identifier , * criterion ) |
def get ( self , document = None , plugin = None ) :
"""Get one or more documents .
: param document : Name of the document
: type document : str
: param plugin : Plugin object , under which the document was registered
: type plugin : GwBasePattern""" | if plugin is not None :
if document is None :
documents_list = { }
for key in self . documents . keys ( ) :
if self . documents [ key ] . plugin == plugin :
documents_list [ key ] = self . documents [ key ]
return documents_list
else :
if document in s... |
def request_sign_out ( self , user ) :
"""Send a single logout request to each service accessed by a
specified user . This is called at logout when single logout
is enabled .
If requests - futures is installed , asynchronous requests will
be sent . Otherwise , synchronous requests will be sent .""" | session = Session ( )
for ticket in self . filter ( user = user , consumed__gte = user . last_login ) :
ticket . request_sign_out ( session = session ) |
def get_url ( request ) :
"""Since we might be hosted behind a proxy , we need to check the
X - Forwarded - Proto , X - Forwarded - Protocol , or X - Forwarded - SSL headers
to find out what protocol was used to access us .""" | protocol = request . headers . get ( 'X-Forwarded-Proto' ) or request . headers . get ( 'X-Forwarded-Protocol' )
if protocol is None and request . headers . get ( 'X-Forwarded-Ssl' ) == 'on' :
protocol = 'https'
if protocol is None :
return request . url
url = list ( urlparse ( request . url ) )
url [ 0 ] = pro... |
def write_edges ( self ) :
"""Write all edges we can find in the graph in a brute - force manner .""" | for node in self . nodes . values ( ) :
if node [ "parent_url" ] in self . nodes :
self . write_edge ( node )
self . flush ( ) |
def arithmetic_mnemonic ( self , op_name , op_type ) :
"""Generates an arithmetic instruction mnemonic""" | return self . OPERATIONS [ op_name ] + self . OPSIGNS [ op_type ] |
def status_for_all_orders_in_a_stock ( self , stock ) :
"""Status for all orders in a stock
https : / / starfighter . readme . io / docs / status - for - all - orders - in - a - stock""" | url_fragment = 'venues/{venue}/accounts/{account}/stocks/{stock}/orders' . format ( stock = stock , venue = self . venue , account = self . account , )
url = urljoin ( self . base_url , url_fragment )
return self . session . get ( url ) . json ( ) |
def _get_user_groups ( self , user ) :
'''Get user groups .
: param user :
: return :''' | return [ g . gr_name for g in grp . getgrall ( ) if user in g . gr_mem ] + [ grp . getgrgid ( pwd . getpwnam ( user ) . pw_gid ) . gr_name ] |
def __set_premature_stop_codon_status ( self , hgvs_string ) :
"""Set whether there is a premature stop codon .""" | if re . search ( '.+\*(\d+)?$' , hgvs_string ) :
self . is_premature_stop_codon = True
self . is_non_silent = True
# check if it is also a nonsense mutation
if hgvs_string . endswith ( '*' ) :
self . is_nonsense_mutation = True
else :
self . is_nonsense_mutation = False
else :
se... |
def _calc_overlap_coef ( markers1 : dict , markers2 : dict , ) :
"""Calculate overlap coefficient between the values of two dictionaries
Note : dict values must be sets""" | overlap_coef = np . zeros ( ( len ( markers1 ) , len ( markers2 ) ) )
j = 0
for marker_group in markers1 :
tmp = [ len ( markers2 [ i ] . intersection ( markers1 [ marker_group ] ) ) / max ( min ( len ( markers2 [ i ] ) , len ( markers1 [ marker_group ] ) ) , 1 ) for i in markers2 . keys ( ) ]
overlap_coef [ j ... |
def add_simmanager_api ( self , mock ) :
'''Add org . ofono . SimManager API to a mock''' | iface = 'org.ofono.SimManager'
mock . AddProperties ( iface , { 'BarredDialing' : _parameters . get ( 'BarredDialing' , False ) , 'CardIdentifier' : _parameters . get ( 'CardIdentifier' , new_iccid ( self ) ) , 'FixedDialing' : _parameters . get ( 'FixedDialing' , False ) , 'LockedPins' : _parameters . get ( 'LockedPin... |
def _explode_shorthand_ip_string ( self ) :
"""Expand a shortened IPv6 address .
Args :
ip _ str : A string , the IPv6 address .
Returns :
A string , the expanded IPv6 address .""" | if isinstance ( self , IPv6Network ) :
ip_str = str ( self . network_address )
elif isinstance ( self , IPv6Interface ) :
ip_str = str ( self . ip )
else :
ip_str = str ( self )
ip_int = self . _ip_int_from_string ( ip_str )
hex_str = '%032x' % ip_int
parts = [ hex_str [ x : x + 4 ] for x in range ( 0 , 32 ... |
def parse ( text : str , style : Style = Style . auto ) -> Docstring :
"""Parse the docstring into its components .
: param text : docstring text to parse
: param style : docstring style
: returns : parsed docstring representation""" | if style != Style . auto :
return _styles [ style ] ( text )
rets = [ ]
for parse_ in _styles . values ( ) :
try :
rets . append ( parse_ ( text ) )
except ParseError as e :
exc = e
if not rets :
raise exc
return sorted ( rets , key = lambda d : len ( d . meta ) , reverse = True ) [ 0 ] |
def find_route_functions_taint_args ( self ) :
"""Find all route functions and taint all of their arguments .
Yields :
CFG of each route function , with args marked as tainted .""" | for definition in _get_func_nodes ( ) :
if self . is_route_function ( definition . node ) :
yield self . get_func_cfg_with_tainted_args ( definition ) |
def add_behaviour ( self , behaviour , template = None ) :
"""Adds and starts a behaviour to the agent .
If template is not None it is used to match
new messages and deliver them to the behaviour .
Args :
behaviour ( spade . behaviour . CyclicBehaviour ) : the behaviour to be started
template ( spade . te... | behaviour . set_agent ( self )
if issubclass ( type ( behaviour ) , FSMBehaviour ) :
for _ , state in behaviour . get_states ( ) . items ( ) :
state . set_agent ( self )
behaviour . set_template ( template )
self . behaviours . append ( behaviour )
if self . is_alive ( ) :
behaviour . start ( ) |
def set_tenant ( self , tenant , include_public = True ) :
"""Main API method to current database schema ,
but it does not actually modify the db connection .""" | self . tenant = tenant
self . schema_name = tenant . schema_name
self . include_public_schema = include_public
self . set_settings_schema ( self . schema_name )
self . search_path_set = False |
def fake_KATCP_client_resource_factory ( KATCPClientResourceClass , fake_options , resource_spec , * args , ** kwargs ) :
"""Create a fake KATCPClientResource - like class and a fake - manager
Parameters
KATCPClientResourceClass : class
Subclass of : class : ` katcp . resource _ client . KATCPClientResource `... | # TODO Implement allow _ any _ request functionality . When True , any unknown request ( even
# if there is no fake implementation ) should succeed
allow_any_request = fake_options . get ( 'allow_any_request' , False )
class FakeKATCPClientResource ( KATCPClientResourceClass ) :
def inspecting_client_factory ( self... |
def expand ( self , id ) :
"""Expand a concept or collection to all it ' s narrower concepts .
If the id passed belongs to a : class : ` skosprovider . skos . Concept ` ,
the id of the concept itself should be include in the return value .
: param str id : A concept or collection id .
: returns : A : class ... | query = """SELECT DISTINCT ?Id{
{
?Subject dc:identifier ?Id; skos:inScheme %s:; gvp:broaderExtended %s;.
}
UNION
{
VALUES ?Id {'%s'}
?Subject dc:identifier ?Id; skos:inScheme %s:; rdf:type skos:Concept.
... |
def timeseries ( self ) :
"""Load time series
It returns the actual time series used in power flow analysis . If
: attr : ` _ timeseries ` is not : obj : ` None ` , it is returned . Otherwise ,
: meth : ` timeseries ( ) ` looks for time series of the according sector in
: class : ` ~ . grid . network . Time... | if self . _timeseries is None :
if isinstance ( self . grid , MVGrid ) :
voltage_level = 'mv'
elif isinstance ( self . grid , LVGrid ) :
voltage_level = 'lv'
ts_total = None
for sector in self . consumption . keys ( ) :
consumption = self . consumption [ sector ]
# check ... |
def create_settings ( from_environment = False , locustfile = None , classes = None , host = None , num_clients = None , hatch_rate = None , reset_stats = False , run_time = "3m" ) :
'''Returns a settings object to be used by a LocalLocustRunner .
Arguments
from _ environment : get settings from environment var... | settings = type ( '' , ( ) , { } ) ( )
settings . from_environment = from_environment
settings . locustfile = locustfile
settings . classes = classes
settings . host = host
settings . num_clients = num_clients
settings . hatch_rate = hatch_rate
settings . reset_stats = reset_stats
settings . run_time = run_time
# Defau... |
def get_departures ( self , station ) :
"""Fetch the current departure times from this station
http : / / webservices . ns . nl / ns - api - avt ? station = $ { Naam of afkorting Station }
@ param station : station to lookup""" | url = 'http://webservices.ns.nl/ns-api-avt?station=' + station
raw_departures = self . _request ( 'GET' , url )
return self . parse_departures ( raw_departures ) |
def format_decimal ( decimal ) :
"""Formats a decimal number
: param decimal : the decimal value
: return : the formatted string value""" | # strip trailing fractional zeros
normalized = decimal . normalize ( )
sign , digits , exponent = normalized . as_tuple ( )
if exponent >= 1 :
normalized = normalized . quantize ( 1 )
return str ( normalized ) |
def delete_files ( self , ids ) :
"""Remove one or more files""" | self . check_owner ( )
if not isinstance ( ids , list ) :
raise TypeError ( "You must specify list of files to delete!" )
self . conn . make_call ( "deleteFiles" , ids ) |
def register_plugin ( self ) :
"""Register plugin in Spyder ' s main window""" | self . focus_changed . connect ( self . main . plugin_focus_changed )
self . main . add_dockwidget ( self )
# self . main . console . set _ historylog ( self )
self . main . console . shell . refresh . connect ( self . refresh_plugin ) |
def _parse_regr_response ( self , response , uri = None , new_authzr_uri = None , terms_of_service = None ) :
"""Parse a registration response from the server .""" | links = _parse_header_links ( response )
if u'terms-of-service' in links :
terms_of_service = links [ u'terms-of-service' ] [ u'url' ]
if u'next' in links :
new_authzr_uri = links [ u'next' ] [ u'url' ]
if new_authzr_uri is None :
raise errors . ClientError ( '"next" link missing' )
return ( response . json... |
def normalize_choices ( db_values , field_name , app = DEFAULT_APP , model_name = '' , human_readable = True , none_value = 'Null' , blank_value = 'Unknown' , missing_value = 'Unknown DB Code' ) :
'''Output the human - readable strings associated with the list of database values for a model field .
Uses the trans... | if app and isinstance ( app , basestring ) :
app = get_app ( app )
if not db_values :
return
try :
db_values = dict ( db_values )
except :
raise NotImplemented ( "This function can only handle objects that can be converted to a dict, not lists or querysets returned by django `.values().aggregate()`." )
... |
def pygame_image_loader ( filename , colorkey , ** kwargs ) :
"""pytmx image loader for pygame
: param filename :
: param colorkey :
: param kwargs :
: return :""" | if colorkey :
colorkey = pygame . Color ( '#{0}' . format ( colorkey ) )
pixelalpha = kwargs . get ( 'pixelalpha' , True )
image = pygame . image . load ( filename )
def load_image ( rect = None , flags = None ) :
if rect :
try :
tile = image . subsurface ( rect )
except ValueError :... |
def extract_fasta ( partition_file , fasta_file , output_dir , chunk_size = DEFAULT_CHUNK_SIZE , max_cores = DEFAULT_MAX_CORES , ) :
"""Extract sequences from bins
Identify bins , extract chunks belonging to each bins and gather them
in a single FASTA file .
Parameters
partition _ file : file , str or pathl... | genome = { record . id : record . seq for record in SeqIO . parse ( fasta_file , "fasta" ) }
data_chunks = list ( zip ( * np . genfromtxt ( partition_file , usecols = ( 0 , 1 ) , dtype = None ) ) )
chunk_names = np . array ( data_chunks [ 0 ] , dtype = object )
cores = np . array ( data_chunks [ 1 ] )
for core in set (... |
def parameters_changed ( self ) :
"""Notice that we update the warping function gradients here .""" | self . Y_normalized [ : ] = self . transform_data ( )
super ( WarpedGP , self ) . parameters_changed ( )
Kiy = self . posterior . woodbury_vector . flatten ( )
self . warping_function . update_grads ( self . Y_untransformed , Kiy ) |
def attach ( self , data , file_name = None , comment = None , compression = True , mime = r"application/octet-stream" , embedded = True , ) :
"""attach embedded attachment as application / octet - stream
Parameters
data : bytes
data to be attached
file _ name : str
string file name
comment : str
atta... | if data in self . _attachments_cache :
return self . _attachments_cache [ data ]
else :
creator_index = len ( self . file_history )
fh = FileHistory ( )
fh . comment = """<FHcomment>
<TX>Added new embedded attachment from {}</TX>
<tool_id>asammdf</tool_id>
<tool_vendor>asammdf</tool_vendor>
<tool_versio... |
def get_state_actions ( self , state , ** kwargs ) :
"""Sends kill signals to running containers .
: param state : Configuration state .
: type state : dockermap . map . state . ConfigState
: param kwargs : Additional keyword arguments .
: return : Actions on the client , map , and configurations .
: rtyp... | if state . config_id . config_type == ItemType . CONTAINER and state . base_state == State . RUNNING :
return [ ItemAction ( state , Action . KILL , extra_data = kwargs ) ] |
def consulta_faixa ( self , localidade , uf ) :
"""Consulta site e retorna faixa para localidade""" | url = 'consultaFaixaCepAction.do'
data = { 'UF' : uf , 'Localidade' : localidade . encode ( 'cp1252' ) , 'cfm' : '1' , 'Metodo' : 'listaFaixaCEP' , 'TipoConsulta' : 'faixaCep' , 'StartRow' : '1' , 'EndRow' : '10' , }
html = self . _url_open ( url , data ) . read ( )
return self . _parse_faixa ( html ) |
def _getTextType ( self , lineData , column ) :
"""Get text type ( letter )""" | if lineData is None :
return ' '
# default is code
textTypeMap = lineData [ 1 ]
if column >= len ( textTypeMap ) : # probably , not actual data , not updated yet
return ' '
return textTypeMap [ column ] |
def do_gdbserver ( self ) :
"""! @ brief Handle ' gdbserver ' subcommand .""" | self . _process_commands ( self . _args . commands )
gdbs = [ ]
try : # Build dict of session options .
sessionOptions = convert_session_options ( self . _args . options )
sessionOptions . update ( { 'gdbserver_port' : self . _args . port_number , 'telnet_port' : self . _args . telnet_port , 'persist' : self . ... |
def assign ( self , objects , nurest_object_type , async = False , callback = None , commit = True ) :
"""Reference a list of objects into the current resource
Args :
objects ( list ) : list of NURESTObject to link
nurest _ object _ type ( type ) : Type of the object to link
callback ( function ) : Callback... | ids = list ( )
for nurest_object in objects :
ids . append ( nurest_object . id )
url = self . get_resource_url_for_child_type ( nurest_object_type )
request = NURESTRequest ( method = HTTP_METHOD_PUT , url = url , data = ids )
user_info = { 'nurest_objects' : objects , 'commit' : commit }
if async :
return sel... |
def _update_id ( record , new_id ) :
"""Update a record id to new _ id , also modifying the ID in record . description""" | old_id = record . id
record . id = new_id
# At least for FASTA , record ID starts the description
record . description = re . sub ( '^' + re . escape ( old_id ) , new_id , record . description )
return record |
def send_request ( self , request ) :
"""Handles the Blocks option in a outgoing request .
: type request : Request
: param request : the outgoing request
: return : the edited request""" | assert isinstance ( request , Request )
if request . block1 or ( request . payload is not None and len ( request . payload ) > defines . MAX_PAYLOAD ) :
host , port = request . destination
key_token = hash ( str ( host ) + str ( port ) + str ( request . token ) )
if request . block1 :
num , m , size... |
def __set_authoring_nodes ( self , source , target ) :
"""Sets given editor authoring nodes .
: param source : Source file .
: type source : unicode
: param target : Target file .
: type target : unicode""" | editor = self . __script_editor . get_editor ( source )
editor . set_file ( target )
self . __script_editor . model . update_authoring_nodes ( editor ) |
def explain_weights_lightgbm ( lgb , vec = None , top = 20 , target_names = None , # ignored
targets = None , # ignored
feature_names = None , feature_re = None , feature_filter = None , importance_type = 'gain' , ) :
"""Return an explanation of an LightGBM estimator ( via scikit - learn wrapper
LGBMClassifier or... | coef = _get_lgb_feature_importances ( lgb , importance_type )
lgb_feature_names = lgb . booster_ . feature_name ( )
return get_feature_importance_explanation ( lgb , vec , coef , feature_names = feature_names , estimator_feature_names = lgb_feature_names , feature_filter = feature_filter , feature_re = feature_re , top... |
async def send_packed_command ( self , command ) :
"Send an already packed command to the Redis server" | if not self . _writer :
await self . connect ( )
try :
if isinstance ( command , str ) :
command = [ command ]
self . _writer . writelines ( command )
except asyncio . futures . TimeoutError :
self . disconnect ( )
raise TimeoutError ( "Timeout writing to socket" )
except Exception :
e =... |
def _result_handler ( self , response : Dict [ str , Any ] ) :
"""应答结果响应处理 .
将结果解析出来设置给任务对应的Future对象上
Parameters :
( response ) : - 响应的python字典形式数据
Return :
( bool ) : - 准确地说没有错误就会返回True""" | res = response . get ( "MESSAGE" )
ID = res . get ( "ID" )
result = res . get ( "RESULT" )
fut = self . tasks . get ( ID )
fut . set_result ( result )
return True |
def get_region ( cls , resource = None ) :
"""Retrieve region from standard environmental variables
or file name .
More information of the following link : http : / / goo . gl / Vb9Jky""" | if resource :
resource_info = cls . parse_remote ( resource )
if resource_info . region :
return resource_info . region
return os . environ . get ( "AWS_DEFAULT_REGION" , cls . _DEFAULT_REGION ) |
def custom_resolve ( self ) :
"""If a custom resolver is defined , perform custom resolution on
the contained addresses .
: return :""" | if not callable ( self . custom_resolver ) :
return
new_addresses = [ ]
for address in self . addresses :
for new_address in self . custom_resolver ( address ) :
new_addresses . append ( new_address )
self . addresses = new_addresses |
def write ( self , fd ) :
"""write out to file descriptor .""" | print >> fd , self . classHead
for t in self . items :
print >> fd , t
print >> fd , self . classFoot |
def update_selected_cb ( parents , combobox ) :
"""Update the combobox with the selected item based on the parents .
Parameters
parents : list of : class : ` FoldScopeHelper `
combobox : : class : ` qtpy . QtWidets . QComboBox `
The combobox to populate
Returns
None""" | if parents is not None and len ( parents ) == 0 :
combobox . setCurrentIndex ( 0 )
else :
item = parents [ - 1 ]
for i in range ( combobox . count ( ) ) :
if combobox . itemData ( i ) == item :
combobox . setCurrentIndex ( i )
break |
def get_ratetimestamp ( self , base , code ) :
"""Return rate timestamp as a datetime / date or None""" | try :
ts = int ( self . get_rate ( code ) [ 'ts' ] )
except RuntimeError :
return None
return datetime . fromtimestamp ( ts ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.