signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _responses ( self , request ) :
"""internal API , returns an iterator with all responses matching
the request .""" | request = self . _before_record_request ( request )
for index , ( stored_request , response ) in enumerate ( self . data ) :
if requests_match ( request , stored_request , self . _match_on ) :
yield index , response |
def extract_text ( fpath ) :
"""Extracts structured text content from a plain - text file at ` ` fpath ` ` .
Parameters
fpath : str
Path to the text file . .
Returns
: class : ` . StructuredFeature `
A : class : ` . StructuredFeature ` that contains sentence context .""" | with codecs . open ( fpath , 'r' ) as f : # Determine the encoding of the file .
document = f . read ( )
encoding = chardet . detect ( document ) [ 'encoding' ]
document = document . decode ( encoding )
tokens = [ ]
sentences = [ ]
i = 0
for sentence in nltk . tokenize . sent_tokenize ( document ) :
sentences .... |
def add_jpeg_decoding ( module_spec ) :
"""Adds operations that perform JPEG decoding and resizing to the graph . .
Args :
module _ spec : The hub . ModuleSpec for the image module being used .
Returns :
Tensors for the node to feed JPEG data into , and the output of the
preprocessing steps .""" | input_height , input_width = hub . get_expected_image_size ( module_spec )
input_depth = hub . get_num_image_channels ( module_spec )
jpeg_data = tf . placeholder ( tf . string , name = 'DecodeJPGInput' )
decoded_image = tf . image . decode_jpeg ( jpeg_data , channels = input_depth )
# Convert from full range of uint8 ... |
def encode_example ( self , bbox ) :
"""See base class for details .""" | # Validate the coordinates
for coordinate in bbox :
if not isinstance ( coordinate , float ) :
raise ValueError ( 'BBox coordinates should be float. Got {}.' . format ( bbox ) )
if not 0.0 <= coordinate <= 1.0 :
raise ValueError ( 'BBox coordinates should be between 0 and 1. Got {}.' . format ( ... |
def has_common ( self , other ) :
"""Return set of common words between two word sets .""" | if not isinstance ( other , WordSet ) :
raise ValueError ( 'Can compare only WordSets' )
return self . term_set & other . term_set |
def p_expression_div ( self , p ) :
'expression : expression DIVIDE expression' | p [ 0 ] = Divide ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def _add_resources ( data , runtime ) :
"""Merge input resources with current CWL runtime parameters .""" | if "config" not in data :
data [ "config" ] = { }
# Convert input resources , which may be a JSON string
resources = data . get ( "resources" , { } ) or { }
if isinstance ( resources , six . string_types ) and resources . startswith ( ( "{" , "[" ) ) :
resources = json . loads ( resources )
data [ "resource... |
def add_variation ( self , order = 1 , first_order = None , first_order_2 = None , testparticle = - 1 ) :
"""This function adds a set of variational particles to the simulation .
If there are N real particles in the simulation , this functions adds N additional variational
particles . To see how many particles ... | cur_var_config_N = self . var_config_N
if order == 1 :
index = clibrebound . reb_add_var_1st_order ( byref ( self ) , c_int ( testparticle ) )
elif order == 2 :
if first_order is None :
raise AttributeError ( "Please specify corresponding first order variational equations when initializing second order ... |
def set_queue_acl ( self , queue_name , signed_identifiers = None , timeout = None ) :
'''Sets stored access policies for the queue that may be used with Shared
Access Signatures .
When you set permissions for a queue , the existing permissions are replaced .
To update the queue ' s permissions , call : func ... | _validate_not_none ( 'queue_name' , queue_name )
_validate_access_policies ( signed_identifiers )
request = HTTPRequest ( )
request . method = 'PUT'
request . host_locations = self . _get_host_locations ( )
request . path = _get_path ( queue_name )
request . query = { 'comp' : 'acl' , 'timeout' : _int_to_str ( timeout ... |
def deallocate_network_ipv4 ( self , id_network_ipv4 ) :
"""Deallocate all relationships between NetworkIPv4.
: param id _ network _ ipv4 : ID for NetworkIPv4
: return : Nothing
: raise InvalidParameterError : Invalid ID for NetworkIPv4.
: raise NetworkIPv4NotFoundError : NetworkIPv4 not found .
: raise D... | if not is_valid_int_param ( id_network_ipv4 ) :
raise InvalidParameterError ( u'The identifier of NetworkIPv4 is invalid or was not informed.' )
url = 'network/ipv4/' + str ( id_network_ipv4 ) + '/deallocate/'
code , xml = self . submit ( None , 'DELETE' , url )
return self . response ( code , xml ) |
def read_cyc ( this , fn , conv = 1.0 ) :
"""Read the lattice information from a cyc . dat file ( i . e . , tblmd input file )""" | f = paropen ( fn , "r" )
f . readline ( )
f . readline ( )
f . readline ( )
f . readline ( )
cell = np . array ( [ [ 0.0 , 0.0 , 0.0 ] , [ 0.0 , 0.0 , 0.0 ] , [ 0.0 , 0.0 , 0.0 ] ] )
l = f . readline ( )
s = map ( float , l . split ( ) )
cell [ 0 , 0 ] = s [ 0 ] * conv
cell [ 1 , 0 ] = s [ 1 ] * conv
cell [ 2 , 0 ] = s... |
def follow ( resources , ** kwargs ) :
"""Follow publications involved with resources .""" | # subscribe
client = redis . Redis ( decode_responses = True , ** kwargs )
resources = resources if resources else find_resources ( client )
channels = [ Keys . EXTERNAL . format ( resource ) for resource in resources ]
if resources :
subscription = Subscription ( client , * channels )
# listen
while resources :
... |
def file_exists ( self , filename , directory = False , note = None , loglevel = logging . DEBUG ) :
"""Return True if file exists on the target host , else False
@ param filename : Filename to determine the existence of .
@ param directory : Indicate that the file is a directory .
@ param note : See send ( )... | shutit = self . shutit
shutit . handle_note ( note , 'Looking for filename in current environment: ' + filename )
test_type = '-d' if directory is True else '-e' if directory is None else '-a'
# v the space is intentional , to avoid polluting bash history .
test = ' test %s %s' % ( test_type , filename )
output = self ... |
def match_start_date ( self , start , end , match ) :
"""Matches temporals whose start date falls in between the given dates inclusive .
arg : start ( osid . calendaring . DateTime ) : start of date range
arg : end ( osid . calendaring . DateTime ) : end of date range
arg : match ( boolean ) : ` ` true ` ` if... | if match :
if end < start :
raise errors . InvalidArgument ( 'end date must be >= start date when match = True' )
self . _query_terms [ 'startDate' ] = { '$gte' : start , '$lte' : end }
else :
raise errors . InvalidArgument ( 'match = False not currently supported' ) |
def create_widget ( self ) :
"""Create the underlying widget .""" | d = self . declaration
self . widget = EditText ( self . get_context ( ) , None , d . style or "@attr/editTextStyle" ) |
def kmer_lca_records ( seqs_path , one_codex_api_key : 'One Codex API key' = None , fastq : 'input is fastq; disable autodetection' = False , progress : 'show progress bar (sent to stderr)' = False ) :
'''Parallel lowest common ancestor sequence classification of fasta / q using the One Codex API .
Returns Biopyt... | records = parse_seqs ( seqs_path , fastq )
one_codex_api_key = one_codex_api_key if one_codex_api_key else config ( ) [ 'one_codex_api_key' ]
print ( 'Classifying sequences…' , file = sys . stderr )
records = asyncio . get_event_loop ( ) . run_until_complete ( oc_classify ( records , one_codex_api_key , progress , Fals... |
async def set_message ( self , text = None , reply_to = 0 , parse_mode = ( ) , link_preview = None ) :
"""Changes the draft message on the Telegram servers . The changes are
reflected in this object .
: param str text : New text of the draft .
Preserved if left as None .
: param int reply _ to : Message ID ... | if text is None :
text = self . _text
if reply_to == 0 :
reply_to = self . reply_to_msg_id
if link_preview is None :
link_preview = self . link_preview
raw_text , entities = await self . _client . _parse_message_text ( text , parse_mode )
result = await self . _client ( SaveDraftRequest ( peer = self . _pee... |
def build_headermap ( headers ) :
"""Construct dictionary { header _ file : set _ of _ included _ files } .
This function operates on " real " set of includes , in the sense that it
parses each header file to check which files are included from there .""" | # TODO : what happens if some headers are circularly dependent ?
headermap = { }
for hfile in headers :
headermap [ hfile ] = None
for hfile in headers :
assert ( hfile . startswith ( "c/" ) or hfile . startswith ( "datatable/include/" ) )
inc = find_includes ( hfile )
for f in inc :
assert f !=... |
def make ( self , host = "localhost" , port = 8082 , protocol = "http" , base_uri = "" , os_auth_type = "http" , ** kwargs ) :
"""Initialize a session to Contrail API server
: param os _ auth _ type : auth plugin to use :
- http : basic HTTP authentification
- v2password : keystone v2 auth
- v3password : ke... | loader = loading . base . get_plugin_loader ( os_auth_type )
plugin_options = { opt . dest : kwargs . pop ( "os_%s" % opt . dest ) for opt in loader . get_options ( ) if 'os_%s' % opt . dest in kwargs }
plugin = loader . load_from_options ( ** plugin_options )
return self . load_from_argparse_arguments ( Namespace ( **... |
def get_client ( self , client_type ) :
"""get _ client .""" | if client_type not in self . _client_cache :
client_class = self . _get_class ( client_type )
self . _client_cache [ client_type ] = self . _get_client_instance ( client_class )
return self . _client_cache [ client_type ] |
def recursive_directory_listing ( log , baseFolderPath , whatToList = "all" ) :
"""* list directory contents recursively . *
Options to list only files or only directories .
* * Key Arguments : * *
- ` ` log ` ` - - logger
- ` ` baseFolderPath ` ` - - path to the base folder to list contained files and fold... | log . debug ( 'starting the ``recursive_directory_listing`` function' )
# # VARIABLES # #
matchedPathList = [ ]
parentDirectoryList = [ baseFolderPath , ]
count = 0
while os . listdir ( baseFolderPath ) and count < 20 :
count += 1
while len ( parentDirectoryList ) != 0 :
childDirList = [ ]
for p... |
def update ( did ) :
"""Update DDO of an existing asset
tags :
- ddo
consumes :
- application / json
parameters :
- in : body
name : body
required : true
description : DDO of the asset .
schema :
type : object
required :
- " @ context "
- created
- id
- publicKey
- authentication
... | required_attributes = [ '@context' , 'created' , 'id' , 'publicKey' , 'authentication' , 'proof' , 'service' ]
required_metadata_base_attributes = [ 'name' , 'dateCreated' , 'author' , 'license' , 'price' , 'encryptedFiles' , 'type' , 'checksum' ]
required_metadata_curation_attributes = [ 'rating' , 'numVotes' ]
assert... |
def _center_window ( self , result , window ) :
"""Center the result in the window .""" | if self . axis > result . ndim - 1 :
raise ValueError ( "Requested axis is larger then no. of argument " "dimensions" )
offset = _offset ( window , True )
if offset > 0 :
if isinstance ( result , ( ABCSeries , ABCDataFrame ) ) :
result = result . slice_shift ( - offset , axis = self . axis )
else :
... |
def _make_builder_configs ( ) :
"""Make built - in Librispeech BuilderConfigs .
Uses 4 text encodings ( plain text , bytes , subwords with 8k vocab , subwords
with 32k vocab ) crossed with the data subsets ( clean100 , clean360 , all ) .
Returns :
` list < tfds . audio . LibrispeechConfig > `""" | text_encoder_configs = [ None , tfds . features . text . TextEncoderConfig ( name = "bytes" , encoder = tfds . features . text . ByteTextEncoder ( ) ) , tfds . features . text . TextEncoderConfig ( name = "subwords8k" , encoder_cls = tfds . features . text . SubwordTextEncoder , vocab_size = 2 ** 13 ) , tfds . features... |
def do_run ( self , count = 1 ) :
'''Roll count dice , store results . Does all stats so might be slower
than specific doFoo methods . But , it is proly faster than running
each of those seperately to get same stats .
Sets the following properties :
- stats . bucket
- stats . sum
- stats . avr
: param... | if not self . roll . summable :
raise Exception ( 'Roll is not summable' )
h = dict ( )
total = 0
for roll in self . roll . x_rolls ( count ) :
total += roll
h [ roll ] = h . get ( roll , 0 ) + 1
self . _bucket = h
self . sum = total
self . avr = total / count |
def mksls ( src , dst = None ) :
'''Convert a preseed file to an SLS file''' | ps_opts = { }
with salt . utils . files . fopen ( src , 'r' ) as fh_ :
for line in fh_ :
line = salt . utils . stringutils . to_unicode ( line )
if line . startswith ( '#' ) :
continue
if not line . strip ( ) :
continue
comps = shlex . split ( line )
i... |
def get_role_id ( self , role_name , mount_point = 'approle' ) :
"""GET / auth / < mount _ point > / role / < role name > / role - id
: param role _ name :
: type role _ name :
: param mount _ point :
: type mount _ point :
: return :
: rtype :""" | url = '/v1/auth/{0}/role/{1}/role-id' . format ( mount_point , role_name )
return self . _adapter . get ( url ) . json ( ) [ 'data' ] [ 'role_id' ] |
def add_highlighted_fits ( self , evnet ) :
"""adds a new interpretation to each specimen highlighted in logger if multiple interpretations are highlighted of the same specimen only one new interpretation is added
@ param : event - > the wx . ButtonEvent that triggered this function""" | specimens = [ ]
next_i = self . logger . GetNextSelected ( - 1 )
if next_i == - 1 :
return
while next_i != - 1 :
fit , specimen = self . fit_list [ next_i ]
if specimen in specimens :
next_i = self . logger . GetNextSelected ( next_i )
continue
else :
specimens . append ( specime... |
def get_objective_bank_hierarchy_design_session ( self ) :
"""Gets the session designing objective bank hierarchies .
return : ( osid . learning . ObjectiveBankHierarchyDesignSession ) - an
` ` ObjectiveBankHierarchyDesignSession ` `
raise : OperationFailed - unable to complete request
raise : Unimplemented... | if not self . supports_objective_bank_hierarchy_design ( ) :
raise errors . Unimplemented ( )
# pylint : disable = no - member
return sessions . ObjectiveBankHierarchyDesignSession ( runtime = self . _runtime ) |
def _parse_uri ( uri_as_string ) :
"""Parse the given URI from a string .
Supported URI schemes are :
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
. s3 , s3a and s3n are treated the same way . s3u is s3 but without SSL .
Valid URI examples : :
* s3 : / / my _ bucket / my _... | if os . name == 'nt' : # urlsplit doesn ' t work on Windows - - it parses the drive as the scheme . . .
if '://' not in uri_as_string : # no protocol given = > assume a local file
uri_as_string = 'file://' + uri_as_string
parsed_uri = _my_urlsplit ( uri_as_string )
if parsed_uri . scheme == "hdfs" :
ret... |
def init ( device_id = None , random_seed = None ) :
"""Initialize Hebel .
This function creates a CUDA context , CUBLAS context and
initializes and seeds the pseudo - random number generator .
* * Parameters : * *
device _ id : integer , optional
The ID of the GPU device to use . If this is omitted , PyC... | if device_id is None :
random_seed = _os . environ . get ( 'CUDA_DEVICE' )
if random_seed is None :
random_seed = _os . environ . get ( 'RANDOM_SEED' )
global is_initialized
if not is_initialized :
is_initialized = True
global context
context . init_context ( device_id )
from pycuda import gpuar... |
def transform ( self , translation , theta , method = 'opencv' ) :
"""Create a new image by translating and rotating the current image .
Parameters
translation : : obj : ` numpy . ndarray ` of float
The XY translation vector .
theta : float
Rotation angle in radians , with positive meaning counter - clock... | # transform channels separately
color_im_tf = self . color . transform ( translation , theta , method = method )
depth_im_tf = self . depth . transform ( translation , theta , method = method )
# return combination of cropped data
return RgbdImage . from_color_and_depth ( color_im_tf , depth_im_tf ) |
def gen_signature ( priv_path , pub_path , sign_path , passphrase = None ) :
'''creates a signature for the given public - key with
the given private key and writes it to sign _ path''' | with salt . utils . files . fopen ( pub_path ) as fp_ :
mpub_64 = fp_ . read ( )
mpub_sig = sign_message ( priv_path , mpub_64 , passphrase )
mpub_sig_64 = binascii . b2a_base64 ( mpub_sig )
if os . path . isfile ( sign_path ) :
return False
log . trace ( 'Calculating signature for %s with %s' , os . path . bas... |
def is_valid ( self , fast = False ) :
"""Returns validation success or failure as boolean .
Optional fast parameter passed directly to validate ( ) .""" | try :
self . validate ( fast = fast )
except BagError :
return False
return True |
def rm_file_or_dir ( path , ignore_errors = True ) :
"""Helper function to clean a certain filepath
Parameters
path
Returns""" | if os . path . exists ( path ) :
if os . path . isdir ( path ) :
if os . path . islink ( path ) :
os . unlink ( path )
else :
shutil . rmtree ( path , ignore_errors = ignore_errors )
else :
if os . path . islink ( path ) :
os . unlink ( path )
... |
def file_to_md5 ( filename , block_size = 8192 ) :
"""Calculate the md5 hash of a file . Memory - friendly solution ,
it reads the file piece by piece . See stackoverflow . com / questions / 1131220/
: param filename : filename to convert
: param block _ size : size of block
: return : MD5 hash of file cont... | md5 = hashlib . md5 ( )
with open ( filename , 'rb' ) as f :
while True :
data = f . read ( block_size )
if not data :
break
md5 . update ( data )
return md5 . hexdigest ( ) |
def heater_level ( self , value ) :
"""Verifies that the heater _ level is between 0 and heater _ segments .
Can only be called when freshroastsr700 object is initialized
with ext _ sw _ heater _ drive = True . Will throw RoasterValueError
otherwise .""" | if self . _ext_sw_heater_drive :
if value not in range ( 0 , self . _heater_bangbang_segments + 1 ) :
raise exceptions . RoasterValueError
self . _heater_level . value = value
else :
raise exceptions . RoasterValueError |
def _description ( self ) :
"""A concise html explanation of this Action .""" | inst = self . timemachine . presently
if self . action_type == "dl" :
return "Deleted %s" % inst . content_type . name
elif self . action_type == "cr" :
return "Created %s" % inst . _object_type_html ( )
else :
return "Modified %s" % inst . _object_type_html ( ) |
def transformToNative ( self ) :
"""Transform this object into a custom VBase subclass .
transformToNative should always return a representation of this object .
It may do so by modifying self in place then returning self , or by
creating a new object .""" | if self . isNative or not self . behavior or not self . behavior . hasNative :
return self
else :
try :
return self . behavior . transformToNative ( self )
except Exception as e : # wrap errors in transformation in a ParseError
lineNumber = getattr ( self , 'lineNumber' , None )
if i... |
def _get_iscsi_settings_resource ( self , data ) :
"""Get the iscsi settings resoure .
: param data : Existing iscsi settings of the server .
: returns : headers , iscsi _ settings url and
iscsi settings as a dictionary .
: raises : IloCommandNotSupportedError , if resource is not found .
: raises : IloEr... | try :
iscsi_settings_uri = data [ 'links' ] [ 'Settings' ] [ 'href' ]
except KeyError :
msg = ( 'iscsi settings resource not found.' )
raise exception . IloCommandNotSupportedError ( msg )
status , headers , iscsi_settings = self . _rest_get ( iscsi_settings_uri )
if status != 200 :
msg = self . _get_ex... |
def post ( method , hmc , uri , uri_parms , body , logon_required , wait_for_completion ) :
"""Operation : Add Candidate Adapter Ports to an FCP Storage Group .""" | assert wait_for_completion is True
# async not supported yet
# The URI is a POST operation , so we need to construct the SG URI
storage_group_oid = uri_parms [ 0 ]
storage_group_uri = '/api/storage-groups/' + storage_group_oid
try :
storage_group = hmc . lookup_by_uri ( storage_group_uri )
except KeyError :
rai... |
def symlink_path ( self ) : # type : ( ) - > bytes
'''Get the path as a string of the symlink target of this Rock Ridge entry
( if this is a symlink ) .
Parameters :
None .
Returns :
Symlink path as a string .''' | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'Rock Ridge extension not yet initialized' )
if not self . is_symlink ( ) :
raise pycdlibexception . PyCdlibInvalidInput ( 'Entry is not a symlink!' )
outlist = [ ]
saved = b''
for rec in self . dr_entries . sl_records + self . ce_entr... |
def recipe_status ( backend ) :
"""Compare local recipe to remote recipe for the current recipe .""" | kitchen = DKCloudCommandRunner . which_kitchen_name ( )
if kitchen is None :
raise click . ClickException ( 'You are not in a Kitchen' )
recipe_dir = DKRecipeDisk . find_recipe_root_dir ( )
if recipe_dir is None :
raise click . ClickException ( 'You must be in a Recipe folder' )
recipe_name = DKRecipeDisk . fin... |
def error ( name = None , message = '' ) :
'''If name is None Then return empty dict
Otherwise raise an exception with _ _ name _ _ from name , message from message
CLI Example :
. . code - block : : bash
salt - wheel error
salt - wheel error . error name = " Exception " message = " This is an error . "''... | ret = { }
if name is not None :
salt . utils . error . raise_error ( name = name , message = message )
return ret |
def extend_schema_spec ( self ) -> None :
"""Injects the identity field""" | super ( ) . extend_schema_spec ( )
identity_field = { 'Name' : '_identity' , 'Type' : BtsType . STRING , 'Value' : 'identity' , ATTRIBUTE_INTERNAL : True }
if self . ATTRIBUTE_FIELDS in self . _spec :
self . _spec [ self . ATTRIBUTE_FIELDS ] . insert ( 0 , identity_field )
self . schema_loader . add_schema_spec... |
def _find_usage_ACLs ( self ) :
"""find usage for ACLs""" | # Network ACLs per VPC
acls = defaultdict ( int )
for acl in self . conn . describe_network_acls ( ) [ 'NetworkAcls' ] :
acls [ acl [ 'VpcId' ] ] += 1
# Rules per network ACL
self . limits [ 'Rules per network ACL' ] . _add_current_usage ( len ( acl [ 'Entries' ] ) , aws_type = 'AWS::EC2::NetworkAcl' , reso... |
def register ( self , event_type , callback , args = None , kwargs = None , details_filter = None , weak = False ) :
"""Register a callback to be called when event of a given type occurs .
Callback will be called with provided ` ` args ` ` and ` ` kwargs ` ` and
when event type occurs ( or on any event if ` ` e... | if not six . callable ( callback ) :
raise ValueError ( "Event callback must be callable" )
if details_filter is not None :
if not six . callable ( details_filter ) :
raise ValueError ( "Details filter must be callable" )
if not self . can_be_registered ( event_type ) :
raise ValueError ( "Disallowe... |
def zlib_decompress_to_string ( blob ) :
"""Decompress things to a string in a py2/3 safe fashion
> > > json _ str = ' { " test " : 1 } '
> > > blob = zlib _ compress ( json _ str )
> > > got _ str = zlib _ decompress _ to _ string ( blob )
> > > got _ str = = json _ str
True""" | if PY3K :
if isinstance ( blob , bytes ) :
decompressed = zlib . decompress ( blob )
else :
decompressed = zlib . decompress ( bytes ( blob , 'utf-8' ) )
return decompressed . decode ( 'utf-8' )
return zlib . decompress ( blob ) |
def republish_module_trigger ( plpy , td ) :
"""Trigger called from postgres database when republishing a module .
When a module is republished , the versions of the collections that it is
part of will need to be updated ( a minor update ) .
e . g . there is a collection c1 v2.1 , which contains module m1 v3 ... | # Is this an insert from legacy ? Legacy always supplies the version .
is_legacy_publication = td [ 'new' ] [ 'version' ] is not None
if not is_legacy_publication : # Bail out , because this trigger only applies to legacy publications .
return "OK"
plpy . log ( 'Trigger fired on %s' % ( td [ 'new' ] [ 'moduleid' ] ... |
def alloc ( self ) :
"""from _ mosquitto _ packet _ alloc .""" | byte = 0
remaining_bytes = bytearray ( 5 )
i = 0
remaining_length = self . remaining_length
self . payload = None
self . remaining_count = 0
loop_flag = True
# self . dump ( )
while loop_flag :
byte = remaining_length % 128
remaining_length = remaining_length / 128
if remaining_length > 0 :
byte = b... |
def file_pour ( filepath , block_size = 10240 , * args , ** kwargs ) :
"""Write physical files from entries .""" | def opener ( archive_res ) :
_LOGGER . debug ( "Opening from file (file_pour): %s" , filepath )
_archive_read_open_filename ( archive_res , filepath , block_size )
return _pour ( opener , * args , flags = 0 , ** kwargs ) |
def has_attribute ( self , name , alias = False ) :
"""Check if the entity contains the attribute * name *""" | prop_dict = merge_dicts ( self . __attributes__ , self . __fields__ , self . __relations__ )
if alias :
prop_dict . update ( { v . alias : v for v in prop_dict . values ( ) if v . alias is not None } )
return name in prop_dict |
def apply_host_template ( self , host_ids , start_roles ) :
"""Apply a host template identified by name on the specified hosts and
optionally start them .
@ param host _ ids : List of host ids .
@ param start _ roles : Whether to start the created roles or not .
@ return : An ApiCommand object .""" | return apply_host_template ( self . _get_resource_root ( ) , self . name , self . clusterRef . clusterName , host_ids , start_roles ) |
def process_loaded_configs ( self , values ) :
"""Takes the loaded config values ( from YAML files ) and performs the
following clean up steps :
1 . remove all value keys that are not uppercase
2 . resolve any keys with missing values
Note : resolving missing values does not fail fast , we will collect
al... | unresolved_value_keys = self . _process_config_values ( [ ] , values , [ ] )
if len ( unresolved_value_keys ) > 0 :
msg = "Unresolved values for: {}" . format ( unresolved_value_keys )
# Even though we will fail , there might be a situation when we want to
# do something with the list of missing values , so... |
def enable_all_cpu ( self ) :
'''Enable all offline cpus''' | for cpu in self . __get_ranges ( "offline" ) :
fpath = path . join ( "cpu%i" % cpu , "online" )
self . __write_cpu_file ( fpath , b"1" ) |
def __get_values ( self ) :
"""Gets values in this cell range as a tuple .
This is much more effective than reading cell values one by one .""" | array = self . _get_target ( ) . getDataArray ( )
return tuple ( itertools . chain . from_iterable ( array ) ) |
def getStartdatetime ( self ) :
"""Returns the date and starttime as datetime object
Parameters
None
Examples
> > > import pyedflib
> > > f = pyedflib . data . test _ generator ( )
> > > f . getStartdatetime ( )
datetime . datetime ( 2011 , 4 , 4 , 12 , 57 , 2)
> > > f . _ close ( )
> > > del f""" | return datetime ( self . startdate_year , self . startdate_month , self . startdate_day , self . starttime_hour , self . starttime_minute , self . starttime_second ) |
def render ( self , filename ) :
"""Perform initialization of render , set quality and size video attributes and then call template method that
is defined in child class .""" | self . elapsed_time = - time ( )
dpi = 100
fig = figure ( figsize = ( 16 , 9 ) , dpi = dpi )
with self . writer . saving ( fig , filename , dpi ) :
for frame_id in xrange ( self . frames + 1 ) :
self . renderFrame ( frame_id )
self . writer . grab_frame ( )
self . elapsed_time += time ( ) |
def get_learned_skills ( self , lang ) :
"""Return the learned skill objects sorted by the order they were learned
in .""" | skills = [ skill for skill in self . user_data . language_data [ lang ] [ 'skills' ] ]
self . _compute_dependency_order ( skills )
return [ skill for skill in sorted ( skills , key = lambda skill : skill [ 'dependency_order' ] ) if skill [ 'learned' ] ] |
def from_blaze ( expr , deltas = 'auto' , checkpoints = 'auto' , loader = None , resources = None , odo_kwargs = None , missing_values = None , domain = GENERIC , no_deltas_rule = 'warn' , no_checkpoints_rule = 'warn' ) :
"""Create a Pipeline API object from a blaze expression .
Parameters
expr : Expr
The bla... | if 'auto' in { deltas , checkpoints } :
invalid_nodes = tuple ( filter ( is_invalid_deltas_node , expr . _subterms ( ) ) )
if invalid_nodes :
raise TypeError ( 'expression with auto %s may only contain (%s) nodes,' " found: %s" % ( ' or ' . join ( [ 'deltas' ] if deltas is not None else [ ] + [ 'checkpo... |
def _remove_code ( site ) :
"""Delete project files
@ type site : Site""" | def handle_error ( function , path , excinfo ) :
click . secho ( 'Failed to remove path ({em}): {p}' . format ( em = excinfo . message , p = path ) , err = True , fg = 'red' )
if os . path . exists ( site . root ) :
shutil . rmtree ( site . root , onerror = handle_error ) |
def update_long ( self , ** kwargs ) :
"""Update the long optional arguments ( those with two leading ' - ' )
This method updates the short argument name for the specified function
arguments as stored in : attr : ` unfinished _ arguments `
Parameters
` ` * * kwargs ` `
Keywords must be keys in the : attr ... | for key , val in six . iteritems ( kwargs ) :
self . update_arg ( key , long = val ) |
def unicode_compatible ( cls ) :
"""Decorator for unicode compatible classes . Method ` ` _ _ unicode _ _ ` `
has to be implemented to work decorator as expected .""" | if PY3 :
cls . __str__ = cls . __unicode__
cls . __bytes__ = lambda self : self . __str__ ( ) . encode ( "utf-8" )
else :
cls . __str__ = lambda self : self . __unicode__ ( ) . encode ( "utf-8" )
return cls |
def sg_arg_def ( ** kwargs ) :
r"""Defines command line options
Args :
* * kwargs :
key : A name for the option .
value : Default value or a tuple of ( default value , description ) .
Returns :
None
For example ,
# Either of the following two lines will define ` - - n _ epoch ` command line argument... | for k , v in kwargs . items ( ) :
if type ( v ) is tuple or type ( v ) is list :
v , c = v [ 0 ] , v [ 1 ]
else :
c = k
if type ( v ) is str :
tf . app . flags . DEFINE_string ( k , v , c )
elif type ( v ) is int :
tf . app . flags . DEFINE_integer ( k , v , c )
elif ... |
def verify_geospatial_bounds ( self , ds ) :
"""Checks that the geospatial bounds is well formed OGC WKT""" | var = getattr ( ds , 'geospatial_bounds' , None )
check = var is not None
if not check :
return ratable_result ( False , "Global Attributes" , # grouped with Globals
[ "geospatial_bounds not present" ] )
try : # TODO : verify that WKT is valid given CRS ( defaults to EPSG : 4326
# in ACDD .
from_wkt ( ds . ... |
def get_item_representations ( self , features = None ) :
"""Get the latent representations for items given model and features .
Arguments
features : np . float32 csr _ matrix of shape [ n _ items , n _ item _ features ] , optional
Each row contains that item ' s weights over features .
An identity matrix w... | self . _check_initialized ( )
if features is None :
return self . item_biases , self . item_embeddings
features = sp . csr_matrix ( features , dtype = CYTHON_DTYPE )
return features * self . item_biases , features * self . item_embeddings |
def increase_route_count ( self , crawled_request ) :
"""Increase the count that determines how many times a URL of a certain route has been crawled .
Args :
crawled _ request ( : class : ` nyawc . http . Request ` ) : The request that possibly matches a route .""" | for route in self . __routing_options . routes :
if re . compile ( route ) . match ( crawled_request . url ) :
count_key = str ( route ) + crawled_request . method
if count_key in self . __routing_count . keys ( ) :
self . __routing_count [ count_key ] += 1
else :
sel... |
def get_property ( self , name ) :
"""get _ property ( property _ name : str ) - > object
Retrieves a property value .""" | if not hasattr ( self . props , name ) :
raise TypeError ( "Unknown property: %r" % name )
return getattr ( self . props , name ) |
def recv_filtered ( self , keycheck , tab_key , timeout = 30 , message = None ) :
'''Receive a filtered message , using the callable ` keycheck ` to filter received messages
for content .
` keycheck ` is expected to be a callable that takes a single parameter ( the decoded response
from chromium ) , and retur... | self . __check_open_socket ( tab_key )
# First , check if the message has already been received .
for idx in range ( len ( self . messages [ tab_key ] ) ) :
if keycheck ( self . messages [ tab_key ] [ idx ] ) :
return self . messages [ tab_key ] . pop ( idx )
timeout_at = time . time ( ) + timeout
while 1 :... |
def refcount ( self ) :
"""Number of references of an article .
Note : Requires the FULL view of the article .""" | refs = self . items . find ( 'bibrecord/tail/bibliography' , ns )
try :
return refs . attrib [ 'refcount' ]
except AttributeError : # refs is None
return None |
def accumulate ( self , buf ) :
'''add in some more bytes''' | bytes = array . array ( 'B' )
if isinstance ( buf , array . array ) :
bytes . extend ( buf )
else :
bytes . fromstring ( buf )
accum = self . crc
for b in bytes :
tmp = b ^ ( accum & 0xff )
tmp = ( tmp ^ ( tmp << 4 ) ) & 0xFF
accum = ( accum >> 8 ) ^ ( tmp << 8 ) ^ ( tmp << 3 ) ^ ( tmp >> 4 )
ac... |
def reset ( self ) :
"""Reset widget to original state .""" | self . filename = None
self . dataset = None
# about the recordings
self . idx_filename . setText ( 'Open Recordings...' )
self . idx_s_freq . setText ( '' )
self . idx_n_chan . setText ( '' )
self . idx_start_time . setText ( '' )
self . idx_end_time . setText ( '' )
# about the visualization
self . idx_scaling . setT... |
def address ( self , is_compressed = None ) :
"""Return the public address representation of this key , if available .""" | return self . _network . address . for_p2pkh ( self . hash160 ( is_compressed = is_compressed ) ) |
def ConsultarAjuste ( self , pto_emision = None , nro_orden = None , nro_contrato = None , coe = None , pdf = None ) :
"Consulta un ajuste de liquidación por No de orden o numero de contrato" | if nro_contrato :
ret = self . client . ajustePorContratoConsultar ( auth = { 'token' : self . Token , 'sign' : self . Sign , 'cuit' : self . Cuit , } , nroContrato = nro_contrato , )
ret = ret [ 'ajusteContratoReturn' ]
elif coe is None or pdf is None :
ret = self . client . ajusteXNroOrdenConsultar ( auth... |
def initial_digit_of_factorial ( num ) :
"""This Python function calculates the first digit of the factorial of a given input number .
Example :
initial _ digit _ of _ factorial ( 5 ) - - > 1
initial _ digit _ of _ factorial ( 10 ) - - > 3
initial _ digit _ of _ factorial ( 7 ) - - > 5
Args :
num : The ... | import math
fact_num = 1
# Calculation of factorial
for i in range ( 2 , num + 1 ) :
fact_num *= i
# Remove trailing zeros from the right side
while fact_num % 10 == 0 :
fact_num //= 10
# Get the first digit from the left side
while fact_num >= 10 :
fact_num /= 10
return math . floor ( fact_num ... |
def get_timeline ( self , auth_secret , max_cnt_tweets ) :
"""Get the general or user timeline .
If an empty authentication secret is given , this method returns the general timeline .
If an authentication secret is given and it is valid , this method returns the user timeline .
If an authentication secret is... | result = { pytwis_constants . ERROR_KEY : None }
if auth_secret == '' : # An empty authentication secret implies getting the general timeline .
timeline_key = pytwis_constants . GENERAL_TIMELINE_KEY
else : # Check if the user is logged in .
loggedin , userid = self . _is_loggedin ( auth_secret )
if not logg... |
def url ( value ) :
"""Validate a URL .
: param string value : The URL to validate
: returns : The URL if valid .
: raises : ValueError""" | if not url_regex . search ( value ) :
message = u"{0} is not a valid URL" . format ( value )
if url_regex . search ( 'http://' + value ) :
message += u". Did you mean: http://{0}" . format ( value )
raise ValueError ( message )
return value |
def predict ( self , x ) :
"""Predict values for a single data point or an RDD of points using
the model trained .
. . note : : In Python , predict cannot currently be used within an RDD
transformation or action .
Call predict directly on the RDD instead .""" | if isinstance ( x , RDD ) :
return self . call ( "predict" , x . map ( _convert_to_vector ) )
else :
return self . call ( "predict" , _convert_to_vector ( x ) ) |
def _get_draw_cache_key ( self , grid , key , drawn_rect , is_selected ) :
"""Returns key for the screen draw cache""" | row , col , tab = key
cell_attributes = grid . code_array . cell_attributes
zoomed_width = drawn_rect . width / self . zoom
zoomed_height = drawn_rect . height / self . zoom
# Button cells shall not be executed for preview
if grid . code_array . cell_attributes [ key ] [ "button_cell" ] :
cell_preview = repr ( grid... |
def read_namespaced_ingress_status ( self , name , namespace , ** kwargs ) : # noqa : E501
"""read _ namespaced _ ingress _ status # noqa : E501
read status of the specified Ingress # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . read_namespaced_ingress_status_with_http_info ( name , namespace , ** kwargs )
# noqa : E501
else :
( data ) = self . read_namespaced_ingress_status_with_http_info ( name , namespace , ** kwargs )
# noqa : E501
... |
def on_epoch_end ( self , pbar , epoch , last_metrics , ** kwargs ) :
"Put the various losses in the recorder and show a sample image ." | if not hasattr ( self , 'last_gen' ) or not self . show_img :
return
data = self . learn . data
img = self . last_gen [ 0 ]
norm = getattr ( data , 'norm' , False )
if norm and norm . keywords . get ( 'do_y' , False ) :
img = data . denorm ( img )
img = data . train_ds . y . reconstruct ( img )
self . imgs . ap... |
def create_subscription ( self , * , customer_id , credit_card_token , plan_code , quantity = None , installments = None , trial_days = None , immediate_payment = None , extra1 = None , extra2 = None , delivery_address = None , notify_url = None , recurring_bill_items = None ) :
"""Creating a new subscription of a ... | payload = { "quantity" : quantity , "installments" : installments , "trialDays" : trial_days , "immediatePayment" : immediate_payment , "extra1" : extra1 , "extra2" : extra2 , "customer" : { "id" : customer_id , "creditCards" : [ { "token" : credit_card_token } ] } , "plan" : { "planCode" : plan_code } , "deliveryAddre... |
def service ( container , name = None ) :
"""A decorator to register a service on a container .
For more information see : meth : ` Container . add _ service ` .""" | def register ( service ) :
container . add_service ( service , name )
return service
return register |
def desc ( t = None , reg = True ) :
"""Describe Class Dependency
: param reg : should we register this class as well
: param t : custom type as well
: return :""" | def decorated_fn ( cls ) :
if not inspect . isclass ( cls ) :
return NotImplemented ( 'For now we can only describe classes' )
name = t or camel_case_to_underscore ( cls . __name__ ) [ 0 ]
if reg :
di . injector . register ( name , cls )
else :
di . injector . describe ( name , c... |
def _try_decode_utf8_content ( self , content , content_type ) :
"""Generic function to decode content .
: param object content :
: return :""" | if not self . _auto_decode or not content :
return content
if content_type in self . _decode_cache :
return self . _decode_cache [ content_type ]
if isinstance ( content , dict ) :
content = self . _try_decode_dict ( content )
else :
content = try_utf8_decode ( content )
self . _decode_cache [ content_t... |
def make_cfglbls ( cfgdict_list , varied_dict ) :
"""Show only the text in labels that mater from the cfgdict""" | import textwrap
wrapper = textwrap . TextWrapper ( width = 50 )
cfglbl_list = [ ]
for cfgdict_ in cfgdict_list :
cfgdict = cfgdict_ . copy ( )
for key in six . iterkeys ( cfgdict_ ) :
try :
vals = varied_dict [ key ]
# Dont print label if not varied
if len ( vals ) ==... |
def symlinks ( self ) :
"""Known symlinks of the block device .""" | if not self . _P . Block . Symlinks :
return [ ]
return [ decode_ay ( path ) for path in self . _P . Block . Symlinks ] |
def remove_node_by_value ( self , value ) :
"""Delete all nodes in ` ` self . node _ list ` ` with the value ` ` value ` ` .
Args :
value ( Any ) : The value to find and delete owners of .
Returns : None
Example :
> > > from blur . markov . node import Node
> > > node _ 1 = Node ( ' One ' )
> > > grap... | self . node_list = [ node for node in self . node_list if node . value != value ]
# Remove links pointing to the deleted node
for node in self . node_list :
node . link_list = [ link for link in node . link_list if link . target . value != value ] |
def write_stats ( datadfs , outputfile , names = [ ] ) :
"""Call calculation functions and write stats file .
This function takes a list of DataFrames ,
and will create a column for each in the tab separated output .""" | if outputfile == 'stdout' :
output = sys . stdout
else :
output = open ( outputfile , 'wt' )
stats = [ Stats ( df ) for df in datadfs ]
features = { "Number of reads" : "number_of_reads" , "Total bases" : "number_of_bases" , "Total bases aligned" : "number_of_bases_aligned" , "Median read length" : "median_read... |
def add_field ( self , field ) :
"""Add the received field to the model .""" | self . remove_field ( field . name )
self . _fields [ field . name ] = field
if field . default is not None :
if six . callable ( field . default ) :
self . _default_callables [ field . key ] = field . default
else :
self . _defaults [ field . key ] = field . default |
def validate ( fname ) :
"""This function uses dciodvfy to generate
a list of warnings and errors discovered within
the DICOM file .
: param fname : Location and filename of DICOM file .""" | validation = { "errors" : [ ] , "warnings" : [ ] }
for line in _process ( fname ) :
kind , message = _determine ( line )
if kind in validation :
validation [ kind ] . append ( message )
return validation |
def _check_perms ( obj_name , obj_type , new_perms , cur_perms , access_mode , ret ) :
'''Helper function used by ` ` check _ perms ` ` for checking and setting Grant and
Deny permissions .
Args :
obj _ name ( str ) :
The name or full path to the object
obj _ type ( Optional [ str ] ) :
The type of obje... | access_mode = access_mode . lower ( )
changes = { }
for user in new_perms :
applies_to_text = ''
# Check that user exists :
try :
user_name = get_name ( principal = user )
except CommandExecutionError :
ret [ 'comment' ] . append ( '{0} Perms: User "{1}" missing from Target System' '' . ... |
def _get_image_workaround_seek ( self , idx ) :
"""Same as _ _ getitem _ _ but seek through the video beforehand
This is a workaround for an all - zero image returned by ` imageio ` .""" | warnings . warn ( "imageio workaround used!" )
cap = self . video_handle
mult = 50
for ii in range ( idx // mult ) :
cap . get_data ( ii * mult )
final = cap . get_data ( idx )
return final |
async def on_shutdown ( app ) :
"""app SHUTDOWN event handler""" | for method in app . get ( "close_methods" , [ ] ) :
logger . debug ( "Calling < %s >" , method )
if asyncio . iscoroutinefunction ( method ) :
await method ( )
else :
method ( ) |
def perform ( self ) :
"""This method converts payload into args and calls the ` ` perform ` `
method on the payload class .
Before calling ` ` perform ` ` , a ` ` before _ perform ` ` class method
is called , if it exists . It takes a dictionary as an argument ;
currently the only things stored on the dict... | payload_class_str = self . _payload [ "class" ]
payload_class = self . safe_str_to_class ( payload_class_str )
payload_class . resq = self . resq
args = self . _payload . get ( "args" )
metadata = dict ( args = args )
if self . enqueue_timestamp :
metadata [ "enqueue_timestamp" ] = self . enqueue_timestamp
before_p... |
def drop ( self , columns ) :
"""Drop 1 or more columns . Any column which does not exist in the DataFrame is skipped , i . e . not removed ,
without raising an exception .
Unlike Pandas ' drop , this is currently restricted to dropping columns .
Parameters
columns : str or list of str
Column name or list... | if isinstance ( columns , str ) :
new_data = OrderedDict ( )
if columns not in self . _gather_column_names ( ) :
raise KeyError ( 'Key {} not found' . format ( columns ) )
for column_name in self :
if column_name != columns :
new_data [ column_name ] = self . _data [ column_name ... |
def describe ( self , fields = None , ** kwargs ) :
""": param fields : dict where the keys are field names that should
be returned , and values should be set to True ( by default ,
all fields are returned )
: type fields : dict
: returns : Description of the analysis
: rtype : dict
Returns a hash with ... | describe_input = { }
if fields is not None :
describe_input [ 'fields' ] = fields
self . _desc = dxpy . api . analysis_describe ( self . _dxid , describe_input , ** kwargs )
return self . _desc |
def export ( outfile ) :
"""Export image anchore data to a JSON file .""" | if not nav :
sys . exit ( 1 )
ecode = 0
savelist = list ( )
for imageId in imagelist :
try :
record = { }
record [ 'image' ] = { }
record [ 'image' ] [ 'imageId' ] = imageId
record [ 'image' ] [ 'imagedata' ] = contexts [ 'anchore_db' ] . load_image_new ( imageId )
saveli... |
def usable_id ( cls , id ) :
"""Retrieve id from input which can be num or id .""" | try :
qry_id = int ( id )
except Exception :
qry_id = None
if not qry_id :
msg = 'unknown identifier %s' % id
cls . error ( msg )
return qry_id |
def colorize ( string , rgb = None , ansi = None , bg = None , ansi_bg = None , fd = 1 ) :
'''Returns the colored string to print on the terminal .
This function detects the terminal type and if it is supported and the
output is not going to a pipe or a file , then it will return the colored
string , otherwis... | # Reinitializes if fd used is different
if colorize . fd != fd :
colorize . init = False
colorize . fd = fd
# Checks if it is on a terminal , and if the terminal is recognized
if not colorize . init :
colorize . init = True
colorize . is_term = isatty ( fd )
if 'TERM' in environ :
if environ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.