signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def read_and_translate ( translator : inference . Translator , output_handler : OutputHandler , chunk_size : Optional [ int ] , input_file : Optional [ str ] = None , input_factors : Optional [ List [ str ] ] = None , input_is_json : bool = False ) -> None :
"""Reads from either a file or stdin and translates each ... | batch_size = translator . max_batch_size
if chunk_size is None :
if translator . max_batch_size == 1 : # No batching , therefore there is not need to read segments in chunks .
chunk_size = C . CHUNK_SIZE_NO_BATCHING
else : # Get a constant number of batches per call to Translator . translate .
c... |
async def finish_authentication ( self , username , password ) :
"""Finish authentication process .
A username ( generated by new _ credentials ) and the PIN code shown on
screen must be provided .""" | # Step 1
self . srp . step1 ( username , password )
data = await self . _send_plist ( 'step1' , method = 'pin' , user = username )
resp = plistlib . loads ( data )
# Step 2
pub_key , key_proof = self . srp . step2 ( resp [ 'pk' ] , resp [ 'salt' ] )
await self . _send_plist ( 'step2' , pk = binascii . unhexlify ( pub_k... |
def valid_color ( x : str ) -> bool :
"""Return ` ` True ` ` if ` ` x ` ` a valid hexadecimal color string without
the leading hash ; otherwise return ` ` False ` ` .""" | if isinstance ( x , str ) and re . match ( COLOR_PATTERN , x ) :
return True
else :
return False |
def OnCellTextRotation ( self , event ) :
"""Cell text rotation event handler""" | with undo . group ( _ ( "Rotation" ) ) :
self . grid . actions . toggle_attr ( "angle" )
self . grid . ForceRefresh ( )
self . grid . update_attribute_toolbar ( )
if is_gtk ( ) :
try :
wx . Yield ( )
except :
pass
event . Skip ( ) |
def create ( self , interface ) :
"""Method to add an interface .
: param interface : List containing interface ' s desired to be created on database .
: return : Id .""" | data = { 'interfaces' : interface }
return super ( ApiInterfaceRequest , self ) . post ( 'api/v3/interface/' , data ) |
def get_sites ( self ) :
"""Parse the site - text string and return a list of sites .
Returns
sites : list [ Site ]
A list of position - residue pairs corresponding to the site - text""" | st = self . site_text
suffixes = [ ' residue' , ' residues' , ',' , '/' ]
for suffix in suffixes :
if st . endswith ( suffix ) :
st = st [ : - len ( suffix ) ]
assert ( not st . endswith ( ',' ) )
# Strip parentheses
st = st . replace ( '(' , '' )
st = st . replace ( ')' , '' )
st = st . replace ( ' or ' , ... |
def filebrowser_remove_file ( request , item_id , file_type ) :
"""Remove file""" | fobj = get_object_or_404 ( FileBrowserFile , file_type = file_type , id = item_id )
fobj . delete ( )
if file_type == 'doc' :
return HttpResponseRedirect ( reverse ( 'mce-filebrowser-documents' ) )
return HttpResponseRedirect ( reverse ( 'mce-filebrowser-images' ) ) |
def combine_dicts ( dictA , dictB ) :
"""Combines two dictionaries into one .
Example usage :
> > > combine _ dicts ( { ' R ' : ' Red ' , ' B ' : ' Black ' , ' P ' : ' Pink ' } , { ' G ' : ' Green ' , ' W ' : ' White ' } )
{ ' B ' : ' Black ' , ' R ' : ' Red ' , ' P ' : ' Pink ' , ' G ' : ' Green ' , ' W ' : ... | import collections as cl
combined_dict = dict ( cl . ChainMap ( { } , dictA , dictB ) )
return combined_dict |
def write_sparse_matrix_hdf5 ( filename , mtx , name = 'a sparse matrix' ) :
"""Assume CSR / CSC .""" | fd = pt . openFile ( filename , mode = 'w' , title = name )
try :
info = fd . createGroup ( '/' , 'info' )
fd . createArray ( info , 'dtype' , mtx . dtype . str )
fd . createArray ( info , 'shape' , mtx . shape )
fd . createArray ( info , 'format' , mtx . format )
data = fd . createGroup ( '/' , 'da... |
def flags ( self , index ) :
"""Return the flags for the given index
This will call : meth : ` TreeItem . flags ` for valid ones .
: param index : the index to query
: type index : : class : ` QtCore . QModelIndex `
: returns : None
: rtype : None
: raises : None""" | if index . isValid ( ) :
item = index . internalPointer ( )
return item . flags ( index )
else :
super ( TreeModel , self ) . flags ( index ) |
def minimumLabelWidth ( self ) :
"""Returns the minimum label width required on this renderers font size .
: param labels | [ < str > , . . ]""" | min_w = 0
metrics = QFontMetrics ( self . labelFont ( ) )
for label in self . labels ( ) :
min_w = max ( min_w , metrics . width ( label ) )
return max ( self . _minimumLabelWidth , min_w + self . horizontalLabelPadding ( ) ) |
def _merge_defaults ( self , data , method_params , defaults ) :
"""Helper method for adding default values to the data dictionary .
The ` defaults ` are the default values inspected from the method that
will be called . For any values that are not present in the incoming
data , the default value is added .""... | if defaults :
optional_args = method_params [ - len ( defaults ) : ]
for key , value in zip ( optional_args , defaults ) :
if not key in data :
data [ key ] = value
return data |
def reduce_filename ( f ) :
r'''Expects something like / tmp / tmpAjry4Gdsbench / test . weights . e5 . XXX . YYY . pb
Where XXX is a variation on the model size for example
And where YYY is a const related to the training dataset''' | f = os . path . basename ( f ) . split ( '.' )
return keep_only_digits ( f [ - 3 ] ) |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'session_id' ) and self . session_id is not None :
_dict [ 'session_id' ] = self . session_id
return _dict |
def _expose_only_preferred_locations ( match_query , location_types , coerced_locations , preferred_locations , eligible_locations ) :
"""Return a MATCH query where only preferred locations are valid as query start locations .""" | preferred_location_types = dict ( )
eligible_location_types = dict ( )
new_match_traversals = [ ]
for current_traversal in match_query . match_traversals :
new_traversal = [ ]
for match_step in current_traversal :
new_step = match_step
current_step_location = match_step . as_block . location
... |
def AjustarLiquidacionContrato ( self ) :
"Ajustar Liquidación activas relacionadas a un contrato" | # limpiar arrays no enviados :
if not self . ajuste [ 'ajusteBase' ] [ 'certificados' ] :
del self . ajuste [ 'ajusteBase' ] [ 'certificados' ]
for k1 in ( 'ajusteCredito' , 'ajusteDebito' ) :
for k2 in ( 'retenciones' , 'deducciones' ) :
if not self . ajuste [ k1 ] [ k2 ] :
del self . ajust... |
def _handle_sync_devices ( self , routers ) :
"""Handles routers during a device _ sync .
This method performs post - processing on routers fetched from the
routing plugin during a device sync . Routers are first fetched
from the plugin based on the list of device _ ids . Since fetched
routers take preceden... | sync_devices_list = list ( self . sync_devices )
LOG . debug ( "Fetching routers on:%s" , sync_devices_list )
fetched_routers = self . _fetch_router_info ( device_ids = sync_devices_list )
if fetched_routers :
LOG . debug ( "[sync_devices] Fetched routers :%s" , pp . pformat ( fetched_routers ) )
# clear router... |
def bind_protocol ( self , proto ) :
"""Tries to bind given protocol to this peer .
Should only be called by ` proto ` trying to bind .
Once bound this protocol instance will be used to communicate with
peer . If another protocol is already bound , connection collision
resolution takes place .""" | LOG . debug ( 'Trying to bind protocol %s to peer %s' , proto , self )
# Validate input .
if not isinstance ( proto , BgpProtocol ) :
raise ValueError ( 'Currently only supports valid instances of' ' `BgpProtocol`' )
if proto . state != const . BGP_FSM_OPEN_CONFIRM :
raise ValueError ( 'Only protocols in OpenCo... |
def i4_uniform ( a , b , seed ) :
"""i4 _ uniform returns a scaled pseudorandom I4.
Discussion :
The pseudorandom number will be scaled to be uniformly distributed
between A and B .
Reference :
Paul Bratley , Bennett Fox , Linus Schrage ,
A Guide to Simulation ,
Springer Verlag , pages 201-202 , 1983.... | if seed == 0 :
print ( 'I4_UNIFORM - Fatal error!' )
print ( ' Input SEED = 0!' )
seed = np . floor ( seed )
a = round ( a )
b = round ( b )
seed = np . mod ( seed , 2147483647 )
if seed < 0 :
seed += 2147483647
k = seed // 127773
seed = 16807 * ( seed - k * 127773 ) - k * 2836
if seed < 0 :
seed += 21... |
def resample ( self , sampling_rate , inplace = False , kind = 'linear' ) :
'''Resample the Variable to the specified sampling rate .
Parameters
sampling _ rate : : obj : ` int ` , : obj : ` float `
Target sampling rate ( in Hz ) .
inplace : : obj : ` bool ` , optional
If True , performs resampling in - p... | if not inplace :
var = self . clone ( )
var . resample ( sampling_rate , True , kind )
return var
if sampling_rate == self . sampling_rate :
return
old_sr = self . sampling_rate
n = len ( self . index )
self . index = self . _build_entity_index ( self . run_info , sampling_rate )
x = np . arange ( n )
n... |
def get_bin ( self , arch = 'x86' ) :
"""Get binaries of Visual C + + .""" | bin_dir = os . path . join ( self . vc_dir , 'bin' )
if arch == 'x86' :
arch = ''
cl_path = os . path . join ( bin_dir , arch , 'cl.exe' )
link_path = os . path . join ( bin_dir , arch , 'link.exe' )
ml_name = 'ml.exe'
if arch in [ 'x86_amd64' , 'amd64' ] :
ml_name = 'ml64.exe'
ml_path = os . path . join ( bin_... |
def _wait_for_process ( self , p , shell = False ) :
"""Debug function used in unit tests .
: param p : A subprocess . Popen process .
: param bool shell : If command requires should be run in its own shell . Optional . Default : False .""" | local_maxmem = - 1
sleeptime = .5
while p . poll ( ) is None :
if not shell :
local_maxmem = max ( local_maxmem , self . _memory_usage ( p . pid ) / 1e6 )
# print ( " int . maxmem ( pid : " + str ( p . pid ) + " ) " + str ( local _ maxmem ) )
time . sleep ( sleeptime )
sleeptime = min ( slee... |
def get_min_row_num ( mention ) :
"""Return the lowest row number that a Mention occupies .
: param mention : The Mention to evaluate . If a candidate is given , default
to its first Mention .
: rtype : integer or None""" | span = _to_span ( mention )
if span . sentence . is_tabular ( ) :
return span . sentence . cell . row_start
else :
return None |
def option ( self , key = None ) :
"""Get the value of a command option .""" | if key is None :
return self . _args . options ( )
return self . _args . option ( key ) |
def composite ( background_image , foreground_image , foreground_width_ratio = 0.25 , foreground_position = ( 0.0 , 0.0 ) , ) :
"""Takes two images and composites them .""" | if foreground_width_ratio <= 0 :
return background_image
composite = background_image . copy ( )
width = int ( foreground_width_ratio * background_image . shape [ 1 ] )
foreground_resized = resize ( foreground_image , width )
size = foreground_resized . shape
x = int ( foreground_position [ 1 ] * ( background_image... |
def _determine_checkout_url ( self , platform , action ) :
"""This returns the Adyen API endpoint based on the provided platform ,
service and action .
Args :
platform ( str ) : Adyen platform , ie ' live ' or ' test ' .
action ( str ) : the API action to perform .""" | api_version = settings . API_CHECKOUT_VERSION
if platform == "test" :
base_uri = settings . ENDPOINT_CHECKOUT_TEST
elif self . live_endpoint_prefix is not None and platform == "live" :
base_uri = settings . ENDPOINT_CHECKOUT_LIVE_SUFFIX . format ( self . live_endpoint_prefix )
elif self . live_endpoint_prefix i... |
def _download_chunk ( self , chunk_offset , chunk_size ) :
"""Reads or downloads the received blob from the system .""" | range_id = 'bytes={0}-{1}' . format ( chunk_offset , chunk_offset + chunk_size - 1 )
return self . _blob_service . get_blob ( container_name = self . _container_name , blob_name = self . _blob_name , x_ms_range = range_id ) |
def get_context_data ( self , ** kwargs ) :
"""Returns the template context , including the workflow class .
This method should be overridden in subclasses to provide additional
context data to the template .""" | context = super ( WorkflowView , self ) . get_context_data ( ** kwargs )
workflow = self . get_workflow ( )
workflow . verify_integrity ( )
context [ self . context_object_name ] = workflow
next = self . request . GET . get ( workflow . redirect_param_name )
context [ 'REDIRECT_URL' ] = next
context [ 'layout' ] = self... |
def refit ( self , data , label , decay_rate = 0.9 , ** kwargs ) :
"""Refit the existing Booster by new data .
Parameters
data : string , numpy array , pandas DataFrame , H2O DataTable ' s Frame or scipy . sparse
Data source for refit .
If string , it represents the path to txt file .
label : list , numpy... | if self . __set_objective_to_none :
raise LightGBMError ( 'Cannot refit due to null objective function.' )
predictor = self . _to_predictor ( copy . deepcopy ( kwargs ) )
leaf_preds = predictor . predict ( data , - 1 , pred_leaf = True )
nrow , ncol = leaf_preds . shape
train_set = Dataset ( data , label , silent =... |
def _normalize_tags_type ( self , tags , device_name = None , metric_name = None ) :
"""Normalize tags contents and type :
- append ` device _ name ` as ` device : ` tag
- normalize tags type
- doesn ' t mutate the passed list , returns a new list""" | normalized_tags = [ ]
if device_name :
self . _log_deprecation ( "device_name" )
device_tag = self . _to_bytes ( "device:{}" . format ( device_name ) )
if device_tag is None :
self . log . warning ( 'Error encoding device name `{}` to utf-8 for metric `{}`, ignoring tag' . format ( repr ( device_nam... |
def _delete ( self , * criterion ) :
"""Delete a model by some criterion .
Avoids race - condition check - then - delete logic by checking the count of affected rows .
: raises ` ResourceNotFound ` if the row cannot be deleted .""" | with self . flushing ( ) :
count = self . _query ( * criterion ) . delete ( )
if count == 0 :
raise ModelNotFoundError
return True |
def await_transform_exists ( cli , transform_path , does_exist = DEFAULT_TRANSFORM_EXISTS , timeout_seconds = DEFAULT_TIMEOUT_SECONDS ) :
"""Waits for a single transform to exist based on does _ exist .
: param cli :
: param transform _ path :
: param does _ exist : Whether or not to await for exist state ( T... | message_payload = { "transform_paths" : [ transform_path ] , "do_exist" : does_exist , "match_mode" : "All" , "timeout" : timeout_seconds }
msg = message . Message ( "await.unity.transform.exists" , message_payload )
cli . send_message ( msg )
response = cli . read_message ( )
verify_response ( response )
return bool (... |
def getEvidenceForID ( uuid : str , prim_id : str ) :
"""returns evidence for a causal primitive ( needs pagination support )""" | evidences = [ evidence . deserialize ( ) for evidence in Evidence . query . filter_by ( causalrelationship_id = prim_id ) . all ( ) ]
for evidence in evidences :
del evidence [ "causalrelationship_id" ]
return jsonify ( evidences ) |
def dropEvent ( self , ev ) :
"""Process drop event .""" | # use function above to accept event if it contains a file URL
files = self . _checkDragDropEvent ( ev )
if files :
pos = ev . pos ( )
dropitem = self . itemAt ( pos )
dprint ( 1 , "dropped on" , pos . x ( ) , pos . y ( ) , dropitem and str ( dropitem . text ( 1 ) ) )
# if event originated with ourselve... |
def andor_tags ( self ) :
"""Return consolidated metadata from Andor tags as dict .
Remove Andor tags from self . tags .""" | if not self . is_andor :
return None
tags = self . tags
result = { 'Id' : tags [ 'AndorId' ] . value }
for tag in list ( self . tags . values ( ) ) :
code = tag . code
if not 4864 < code < 5031 :
continue
value = tag . value
name = tag . name [ 5 : ] if len ( tag . name ) > 5 else tag . name... |
def FormatSOAPDateTime ( value ) :
"""Format a SOAP DateTime object for printing .
Args :
value : The DateTime object to format .
Returns :
A string representing the value .""" | value_date = value [ 'date' ]
return '%s-%s-%s %s:%s:%s (%s)' % ( value_date [ 'year' ] , value_date [ 'month' ] , value_date [ 'day' ] , value [ 'hour' ] , value [ 'minute' ] , value [ 'second' ] , value [ 'timeZoneId' ] ) |
def filtered_cls_slots ( self , cn : ClassDefinitionName , all_slots : bool = True ) -> List [ SlotDefinitionName ] :
"""Return the set of slots associated with the class that meet the filter criteria . Slots will be returned
in defining order , with class slots returned last
@ param cn : name of class to filte... | rval = [ ]
cls = self . schema . classes [ cn ]
cls_slots = self . all_slots ( cls , cls_slots_first = True )
for slot in cls_slots :
if all_slots or slot . range in self . schema . classes :
rval . append ( slot . name )
return rval |
def _filter_schema ( schema , schema_tables , exclude_table_columns ) :
"""Filters a schema to only include the specified tables in the
schema _ tables parameter . This will also filter out any colums for
included tables that reference tables that are not included
in the schema _ tables parameter
: param sc... | tables = { }
for tbl_name , tbl_data in schema [ 'tables' ] . items ( ) :
if not schema_tables or tbl_name in schema_tables :
columns = { }
exclude_columns = exclude_table_columns . get ( tbl_name , [ ] )
for col_name , col_data in tbl_data [ 'columns' ] . items ( ) :
if col_name... |
def check ( self , pattern ) :
"""Apply ` pattern ` on the current position and return
the match object . ( Doesn ' t touch pos ) . Use this for
lookahead .""" | if self . eos :
raise EndOfText ( )
if pattern not in self . _re_cache :
self . _re_cache [ pattern ] = re . compile ( pattern , self . flags )
return self . _re_cache [ pattern ] . match ( self . data , self . pos ) |
def _mod_run_check ( cmd_kwargs , onlyif , unless ) :
'''Execute the onlyif and unless logic .
Return a result dict if :
* onlyif failed ( onlyif ! = 0)
* unless succeeded ( unless = = 0)
else return True''' | if onlyif :
if __salt__ [ 'cmd.retcode' ] ( onlyif , ** cmd_kwargs ) != 0 :
return { 'comment' : 'onlyif condition is false' , 'skip_watch' : True , 'result' : True }
if unless :
if __salt__ [ 'cmd.retcode' ] ( unless , ** cmd_kwargs ) == 0 :
return { 'comment' : 'unless condition is true' , 'sk... |
async def from_payload ( cls , payload , endpoint , idgen , debug , force_protocol = None ) :
"""Create Service object from a payload .""" | service_name = payload [ "service" ]
if "protocols" not in payload :
raise SongpalException ( "Unable to find protocols from payload: %s" % payload )
protocols = payload [ "protocols" ]
_LOGGER . debug ( "Available protocols for %s: %s" , service_name , protocols )
if force_protocol and force_protocol . value in pr... |
def get_constant_state ( self ) :
"""Read state that was written in " first _ part " mode .
Returns :
a structure""" | ret = self . constant_states [ self . next_constant_state ]
self . next_constant_state += 1
return ret |
def add_tags ( ctx , archive_name , tags ) :
'''Add tags to an archive''' | _generate_api ( ctx )
var = ctx . obj . api . get_archive ( archive_name )
var . add_tags ( * tags ) |
def _decrypt ( file_contents , password ) :
"""The corresponding decryption routine for _ encrypt ( ) .
' securesystemslib . exceptions . CryptoError ' raised if the decryption fails .""" | # Extract the salt , iterations , hmac , initialization vector , and ciphertext
# from ' file _ contents ' . These five values are delimited by
# ' _ ENCRYPTION _ DELIMITER ' . This delimiter is arbitrarily chosen and should
# not occur in the hexadecimal representations of the fields it is
# separating . Raise ' secur... |
def sliding_window ( sequence , win_size , step = 1 ) :
"""Returns a generator that will iterate through
the defined chunks of input sequence . Input sequence
must be iterable .
Credit : http : / / scipher . wordpress . com / 2010/12/02 / simple - sliding - window - iterator - in - python /
https : / / gith... | # Verify the inputs
try :
it = iter ( sequence )
except TypeError :
raise ValueError ( "sequence must be iterable." )
if not isinstance ( win_size , int ) :
raise ValueError ( "type(win_size) must be int." )
if not isinstance ( step , int ) :
raise ValueError ( "type(step) must be int." )
if step > win_... |
def getArraysByName ( elem , name ) :
"""Return a list of arrays with name name under elem .""" | name = StripArrayName ( name )
return elem . getElements ( lambda e : ( e . tagName == ligolw . Array . tagName ) and ( e . Name == name ) ) |
def parse ( cls , fptr , offset , length ) :
"""Parse number list box .
Parameters
fptr : file
Open file object .
offset : int
Start position of box in bytes .
length : int
Length of the box in bytes .
Returns
LabelBox
Instance of the current number list box .""" | num_bytes = offset + length - fptr . tell ( )
raw_data = fptr . read ( num_bytes )
num_associations = int ( len ( raw_data ) / 4 )
lst = struct . unpack ( '>' + 'I' * num_associations , raw_data )
return cls ( lst , length = length , offset = offset ) |
def range_values ( args ) :
"""Function used to compute returned range value of [ x ] range function .""" | if len ( args ) == 1 :
return Interval ( 0 , args [ 0 ] . high )
elif len ( args ) == 2 :
return Interval ( args [ 0 ] . low , args [ 1 ] . high )
elif len ( args ) == 3 :
is_neg = args [ 2 ] . low < 0
is_pos = args [ 2 ] . high > 0
if is_neg and is_pos :
return UNKNOWN_RANGE
elif is_neg... |
def calculate_transmission ( thickness_cm : np . float , atoms_per_cm3 : np . float , sigma_b : np . array ) :
"""calculate the transmission signal using the formula
transmission = exp ( - thickness _ cm * atoms _ per _ cm3 * 1e - 24 * sigma _ b )
Parameters :
thickness : float ( in cm )
atoms _ per _ cm3 :... | miu_per_cm = calculate_linear_attenuation_coefficient ( atoms_per_cm3 = atoms_per_cm3 , sigma_b = sigma_b )
transmission = calculate_trans ( thickness_cm = thickness_cm , miu_per_cm = miu_per_cm )
return miu_per_cm , transmission |
def generate_user_agent ( os = None , navigator = None , platform = None , device_type = None ) :
"""Generates HTTP User - Agent header
: param os : limit list of os for generation
: type os : string or list / tuple or None
: param navigator : limit list of browser engines for generation
: type navigator : ... | return generate_navigator ( os = os , navigator = navigator , platform = platform , device_type = device_type ) [ 'user_agent' ] |
def create ( gandi , address , destination ) :
"""Create a domain mail forward .""" | source , domain = address
result = gandi . forward . create ( domain , source , destination )
return result |
def restore_cmd ( argv ) :
"""Try to restore a broken virtualenv by reinstalling the same python version on top of it""" | if len ( argv ) < 1 :
sys . exit ( 'You must provide a valid virtualenv to target' )
env = argv [ 0 ]
path = workon_home / env
py = path / env_bin_dir / ( 'python.exe' if windows else 'python' )
exact_py = py . resolve ( ) . name
return check_call ( [ sys . executable , "-m" , "virtualenv" , str ( path . absolute (... |
def Dict ( self , name , initial = None , ** extra ) :
"""The dictionary datatype ( Hash ) .
: param name : The name of the dictionary .
: keyword initial : Initial contents .
: keyword \ * \ * extra : Initial contents as keyword arguments .
The ` ` initial ` ` , and ` ` * * extra ` ` keyword arguments
wi... | return types . Dict ( name , self . api , initial = initial , ** extra ) |
def get_external_host_tags ( self ) :
"""Returns a list of tags for every host that is detected by the vSphere
integration .
Returns a list of pairs ( hostname , { ' SOURCE _ TYPE : list _ of _ tags } , )""" | self . log . debug ( "Sending external_host_tags now" )
external_host_tags = [ ]
for instance in self . instances :
i_key = self . _instance_key ( instance )
if not self . mor_cache . contains ( i_key ) :
self . log . warning ( "Unable to extract host tags for vSphere instance: {}" . format ( i_key ) )
... |
def lib ( names , sources = [ ] , requirements = [ ] , default_build = [ ] , usage_requirements = [ ] ) :
"""The implementation of the ' lib ' rule . Beyond standard syntax that rule allows
simplified : ' lib a b c ; ' .""" | assert is_iterable_typed ( names , basestring )
assert is_iterable_typed ( sources , basestring )
assert is_iterable_typed ( requirements , basestring )
assert is_iterable_typed ( default_build , basestring )
assert is_iterable_typed ( usage_requirements , basestring )
if len ( names ) > 1 :
if any ( r . startswith... |
def collect_and_execute_subfields ( self , return_type : GraphQLObjectType , field_nodes : List [ FieldNode ] , path : ResponsePath , result : Any , ) -> AwaitableOrValue [ Dict [ str , Any ] ] :
"""Collect sub - fields to execute to complete this value .""" | sub_field_nodes = self . collect_subfields ( return_type , field_nodes )
return self . execute_fields ( return_type , result , path , sub_field_nodes ) |
def get_compensation_matrix ( ct21 , ct31 , ct12 , ct32 , ct13 , ct23 ) :
"""Compute crosstalk inversion matrix
The spillover matrix is
| | c11 c12 c13 |
| | c21 c22 c23 |
| | c31 c32 c33 |
The diagonal elements are set to 1 , i . e .
ct11 = c22 = c33 = 1
Parameters
cij : float
Spill from channel ... | ct11 = 1
ct22 = 1
ct33 = 1
if ct21 < 0 :
raise ValueError ( "ct21 matrix element must not be negative!" )
if ct31 < 0 :
raise ValueError ( "ct31 matrix element must not be negative!" )
if ct12 < 0 :
raise ValueError ( "ct12 matrix element must not be negative!" )
if ct32 < 0 :
raise ValueError ( "ct32 m... |
def get_resources_by_ids ( self , resource_ids ) :
"""Gets a ` ` ResourceList ` ` corresponding to the given ` ` IdList ` ` .
In plenary mode , the returned list contains all of the resources
specified in the ` ` Id ` ` list , in the order of the list ,
including duplicates , or an error results if an ` ` Id ... | # Implemented from template for
# osid . resource . ResourceLookupSession . get _ resources _ by _ ids
# NOTE : This implementation currently ignores plenary view
collection = JSONClientValidated ( 'resource' , collection = 'Resource' , runtime = self . _runtime )
object_id_list = [ ]
for i in resource_ids :
object... |
def split_date ( value ) :
"""This method splits a date in a tuple .
value : valid iso date
ex :
2016-01-31 : ( ' 2016 ' , ' 01 ' , ' 01 ' )
2016-01 : ( ' 2016 ' , ' 01 ' , ' ' )
2016 : ( ' 2016 ' , ' ' , ' ' )""" | if not is_valid_date ( value ) :
return ( '' , '' , '' )
splited = value . split ( '-' )
try :
year = splited [ 0 ]
except IndexError :
year = ''
try :
month = splited [ 1 ]
except IndexError :
month = ''
try :
day = splited [ 2 ]
except IndexError :
day = ''
return ( year , month , day ) |
def dbRestore ( self , db_value , context = None ) :
"""Converts a stored database value to Python .
: param py _ value : < variant >
: param context : < orb . Context >
: return : < variant >""" | if db_value is not None :
jdata = super ( QueryColumn , self ) . dbRestore ( db_value , context = context )
return orb . Query . fromJSON ( jdata )
else :
return db_value |
def find_in_bids ( filename , pattern = None , generator = False , upwards = False , wildcard = True , ** kwargs ) :
"""Find nearest file matching some criteria .
Parameters
filename : instance of Path
search the root for this file
pattern : str
glob string for search criteria of the filename of interest ... | if upwards and generator :
raise ValueError ( 'You cannot search upwards and have a generator' )
if pattern is None :
pattern = _generate_pattern ( wildcard , kwargs )
lg . debug ( f'Searching {pattern} in {filename}' )
if upwards and filename == find_root ( filename ) :
raise FileNotFoundError ( f'Could no... |
def get_power ( self , callb = None ) :
"""Convenience method to request the power status from the device
This method will check whether the value has already been retrieved from the device ,
if so , it will simply return it . If no , it will request the information from the device
and request that callb be e... | if self . power_level is None :
response = self . req_with_resp ( LightGetPower , LightStatePower , callb = callb )
return self . power_level |
def upload ( self , params = { } ) :
"""start uploading the file until upload is complete or error .
This is the main method to used , If you do not care about
state of process .
Args :
params : a dict object describe video info , eg title ,
tags , description , category .
all video params see the doc o... | if self . upload_token is not None : # resume upload
status = self . check ( )
if status [ 'status' ] != 4 :
return self . commit ( )
else :
self . new_slice ( )
while self . slice_task_id != 0 :
self . upload_slice ( )
return self . commit ( )
else : # new upload... |
def _insertNewBlock ( self ) :
"""Enter pressed .
Insert properly indented block""" | cursor = self . textCursor ( )
atStartOfLine = cursor . positionInBlock ( ) == 0
with self :
cursor . insertBlock ( )
if not atStartOfLine : # if whole line is moved down - just leave it as is
self . _indenter . autoIndentBlock ( cursor . block ( ) )
self . ensureCursorVisible ( ) |
def update ( self , data : Union [ Mapping , str , bytes ] , layer : str = None , source : str = None ) :
"""Adds additional data into the ConfigTree .
Parameters
data :
source data
layer :
layer to load data into . If none is supplied the outermost one is used
source :
Source to attribute the values ... | if isinstance ( data , dict ) :
self . _read_dict ( data , layer , source )
elif isinstance ( data , ConfigTree ) : # TODO : set this to parse the other config tree including layer and source info . Maybe .
self . _read_dict ( data . to_dict ( ) , layer , source )
elif isinstance ( data , str ) :
if data . ... |
def predict_proba ( self , features ) :
"""Use the optimized pipeline to estimate the class probabilities for a feature set .
Parameters
features : array - like { n _ samples , n _ features }
Feature matrix of the testing set
Returns
array - like : { n _ samples , n _ target }
The class probabilities of... | if not self . fitted_pipeline_ :
raise RuntimeError ( 'A pipeline has not yet been optimized. Please call fit() first.' )
else :
if not ( hasattr ( self . fitted_pipeline_ , 'predict_proba' ) ) :
raise RuntimeError ( 'The fitted pipeline does not have the predict_proba() function.' )
features = self... |
def parse_value_namedinstance ( self , tup_tree ) :
"""< ! ELEMENT VALUE . NAMEDINSTANCE ( INSTANCENAME , INSTANCE ) >
Returns :
CIMInstance object with path set ( without host or namespace ) .""" | self . check_node ( tup_tree , 'VALUE.NAMEDINSTANCE' )
k = kids ( tup_tree )
if len ( k ) != 2 :
raise CIMXMLParseError ( _format ( "Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(INSTANCENAME, INSTANCE))" , name ( tup_tree ) , k ) , conn_id = self . conn_id )
inst_pat... |
def parents ( self , as_resources = False ) :
'''method to return hierarchical parents of this resource
Args :
as _ resources ( bool ) : if True , opens each as appropriate resource type instead of return URI only
Returns :
( list ) : list of resources''' | parents = [ o for s , p , o in self . rdf . graph . triples ( ( None , self . rdf . prefixes . fedora . hasParent , None ) ) ]
# if as _ resources , issue GET requests for children and return
if as_resources :
logger . debug ( 'retrieving parent as resource' )
parents = [ self . repo . get_resource ( parent ) f... |
def create ( self , project , name , ** attrs ) :
"""Create a new : class : ` CustomAttribute ` .
: param project : : class : ` Project ` id
: param name : name of the custom attribute
: param attrs : optional attributes of the custom attributes""" | attrs . update ( { 'project' : project , 'name' : name } )
return self . _new_resource ( payload = attrs ) |
def check_for_error ( func ) :
"""Executes the wrapped function and inspects the response object
for specific errors .""" | @ functools . wraps ( func )
def wrapper ( * args , ** kwargs ) :
try :
response = func ( * args , ** kwargs )
status_code = response . status_code
if status_code in range ( 200 , 204 ) :
return response
if status_code == 204 :
return
data = response .... |
def encode ( self , pdu ) :
"""encode the contents of the BSLCI into the PDU .""" | if _debug :
BSLCI . _debug ( "encode %r" , pdu )
# copy the basics
PCI . update ( pdu , self )
pdu . put ( self . bslciType )
# 0x83
pdu . put ( self . bslciFunction )
if ( self . bslciLength != len ( self . pduData ) + 4 ) :
raise EncodingError ( "invalid BSLCI length" )
pdu . put_short ( self . bslciLength ) |
def reftrack_descriptor_data ( rt , role ) :
"""Return the data for the descriptor that is loaded by the reftrack
: param rt : the : class : ` jukeboxcore . reftrack . Reftrack ` holds the data
: type rt : : class : ` jukeboxcore . reftrack . Reftrack `
: param role : item data role
: type role : QtCore . Q... | tfi = rt . get_taskfileinfo ( )
if not tfi :
return
return filesysitemdata . taskfileinfo_descriptor_data ( tfi , role ) |
def open_resource ( source ) :
"""Opens a resource in binary reading mode . Wraps the resource with a
context manager when it doesn ' t have one .
: param source : a filepath or an URL .""" | try :
return open ( source , mode = 'rb' )
except ( IOError , OSError ) as err :
try :
resource = urlopen ( source )
except ValueError :
pass
else :
resource . name = resource . url
if hasattr ( resource , '__enter__' ) :
return resource
else :
... |
def _parse_line_vars ( self , line ) :
"""Parse a line in a [ XXXXX : vars ] section .""" | key_values = { }
# Undocumented feature allows json in vars sections like so :
# [ prod : vars ]
# json _ like _ vars = [ { ' name ' : ' htpasswd _ auth ' } ]
# We ' ll try this first . If it fails , we ' ll fall back to normal var
# lines . Since it ' s undocumented , we just assume some things .
k , v = line . strip ... |
def make_graph ( node , call_deps = False ) :
'''Create a dependency graph from an ast node .
: param node : ast node .
: param call _ deps : if true , then the graph will create a cyclic dependence for all
function calls . ( i . e for ` a . b ( c ) ` a depends on b and b depends on a )
: returns : a tuple ... | gen = GraphGen ( call_deps = call_deps )
gen . visit ( node )
return gen . graph , gen . undefined |
def _add_non_batch ( self , TX_nodes , PmtInf_nodes ) :
"""Method to add a transaction as non batch , will fold the transaction
together with the payment info node and append to the main xml .""" | PmtInf_nodes [ 'PmtInfNode' ] . append ( PmtInf_nodes [ 'PmtInfIdNode' ] )
PmtInf_nodes [ 'PmtInfNode' ] . append ( PmtInf_nodes [ 'PmtMtdNode' ] )
PmtInf_nodes [ 'PmtInfNode' ] . append ( PmtInf_nodes [ 'BtchBookgNode' ] )
PmtInf_nodes [ 'PmtInfNode' ] . append ( PmtInf_nodes [ 'NbOfTxsNode' ] )
PmtInf_nodes [ 'PmtInf... |
def fill_nan ( self , val : str , * cols ) :
"""Fill NaN values with new values in the main dataframe
: param val : new value
: type val : str
: param \ * cols : names of the colums
: type \ * cols : str , at least one
: example : ` ` ds . fill _ nan ( " new value " , " mycol1 " , " mycol2 " ) ` `""" | df = self . _fill_nan ( val , * cols )
if df is not None :
self . df = df
else :
self . err ( "Can not fill nan values" ) |
def _cmp_key ( self , obj = None ) :
"""Comparison key for sorting results from all linters .
The sort should group files and lines from different linters to make it
easier for refactoring .""" | if not obj :
obj = self
line_nr = int ( obj . line_nr ) if obj . line_nr else 0
col = int ( obj . col ) if obj . col else 0
return ( obj . path , line_nr , col , obj . msg ) |
def base64url_decode ( msg ) :
"""Decode a base64 message based on JWT spec , Appendix B .
" Notes on implementing base64url encoding without padding " """ | rem = len ( msg ) % 4
if rem :
msg += b'=' * ( 4 - rem )
return base64 . urlsafe_b64decode ( msg ) |
def _stop ( self ) :
"""Stop the GNS3 VM""" | engine = self . current_engine ( )
if "vm" in self . _controller . computes :
yield from self . _controller . delete_compute ( "vm" )
if engine . running :
log . info ( "Stop the GNS3 VM" )
yield from engine . stop ( ) |
def _asdict ( self ) :
"""Create a dictionary snapshot of the current config values .""" | # Start with any default values we have , and override with loaded values ,
# and then override with flag values .
retval = { key : self . _declarations [ key ] . default_value for key in self . _declarations if self . _declarations [ key ] . has_default }
retval . update ( self . _loaded_values )
# Only update keys th... |
def qImageToArray ( qimage , dtype = 'array' ) :
"""Convert QImage to numpy . ndarray . The dtype defaults to uint8
for QImage . Format _ Indexed8 or ` bgra _ dtype ` ( i . e . a record array )
for 32bit color images . You can pass a different dtype to use , or
' array ' to get a 3D uint8 array for color imag... | result_shape = ( qimage . height ( ) , qimage . width ( ) )
temp_shape = ( qimage . height ( ) , qimage . bytesPerLine ( ) * 8 // qimage . depth ( ) )
if qimage . format ( ) in ( QtGui . QImage . Format_ARGB32_Premultiplied , QtGui . QImage . Format_ARGB32 , QtGui . QImage . Format_RGB32 ) :
if dtype == 'rec' :
... |
def set_response_headers ( self , request , total_count ) :
'''Set the correct range headers on the response
: param request : a request object
: param total _ count : the total number of results''' | response = request . response
response . headerlist . append ( ( 'Access-Control-Expose-Headers' , 'Content-Range, X-Content-Range' ) )
response . accept_ranges = 'items'
if total_count is None :
raise RangeParseException ( 'Provided length value is null' )
if total_count > 0 :
response . content_range = self .... |
def subtype ( self , ** kwargs ) :
"""Create a specialization of | ASN . 1 | schema object .
The ` subtype ( ) ` method accepts the same set arguments as | ASN . 1 |
class takes on instantiation except that all parameters
of the ` subtype ( ) ` method are optional .
With the exception of the arguments descr... | initializers = self . readOnly . copy ( )
cloneValueFlag = kwargs . pop ( 'cloneValueFlag' , False )
implicitTag = kwargs . pop ( 'implicitTag' , None )
if implicitTag is not None :
initializers [ 'tagSet' ] = self . tagSet . tagImplicitly ( implicitTag )
explicitTag = kwargs . pop ( 'explicitTag' , None )
if expli... |
def update_module_moved_fields ( cr , model , moved_fields , old_module , new_module ) :
"""Update module for field definition in general tables that have been moved
from one module to another .
NOTE : This is not needed in > = v12 , as now Odoo always add the XML - ID entry :
https : / / github . com / odoo ... | if version_info [ 0 ] <= 7 :
do_raise ( "This only works for Odoo version >=v8" )
if version_info [ 0 ] >= 12 :
do_raise ( "This should be used only for Odoo version <v12" )
if not isinstance ( moved_fields , ( list , tuple ) ) :
do_raise ( "moved_fields %s must be a tuple or list!" % moved_fields )
logger ... |
def get_modules ( ) :
'''List available ` ` eselect ` ` modules .
CLI Example :
. . code - block : : bash
salt ' * ' eselect . get _ modules''' | modules = [ ]
module_list = exec_action ( 'modules' , 'list' , action_parameter = '--only-names' )
if not module_list :
return None
for module in module_list :
if module not in [ 'help' , 'usage' , 'version' ] :
modules . append ( module )
return modules |
def _e ( op , inv = False ) :
"""Lightweight factory which returns a method that builds an Expression
consisting of the left - hand and right - hand operands , using ` op ` .""" | def inner ( self , rhs ) :
if inv :
return Expression ( rhs , op , self )
return Expression ( self , op , rhs )
return inner |
def determine_config_changes ( self ) :
"""The magic : Determine what has changed since the last time .
Caller should pass the returned config to register _ config _ changes to persist .""" | # ' update ' here is synonymous with ' add or update '
instances = set ( )
new_configs = { }
meta_changes = { 'changed_instances' : set ( ) , 'remove_instances' : [ ] , 'remove_configs' : self . get_remove_configs ( ) }
for config_file , stored_config in self . get_registered_configs ( ) . items ( ) :
new_config = ... |
def predict ( self , X ) :
"""Perform classification on an array of test vectors X .
Parameters
X : array - like , shape = [ n _ samples , n _ features ]
Returns
C : array , shape = [ n _ samples ]
Predicted target values for X""" | jll = self . _joint_log_likelihood ( X )
return self . classes_ [ np . argmax ( jll , axis = 1 ) ] |
def to_uint8 ( self , data ) :
"""Converts floating point image on the range [ 0,1 ] and integer images
on the range [ 0,255 ] to uint8 , clipping if necessary .""" | np = util . get_module ( "numpy" , required = "wandb.Image requires numpy if not supplying PIL Images: pip install numpy" )
# I think it ' s better to check the image range vs the data type , since many
# image libraries will return floats between 0 and 255
# some images have range - 1 . . . 1 or 0-1
dmin = np . min ( ... |
async def dump_message ( obj , msg , field_archiver = None ) :
"""Dumps message to the object .
Returns message popo representation .
: param obj :
: param msg :
: param field _ archiver :
: return :""" | mtype = msg . __class__
fields = mtype . f_specs ( )
obj = collections . OrderedDict ( ) if obj is None else get_elem ( obj )
for field in fields :
await dump_message_field ( obj , msg = msg , field = field , field_archiver = field_archiver )
return obj |
def __convertRlocToRouterId ( self , xRloc16 ) :
"""mapping Rloc16 to router id
Args :
xRloc16 : hex rloc16 short address
Returns :
actual router id allocated by leader""" | routerList = [ ]
routerList = self . __sendCommand ( WPANCTL_CMD + 'getprop -v Thread:RouterTable' )
print routerList
print xRloc16
for line in routerList :
if re . match ( '\[|\]' , line ) :
continue
if re . match ( WPAN_CARRIER_PROMPT , line , re . M | re . I ) :
break
router = [ ]
rou... |
def load ( self ) :
"""a private method that loads an estimator object from the filesystem""" | if self . is_file_persisted :
self . object_file . open ( )
temp = dill . loads ( self . object_file . read ( ) )
self . set_object ( temp )
self . object_file . close ( ) |
def create_enum_subset ( enum_type , help_string = NO_HELP , default = NO_DEFAULT ) : # type : ( Type [ Enum ] , str , EnumSubset ) - > EnumSubset
"""Create an enum config
: param enum _ type :
: param help _ string :
: param default :
: return :""" | # noinspection PyTypeChecker
return ParamEnumSubset ( help_string = help_string , default = default , enum_type = enum_type , ) |
def set_filter_raw_should ( self , filter_raw_should ) :
"""Bool filter should to be used when getting items from Ocean index""" | self . filter_raw_should = filter_raw_should
self . filter_raw_should_dict = [ ]
splitted = re . compile ( FILTER_SEPARATOR ) . split ( filter_raw_should )
for fltr_raw in splitted :
fltr = self . __process_filter ( fltr_raw )
self . filter_raw_should_dict . append ( fltr ) |
def move ( self , bucket , key , bucket_to , key_to , force = 'false' ) :
"""移动文件 :
将资源从一个空间到另一个空间 , 具体规格参考 :
http : / / developer . qiniu . com / docs / v6 / api / reference / rs / move . html
Args :
bucket : 待操作资源所在空间
bucket _ to : 目标资源空间名
key : 待操作资源文件名
key _ to : 目标资源文件名
Returns :
一个dict变量 , 成... | resource = entry ( bucket , key )
to = entry ( bucket_to , key_to )
return self . __rs_do ( 'move' , resource , to , 'force/{0}' . format ( force ) ) |
def overlay_gateway_site_tunnel_dst_address ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" )
name_key = ET . SubElement ( overlay_gateway , "name" )
name_key . text = kwargs . pop ( 'name' )
site = ET . SubElement ( overlay_gateway , "site" )
name_key = ET . SubEl... |
def nucnorm ( x0 , rho , gamma ) :
"""Proximal operator for the nuclear norm ( sum of the singular values of a matrix )
Parameters
x0 : array _ like
The starting or initial point used in the proximal update step
rho : float
Momentum parameter for the proximal step ( larger value - > stays closer to x0)
... | # compute SVD
u , s , v = np . linalg . svd ( x0 , full_matrices = False )
# soft threshold the singular values
sthr = np . maximum ( s - ( gamma / float ( rho ) ) , 0 )
# reconstruct
x_out = ( u . dot ( np . diag ( sthr ) ) . dot ( v ) )
return x_out |
def from_dataframe ( self , dataframe , add_index_column = False ) :
"""Set tabular attributes to the writer from : py : class : ` pandas . DataFrame ` .
Following attributes are set by the method :
- : py : attr : ` ~ . headers `
- : py : attr : ` ~ . value _ matrix `
- : py : attr : ` ~ . type _ hints `
... | if typepy . String ( dataframe ) . is_type ( ) :
import pandas as pd
dataframe = pd . read_pickle ( dataframe )
self . headers = list ( dataframe . columns . values )
self . type_hints = [ self . __get_typehint_from_dtype ( dtype ) for dtype in dataframe . dtypes ]
if add_index_column :
self . headers = [ "... |
def get_record_params ( args ) :
"""Get record parameters from command options .
Argument :
args : arguments object""" | name , rtype , content , ttl , priority = ( args . name , args . rtype , args . content , args . ttl , args . priority )
return name , rtype , content , ttl , priority |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.