signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def update ( self , index , doc_type , id , body = None , ** query_params ) :
"""Update a document with the body param or list of ids
` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / docs - update . html > ` _
: param index : the name of the index
: param doc _ type : the... | self . _es_parser . is_not_empty_params ( index , doc_type , id )
path = self . _es_parser . make_path ( index , doc_type , id , EsMethods . UPDATE )
result = yield self . _perform_request ( HttpMethod . POST , path , body = body , params = query_params )
returnValue ( result ) |
def using_transport ( self , transport = None , path = None , logs = True ) :
"""change used transport
: param transport : from where will be this image copied
: param path in filesystem
: param logs enable / disable
: return : self""" | if not transport :
return self
if self . transport == transport and self . path == path :
return self
path_required = [ SkopeoTransport . DIRECTORY , SkopeoTransport . DOCKER_ARCHIVE , SkopeoTransport . OCI ]
if transport in path_required :
if not path and logs :
logging . debug ( "path not provided... |
def tournament_selection ( population , fitnesses , num_competitors = 2 , diversity_weight = 0.0 ) :
"""Create a list of parents with tournament selection .
Args :
population : A list of solutions .
fitnesses : A list of fitness values corresponding to solutions in population .
num _ competitors : Number of... | # Optimization if diversity factor is disabled
if diversity_weight <= 0.0 :
fitness_pop = zip ( fitnesses , population )
# Zip for easy fitness comparison
# Get num _ competitors random chromosomes , then add best to result ,
# by taking max fitness and getting chromosome from tuple .
# Repeat until... |
def system_multicall ( self , call_list ) :
"""system . multicall ( [ { ' methodName ' : ' add ' , ' params ' : [ 2 , 2 ] } , . . . ] ) = > [ [ 4 ] , . . . ]
Allows the caller to package multiple XML - RPC calls into a single
request .
See http : / / www . xmlrpc . com / discuss / msgReader $ 1208""" | results = [ ]
for call in call_list :
method_name = call [ 'methodName' ]
params = call [ 'params' ]
try : # XXX A marshalling error in any response will fail the entire
# multicall . If someone cares they should fix this .
results . append ( [ self . _dispatch ( method_name , params ) ] )
e... |
def add_user_story_attribute ( self , name , ** attrs ) :
"""Add a new User Story attribute and return a
: class : ` UserStoryAttribute ` object .
: param name : name of the : class : ` UserStoryAttribute `
: param attrs : optional attributes for : class : ` UserStoryAttribute `""" | return UserStoryAttributes ( self . requester ) . create ( self . id , name , ** attrs ) |
def ransohoff_snap_off ( target , shape_factor = 2.0 , wavelength = 5e-6 , require_pair = False , surface_tension = 'pore.surface_tension' , contact_angle = 'pore.contact_angle' , diameter = 'throat.diameter' , vertices = 'throat.offset_vertices' , ** kwargs ) :
r"""Computes the capillary snap - off pressure assumi... | phase = target . project . find_phase ( target )
geometry = target . project . find_geometry ( target )
element , sigma , theta = _get_key_props ( phase = phase , diameter = diameter , surface_tension = surface_tension , contact_angle = contact_angle )
try :
all_verts = geometry [ vertices ]
# Work out whether ... |
def orig_py_exe ( exe ) : # pragma : no cover ( platform specific )
"""A - mvenv virtualenv made from a - mvirtualenv virtualenv installs
packages to the incorrect location . Attempt to find the _ original _ exe
and invoke ` - mvenv ` from there .
See :
- https : / / github . com / pre - commit / pre - comm... | try :
prefix_script = 'import sys; print(sys.real_prefix)'
_ , prefix , _ = cmd_output ( exe , '-c' , prefix_script )
prefix = prefix . strip ( )
except CalledProcessError : # not created from - mvirtualenv
return exe
if os . name == 'nt' :
expected = os . path . join ( prefix , 'python.exe' )
else ... |
def iteritems ( self ) :
"""Iterate over all header lines , including duplicate ones .""" | for key in self :
vals = _dict_getitem ( self , key )
for val in vals [ 1 : ] :
yield vals [ 0 ] , val |
def wash ( self , html_buffer , render_unallowed_tags = False , allowed_tag_whitelist = CFG_HTML_BUFFER_ALLOWED_TAG_WHITELIST , automatic_link_transformation = False , allowed_attribute_whitelist = CFG_HTML_BUFFER_ALLOWED_ATTRIBUTE_WHITELIST ) :
"""Wash HTML buffer , escaping XSS attacks .
@ param html _ buffer :... | self . reset ( )
self . result = ''
self . nb = 0
self . previous_nbs = [ ]
self . previous_type_lists = [ ]
self . url = ''
self . render_unallowed_tags = render_unallowed_tags
self . automatic_link_transformation = automatic_link_transformation
self . allowed_tag_whitelist = allowed_tag_whitelist
self . allowed_attri... |
def _find_cert_in_list ( cert , issuer , certificate_list , crl_issuer ) :
"""Looks for a cert in the list of revoked certificates
: param cert :
An asn1crypto . x509 . Certificate object of the cert being checked
: param issuer :
An asn1crypto . x509 . Certificate object of the cert issuer
: param certif... | revoked_certificates = certificate_list [ 'tbs_cert_list' ] [ 'revoked_certificates' ]
cert_serial = cert . serial_number
issuer_name = issuer . subject
known_extensions = set ( [ 'crl_reason' , 'hold_instruction_code' , 'invalidity_date' , 'certificate_issuer' ] )
last_issuer_name = crl_issuer . subject
for revoked_ce... |
def random_draw ( self , size = None ) :
"""Draw random samples of the hyperparameters .
Parameters
size : None , int or array - like , optional
The number / shape of samples to draw . If None , only one sample is
returned . Default is None .""" | return scipy . asarray ( [ numpy . random . uniform ( low = b [ 0 ] , high = b [ 1 ] , size = size ) for b in self . bounds ] ) |
def _create_sbatch ( self , ostr ) :
"""Write sbatch template to output stream
: param ostr : opened file to write to""" | properties = dict ( sbatch_arguments = self . sbatch_args , hpcbench_command = self . hpcbench_cmd )
try :
self . sbatch_template . stream ( ** properties ) . dump ( ostr )
except jinja2 . exceptions . UndefinedError :
self . logger . error ( 'Error while generating SBATCH template:' )
self . logger . error... |
def listen_on_socket ( self , socket_name = None ) :
"""Listen for clients on a Unix socket .
Returns the socket name .""" | def connection_cb ( pipe_connection ) : # We have to create a new ` context ` , because this will be the scope for
# a new prompt _ toolkit . Application to become active .
with context ( ) :
connection = ServerConnection ( self , pipe_connection )
self . connections . append ( connection )
self . socke... |
def init_widget ( self ) :
"""Set the listeners""" | w = self . dialog
# Listen for events
w . setOnDismissListener ( w . getId ( ) )
w . onDismiss . connect ( self . on_dismiss )
w . setOnCancelListener ( w . getId ( ) )
w . onCancel . connect ( self . on_cancel )
super ( AndroidDialog , self ) . init_widget ( ) |
def _lock ( self , lock_type = 'update' , failhard = False ) :
'''Place a lock file if ( and only if ) it does not already exist .''' | try :
fh_ = os . open ( self . _get_lock_file ( lock_type ) , os . O_CREAT | os . O_EXCL | os . O_WRONLY )
with os . fdopen ( fh_ , 'wb' ) : # Write the lock file and close the filehandle
os . write ( fh_ , salt . utils . stringutils . to_bytes ( six . text_type ( os . getpid ( ) ) ) )
except ( OSError ... |
def index_transcriptome ( gtf_file , ref_file , data ) :
"""use a GTF file and a reference FASTA file to index the transcriptome""" | gtf_fasta = gtf . gtf_to_fasta ( gtf_file , ref_file )
return build_bwa_index ( gtf_fasta , data ) |
def get_all_artifacts_per_task_id ( chain , upstream_artifacts ) :
"""Return every artifact to download , including the Chain Of Trust Artifacts .
Args :
chain ( ChainOfTrust ) : the chain of trust object
upstream _ artifacts : the list of upstream artifact definitions
Returns :
dict : sorted list of path... | all_artifacts_per_task_id = { }
for link in chain . links : # Download task - graph . json for decision + action task cot verification
if link . task_type in PARENT_TASK_TYPES :
add_enumerable_item_to_dict ( dict_ = all_artifacts_per_task_id , key = link . task_id , item = 'public/task-graph.json' )
# D... |
def ParseCookieRow ( self , parser_mediator , query , row , ** unused_kwargs ) :
"""Parses a row from the database .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
query ( str ) : query that created the row .
row ( sql... | query_hash = hash ( query )
cookie_name = self . _GetRowValue ( query_hash , row , 'name' )
cookie_value = self . _GetRowValue ( query_hash , row , 'value' )
path = self . _GetRowValue ( query_hash , row , 'path' )
hostname = self . _GetRowValue ( query_hash , row , 'domain' )
if hostname . startswith ( '.' ) :
hos... |
def print ( self , format = TEXT , output = sys . stdout , ** kwargs ) :
"""Print the object in a file or on standard output by default .
Args :
format ( str ) : output format ( csv , json or text ) .
output ( file ) :
descriptor to an opened file ( default to standard output ) .
* * kwargs ( ) : addition... | if format is None :
format = TEXT
if format == TEXT :
print ( self . _to_text ( ** kwargs ) , file = output )
elif format == CSV :
print ( self . _to_csv ( ** kwargs ) , file = output )
elif format == JSON :
print ( self . _to_json ( ** kwargs ) , file = output ) |
def sendline ( command , method = 'cli_show_ascii' , ** kwargs ) :
'''Send arbitray commands to the NX - OS device .
command
The command to be sent .
method :
` ` cli _ show _ ascii ` ` : Return raw test or unstructured output .
` ` cli _ show ` ` : Return structured output .
` ` cli _ conf ` ` : Send c... | smethods = [ 'cli_show_ascii' , 'cli_show' , 'cli_conf' ]
if method not in smethods :
msg = """
INPUT ERROR: Second argument 'method' must be one of {0}
Value passed: {1}
Hint: White space separated commands should be wrapped by double quotes
""" . format ( smethods , method )
re... |
def posterior_step ( logposts , dim ) :
"""Finds the last time a chain made a jump > dim / 2.
Parameters
logposts : array
1D array of values that are proportional to the log posterior values .
dim : int
The dimension of the parameter space .
Returns
int
The index of the last time the logpost made a ... | if logposts . ndim > 1 :
raise ValueError ( "logposts must be a 1D array" )
criteria = dim / 2.
dp = numpy . diff ( logposts )
indices = numpy . where ( dp >= criteria ) [ 0 ]
if indices . size > 0 :
idx = indices [ - 1 ] + 1
else :
idx = 0
return idx |
def try_fields ( cls , * names ) -> t . Optional [ t . Any ] :
"""Return first existing of given class field names .""" | for name in names :
if hasattr ( cls , name ) :
return getattr ( cls , name )
raise AttributeError ( ( cls , names ) ) |
def parse_type ( string , capture_strings , settings ) :
"""Gets variable type , kind , length , and / or derived - type attributes from a
variable declaration .""" | typestr = ''
for vtype in settings [ 'extra_vartypes' ] :
typestr = typestr + '|' + vtype
var_type_re = re . compile ( VAR_TYPE_STRING + typestr , re . IGNORECASE )
match = var_type_re . match ( string )
if not match :
raise Exception ( "Invalid variable declaration: {}" . format ( string ) )
vartype = match . ... |
def runGetInfo ( self , request ) :
"""Returns information about the service including protocol version .""" | return protocol . toJson ( protocol . GetInfoResponse ( protocol_version = protocol . version ) ) |
def _max_form ( f , colname ) :
"""Assumes dataframe with hierarchical columns with first index equal to the
use and second index equal to the attribute .
e . g . f . columns equal to : :
mixedoffice building _ cost
building _ revenue
building _ size
max _ profit
max _ profit _ far
total _ cost
in... | df = f . stack ( level = 0 ) [ [ colname ] ] . stack ( ) . unstack ( level = 1 ) . reset_index ( level = 1 , drop = True )
return df . idxmax ( axis = 1 ) |
def get ( self , id , ** kwargs ) :
"""Retrieve a single object .
Args :
id ( int or str ) : ID of the object to retrieve
lazy ( bool ) : If True , don ' t request the server , but create a
shallow object giving access to the managers . This is
useful if you want to avoid useless calls to the API .
* * ... | obj = super ( ProjectServiceManager , self ) . get ( id , ** kwargs )
obj . id = id
return obj |
def _collapse_address_list_recursive ( addresses ) :
"""Loops through the addresses , collapsing concurrent netblocks .
Example :
ip1 = IPv4Network ( ' 1.1.0.0/24 ' )
ip2 = IPv4Network ( ' 1.1.1.0/24 ' )
ip3 = IPv4Network ( ' 1.1.2.0/24 ' )
ip4 = IPv4Network ( ' 1.1.3.0/24 ' )
ip5 = IPv4Network ( ' 1.1.... | ret_array = [ ]
optimized = False
for cur_addr in addresses :
if not ret_array :
ret_array . append ( cur_addr )
continue
if cur_addr in ret_array [ - 1 ] :
optimized = True
elif cur_addr == ret_array [ - 1 ] . supernet ( ) . subnet ( ) [ 1 ] :
ret_array . append ( ret_array ... |
def _set_cos_traffic_class ( self , v , load = False ) :
"""Setter method for cos _ traffic _ class , mapped from YANG variable / qos / map / cos _ traffic _ class ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ cos _ traffic _ class is considered as a private ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "name" , cos_traffic_class . cos_traffic_class , yang_name = "cos-traffic-class" , rest_name = "cos-traffic-class" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_hel... |
def encode ( self ) :
"""Encodes this IE and returns the resulting bytes""" | result = bytearray ( )
result . append ( self . id )
result . append ( self . dataLength )
result . extend ( self . data )
return result |
def pretty_str ( self , indent = 0 ) :
"""Return a human - readable string representation of this object .
Kwargs :
indent ( int ) : The amount of spaces to use as indentation .""" | indent = ' ' * indent
values = '{{{}}}' . format ( ', ' . join ( map ( pretty_str , self . value ) ) )
if self . parenthesis :
return '{}({})' . format ( indent , values )
return '{}{}' . format ( indent , values ) |
async def update_data_status ( self , ** kwargs ) :
"""Update ( PATCH ) Data object .
: param kwargs : The dictionary of
: class : ` ~ resolwe . flow . models . Data ` attributes to be changed .""" | await self . _send_manager_command ( ExecutorProtocol . UPDATE , extra_fields = { ExecutorProtocol . UPDATE_CHANGESET : kwargs } ) |
def project_geometry ( geometry , source , target ) :
"""Projects a shapely geometry object from the source to the target projection .""" | project = partial ( pyproj . transform , source , target )
return transform ( project , geometry ) |
def modify_schema ( self , field_schema ) :
"""Modify field schema .""" | field_schema [ 'maximum' ] = self . maximum_value
if self . exclusive :
field_schema [ 'exclusiveMaximum' ] = True |
def dispatch ( self , tree ) :
"""Dispatcher function , dispatching tree type T to method _ T .""" | # display omp directive in python dump
for omp in metadata . get ( tree , openmp . OMPDirective ) :
deps = list ( )
for dep in omp . deps :
old_file = self . f
self . f = io . StringIO ( )
self . dispatch ( dep )
deps . append ( self . f . getvalue ( ) )
self . f = old_fi... |
def extract_endpoints ( api_module ) :
"""Return the endpoints from an API implementation module .
The results returned by this are used to populate your HTTP layer ' s
route handler , as well as by the documentation generator .""" | if not hasattr ( api_module , 'endpoints' ) :
raise ValueError ( ( "pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!" ) )
endpoints = api_module . endpoints
if isinstance ( endpoints , types . ModuleType ) :
classes = [ v for ( k , v ) in inspect . get... |
def is_resource_class_terminal_attribute ( rc , attr_name ) :
"""Checks if the given attribute name is a terminal attribute of the given
registered resource .""" | attr = get_resource_class_attribute ( rc , attr_name )
return attr . kind == RESOURCE_ATTRIBUTE_KINDS . TERMINAL |
def convert_timestamp ( timestamp ) :
"""Converts bokehJS timestamp to datetime64.""" | datetime = dt . datetime . utcfromtimestamp ( timestamp / 1000. )
return np . datetime64 ( datetime . replace ( tzinfo = None ) ) |
def _sorter ( generated ) :
"""Return a list of paths sorted by dirname & basename .""" | pairs = [ ( os . path . dirname ( f ) , os . path . basename ( f ) ) for f in set ( list ( generated ) ) ]
pairs . sort ( )
return [ os . path . join ( pair [ 0 ] , pair [ 1 ] ) for pair in pairs ] |
def construct_tree ( index ) :
"""Construct tree representation of the pkgs from the index .
The keys of the dict representing the tree will be objects of type
DistPackage and the values will be list of ReqPackage objects .
: param dict index : dist index ie . index of pkgs by their keys
: returns : tree of... | return dict ( ( p , [ ReqPackage ( r , index . get ( r . key ) ) for r in p . requires ( ) ] ) for p in index . values ( ) ) |
def update_resource_fields ( self , data , data_to_add ) :
"""Update resource data with new fields .
Args :
data : resource data
data _ to _ update : dict of data to update resource data
Returnes :
Returnes dict""" | for key , value in data_to_add . items ( ) :
if not data . get ( key ) :
data [ key ] = value
return data |
def log_request ( self , handler : web . RequestHandler ) -> None :
"""Handle access log .""" | if 'log_function' in self . settings :
self . settings [ 'log_function' ] ( handler )
return
status = handler . get_status ( )
if status < 400 :
log_method = logger . info
elif status < 500 :
log_method = logger . warning
else :
log_method = logger . error
request_time = 1000.0 * handler . request .... |
def connect ( self , address , token = None ) :
"""Connect the underlying websocket to the address ,
send a handshake and optionally a token packet .
Returns ` True ` if connected , ` False ` if the connection failed .
: param address : string , ` IP : PORT `
: param token : unique token , required by offic... | if self . connected :
self . subscriber . on_connect_error ( 'Already connected to "%s"' % self . address )
return False
self . address = address
self . server_token = token
self . ingame = False
self . ws . settimeout ( 1 )
self . ws . connect ( 'ws://%s' % self . address , origin = 'http://agar.io' )
if not s... |
def login ( self ) -> bool :
"""Return True if log in request succeeds""" | user_check = isinstance ( self . username , str ) and len ( self . username ) > 0
pass_check = isinstance ( self . password , str ) and len ( self . password ) > 0
if user_check and pass_check :
response , _ = helpers . call_api ( '/cloud/v1/user/login' , 'post' , json = helpers . req_body ( self , 'login' ) )
... |
def _get ( cls , resource_id , parent_id , grandparent_id ) :
"""" Retrieves the required resource .""" | client = cls . _get_client ( )
endpoint = cls . _endpoint . format ( resource_id = resource_id or "" , parent_id = parent_id or "" , grandparent_id = grandparent_id or "" )
raw_data = client . get_resource ( endpoint )
raw_data [ "parentResourceID" ] = parent_id
raw_data [ "grandParentResourceID" ] = grandparent_id
ret... |
def remove_entity ( self , entity , sub_entity_kind = None ) :
"""Remove an entity , or sub - entity group to this EntityGroup .
: type entity : Entity
: param entity : The entity to remove .
: type sub _ entity _ kind : Optional EntityKind
: param sub _ entity _ kind : If a sub _ entity _ kind is given , a... | EntityGroupMembership . objects . get ( entity_group = self , entity = entity , sub_entity_kind = sub_entity_kind , ) . delete ( ) |
def next ( self ) :
"""Where to redirect after authorization""" | next = request . args . get ( 'next' )
if next is None :
params = self . default_redirect_params
next = url_for ( self . default_redirect_endpoint , ** params )
return next |
def __find_handler_factories ( self ) :
"""Finds all registered handler factories and stores them""" | # Get the references
svc_refs = self . __context . get_all_service_references ( handlers_const . SERVICE_IPOPO_HANDLER_FACTORY )
if svc_refs :
for svc_ref in svc_refs : # Store each handler factory
self . __add_handler_factory ( svc_ref ) |
def put ( self , local , remote = None , preserve_mode = True ) :
"""Upload a file from the local filesystem to the current connection .
: param local :
Local path of file to upload , or a file - like object .
* * If a string is given * * , it should be a path to a local ( regular )
file ( not a directory )... | if not local :
raise ValueError ( "Local path must not be empty!" )
is_file_like = hasattr ( local , "write" ) and callable ( local . write )
# Massage remote path
orig_remote = remote
if is_file_like :
local_base = getattr ( local , "name" , None )
else :
local_base = os . path . basename ( local )
if not ... |
def update ( self , index , id , doc_type = "_doc" , body = None , params = None ) :
"""Update a document based on a script or partial data provided .
` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / docs - update . html > ` _
: arg index : The name of the index
: arg id ... | for param in ( index , id ) :
if param in SKIP_IN_PATH :
raise ValueError ( "Empty value passed for a required argument." )
return self . transport . perform_request ( "POST" , _make_path ( index , doc_type , id , "_update" ) , params = params , body = body ) |
def process_raw_data ( cls , raw_data ) :
"""Create a new model using raw API response .""" | properties = raw_data . get ( "properties" , { } )
bgp_peers = [ ]
for raw_content in properties . get ( "bgpPeers" , [ ] ) :
raw_content [ "parentResourceID" ] = raw_data [ "resourceId" ]
raw_content [ "grandParentResourceID" ] = raw_data [ "parentResourceID" ]
bgp_peers . append ( BGPPeers . from_raw_data... |
def set_content ( self , data ) :
"""handle the content from the data
: param data : contains the data from the provider
: type data : dict
: rtype : string""" | content = self . _get_content ( data , 'content' )
if content == '' :
content = self . _get_content ( data , 'summary_detail' )
if content == '' :
if data . get ( 'description' ) :
content = data . get ( 'description' )
return content |
def _tile_images ( imgs , tile_shape , concatenated_image ) :
"""Concatenate images whose sizes are same .
@ param imgs : image list which should be concatenated
@ param tile _ shape : shape for which images should be concatenated
@ param concatenated _ image : returned image .
if it is None , new image wil... | y_num , x_num = tile_shape
one_width = imgs [ 0 ] . shape [ 1 ]
one_height = imgs [ 0 ] . shape [ 0 ]
if concatenated_image is None :
if len ( imgs [ 0 ] . shape ) == 3 :
n_channels = imgs [ 0 ] . shape [ 2 ]
assert all ( im . shape [ 2 ] == n_channels for im in imgs )
concatenated_image = n... |
def minify_print ( ast , obfuscate = False , obfuscate_globals = False , shadow_funcname = False , drop_semi = False ) :
"""Simple minify print function ; returns a string rendering of an input
AST of an ES5 program
Arguments
ast
The AST to minify print
obfuscate
If True , obfuscate identifiers nested i... | return '' . join ( chunk . text for chunk in minify_printer ( obfuscate , obfuscate_globals , shadow_funcname , drop_semi ) ( ast ) ) |
def get ( self , node = None ) :
"""Run basic healthchecks against the current node , or against a given
node .
Example response :
> { " status " : " ok " }
> { " status " : " failed " , " reason " : " string " }
: param node : Node name
: raises ApiError : Raises if the remote server encountered an err... | if not node :
return self . http_client . get ( HEALTHCHECKS )
return self . http_client . get ( HEALTHCHECKS_NODE % node ) |
def is_file ( cls , file ) :
'''Return whether the file is likely CSS .''' | peeked_data = wpull . string . printable_bytes ( wpull . util . peek_file ( file ) ) . lower ( )
if b'<html' in peeked_data :
return VeryFalse
if re . search ( br'@import |color:|background[a-z-]*:|font[a-z-]*:' , peeked_data ) :
return True |
def codes2unicode ( codes , composed = True ) :
'''Convert Hanyang - PUA code iterable to Syllable - Initial - Peak - Final
encoded unicode string .
: param codes :
an iterable of Hanyang - PUA code
: param composed :
the result should be composed as much as possible ( default True )
: return : Syllable... | pua = u'' . join ( unichr ( code ) for code in codes )
return translate ( pua , composed = composed ) |
def escape_identifier ( text , reg = KWD_RE ) :
"""Escape partial C identifiers so they can be used as
attributes / arguments""" | # see http : / / docs . python . org / reference / lexical _ analysis . html # identifiers
if not text :
return "_"
if text [ 0 ] . isdigit ( ) :
text = "_" + text
return reg . sub ( r"\1_" , text ) |
def _draw_polygons ( self , feature , bg , colour , extent , polygons , xo , yo ) :
"""Draw a set of polygons from a vector tile .""" | coords = [ ]
for polygon in polygons :
coords . append ( [ self . _scale_coords ( x , y , extent , xo , yo ) for x , y in polygon ] )
# Polygons are expensive to draw and the buildings layer is huge - so we convert to
# lines in order to process updates fast enough to animate .
if "type" in feature [ "properties" ]... |
def copy_traj_attributes ( target , origin , start ) :
"""Inserts certain attributes of origin into target
: param target : target trajectory object
: param origin : origin trajectory object
: param start : : py : obj : ` origin ` attributes will be inserted in : py : obj : ` target ` starting at this index
... | # The list of copied attributes can be extended here with time
# Or perhaps ask the mdtraj guys to implement something similar ?
stop = start + origin . n_frames
target . xyz [ start : stop ] = origin . xyz
target . unitcell_lengths [ start : stop ] = origin . unitcell_lengths
target . unitcell_angles [ start : stop ] ... |
def exists ( self , queue_name , timeout = None ) :
'''Returns a boolean indicating whether the queue exists .
: param str queue _ name :
The name of queue to check for existence .
: param int timeout :
The server timeout , expressed in seconds .
: return : A boolean indicating whether the queue exists . ... | try :
self . get_queue_metadata ( queue_name , timeout = timeout )
return True
except AzureHttpError as ex :
_dont_fail_not_exist ( ex )
return False |
def when_starts ( self , timeformat = 'unix' ) :
"""Returns the GMT time of the start of the forecast coverage , which is
the time of the most ancient * Weather * item in the forecast
: param timeformat : the format for the time value . May be :
' * unix * ' ( default ) for UNIX time
' * iso * ' for ISO8601... | start_coverage = min ( [ item . get_reference_time ( ) for item in self . _forecast ] )
return timeformatutils . timeformat ( start_coverage , timeformat ) |
def enable ( step : 'projects.ProjectStep' ) :
"""Create a print equivalent function that also writes the output to the
project page . The write _ through is enabled so that the TextIOWrapper
immediately writes all of its input data directly to the underlying
BytesIO buffer . This is needed so that we can saf... | # Prevent anything unusual from causing buffer issues
restore_default_configuration ( )
stdout_interceptor = RedirectBuffer ( sys . stdout )
sys . stdout = stdout_interceptor
step . report . stdout_interceptor = stdout_interceptor
stderr_interceptor = RedirectBuffer ( sys . stderr )
sys . stderr = stderr_interceptor
st... |
def normalize_type ( self , names ) :
"""Decide if this param is an arg or a kwarg and set appropriate internal flags""" | self . name = names [ 0 ]
self . is_kwarg = False
self . is_arg = False
self . names = [ ]
try : # http : / / stackoverflow . com / a / 16488383/5006 uses ask forgiveness because
# of py2/3 differences of integer check
self . index = int ( self . name )
self . name = ""
self . is_arg = True
except ValueErro... |
def t_INITIAL_preproc_NEWLINE ( self , t ) :
r'\ r ? \ n' | t . lexer . lineno += 1
t . lexer . begin ( 'INITIAL' )
return t |
def assert_on_branch ( branch_name ) : # type : ( str ) - > None
"""Print error and exit if * branch _ name * is not the current branch .
Args :
branch _ name ( str ) :
The supposed name of the current branch .""" | branch = git . current_branch ( refresh = True )
if branch . name != branch_name :
if context . get ( 'pretend' , False ) :
log . info ( "Would assert that you're on a <33>{}<32> branch" , branch_name )
else :
log . err ( "You're not on a <33>{}<31> branch!" , branch_name )
sys . exit ( ... |
def create_table_from_object ( self , obj ) :
'''Create a table from the object .
NOTE : This method doesn ' t stores anything .
: param obj :
: return :''' | get_type = lambda item : str ( type ( item ) ) . split ( "'" ) [ 1 ]
if not os . path . exists ( os . path . join ( self . db_path , obj . _TABLE ) ) :
with gzip . open ( os . path . join ( self . db_path , obj . _TABLE ) , 'wb' ) as table_file :
csv . writer ( table_file ) . writerow ( [ '{col}:{type}' . f... |
def on_change_categ ( self ) :
'''When you change categ _ id it check checkin and checkout are
filled or not if not then raise warning
@ param self : object pointer''' | hotel_room_obj = self . env [ 'hotel.room' ]
hotel_room_ids = hotel_room_obj . search ( [ ( 'categ_id' , '=' , self . categ_id . id ) ] )
room_ids = [ ]
if not self . line_id . checkin :
raise ValidationError ( _ ( 'Before choosing a room,\n You have to \
select a Check in date ... |
def update ( self , func , ** kw ) :
"Update the signature of func with the data in self" | func . __name__ = self . name
func . __doc__ = getattr ( self , 'doc' , None )
func . __dict__ = getattr ( self , 'dict' , { } )
func . __defaults__ = getattr ( self , 'defaults' , ( ) )
func . __kwdefaults__ = getattr ( self , 'kwonlydefaults' , None )
func . __annotations__ = getattr ( self , 'annotations' , None )
c... |
def iterdata ( self , start , end = None , forward = True , condition = None ) :
"""Perform a depth - first walk of the graph ( as ` ` iterdfs ` ` )
and yield the item data of every node where condition matches . The
condition callback is only called when node _ data is not None .""" | visited , stack = set ( [ start ] ) , deque ( [ start ] )
if forward :
get_edges = self . out_edges
get_next = self . tail
else :
get_edges = self . inc_edges
get_next = self . head
get_data = self . node_data
while stack :
curr_node = stack . pop ( )
curr_data = get_data ( curr_node )
if cu... |
def carmichael_of_factorized ( f_list ) :
"""Return the Carmichael function of a number that is
represented as a list of ( prime , exponent ) pairs .""" | if len ( f_list ) < 1 :
return 1
result = carmichael_of_ppower ( f_list [ 0 ] )
for i in range ( 1 , len ( f_list ) ) :
result = lcm ( result , carmichael_of_ppower ( f_list [ i ] ) )
return result |
def get_snapshot ( name , config_path = _DEFAULT_CONFIG_PATH , with_packages = False ) :
'''Get detailed information about a snapshot .
: param str name : The name of the snapshot given during snapshot creation .
: param str config _ path : The path to the configuration file for the aptly instance .
: param b... | _validate_config ( config_path )
sources = list ( )
cmd = [ 'snapshot' , 'show' , '-config={}' . format ( config_path ) , '-with-packages={}' . format ( str ( with_packages ) . lower ( ) ) , name ]
cmd_ret = _cmd_run ( cmd )
ret = _parse_show_output ( cmd_ret = cmd_ret )
if ret :
log . debug ( 'Found shapshot: %s' ... |
def send_mini_program_page ( self , user_id , miniprogrampage , account = None ) :
"""发送小程序卡片 ( 要求小程序与公众号已关联 )
详情请参参考
https : / / mp . weixin . qq . com / wiki ? t = resource / res _ main & id = mp1421140547
: param user _ id : 用户 ID openid
: param miniprogrampage : 小程序卡片信息
: param account : 可选 , 客服账号
:... | data = { 'touser' : user_id , 'msgtype' : 'miniprogrampage' , 'miniprogrampage' : miniprogrampage }
return self . _send_custom_message ( data , account = account ) |
def add_textbox ( self , id_ , name , x , y , cx , cy ) :
"""Append a newly - created textbox ` ` < p : sp > ` ` shape having the specified
position and size .""" | sp = CT_Shape . new_textbox_sp ( id_ , name , x , y , cx , cy )
self . insert_element_before ( sp , 'p:extLst' )
return sp |
def load_dataframe ( mhc_class = None , # 1 , 2 , or None for neither
hla = None , exclude_hla = None , human_only = False , peptide_length = None , assay_method = None , assay_group = None , only_standard_amino_acids = True , reduced_alphabet = None , # 20 letter AA strings - > simpler alphabet
warn_bad_lines = True ,... | df = pd . read_csv ( local_path ( ) , header = [ 0 , 1 ] , skipinitialspace = True , nrows = nrows , low_memory = False , error_bad_lines = False , encoding = "latin-1" , warn_bad_lines = warn_bad_lines )
# Sometimes the IEDB seems to put in an extra comma in the
# header line , which creates an unnamed column of NaNs ... |
def _do_merge ( self , f , merge_strategy , add_duplicate = False ) :
"""Different merge strategies upon name conflicts .
" error " :
Raise error
" warning "
Log a warning
" merge " :
Combine old and new attributes - - but only if everything else
matches ; otherwise error . This can be slow , but is t... | if merge_strategy == 'error' :
raise ValueError ( "Duplicate ID {0.id}" . format ( f ) )
if merge_strategy == 'warning' :
logger . warning ( "Duplicate lines in file for id '{0.id}'; " "ignoring all but the first" . format ( f ) )
return None , merge_strategy
elif merge_strategy == 'replace' :
return f ... |
def write_option ( ** kwargs ) :
"""Create a write option for write operations .
Write operations include : meth : ` ~ . DocumentReference . set ` ,
: meth : ` ~ . DocumentReference . update ` and
: meth : ` ~ . DocumentReference . delete ` .
One of the following keyword arguments must be provided :
* ` `... | if len ( kwargs ) != 1 :
raise TypeError ( _BAD_OPTION_ERR )
name , value = kwargs . popitem ( )
if name == "last_update_time" :
return _helpers . LastUpdateOption ( value )
elif name == "exists" :
return _helpers . ExistsOption ( value )
else :
extra = "{!r} was provided" . format ( name )
raise Ty... |
def _sendmsg ( self , method , url , headers ) :
'''发送消息''' | msg = '%s %s %s' % ( method , url , RTSP_VERSION )
headers [ 'User-Agent' ] = DEFAULT_USERAGENT
cseq = self . _next_seq ( )
self . _cseq_map [ cseq ] = method
headers [ 'CSeq' ] = str ( cseq )
if self . _session_id :
headers [ 'Session' ] = self . _session_id
for ( k , v ) in headers . items ( ) :
msg += LINE_S... |
def hincrby ( self , hashkey , attribute , increment = 1 ) :
"""Emulate hincrby .""" | return self . _hincrby ( hashkey , attribute , 'HINCRBY' , long , increment ) |
def execute ( self ) :
"""Execute the PEX .
This function makes assumptions that it is the last function called by
the interpreter .""" | teardown_verbosity = self . _vars . PEX_TEARDOWN_VERBOSE
try :
pex_inherit_path = self . _vars . PEX_INHERIT_PATH
if pex_inherit_path == "false" :
pex_inherit_path = self . _pex_info . inherit_path
self . patch_sys ( pex_inherit_path )
working_set = self . _activate ( )
self . patch_pkg_reso... |
def format_dates ( self , data , columns ) :
"""This method translates columns values into datetime objects
: param data : original Pandas dataframe
: param columns : list of columns to cast the date to a datetime object
: type data : pandas . DataFrame
: type columns : list of strings
: returns : Pandas ... | for column in columns :
if column in data . columns :
data [ column ] = pandas . to_datetime ( data [ column ] )
return data |
def OnTimerToggle ( self , event ) :
"""Toggles the timer for updating frozen cells""" | if self . grid . timer_running : # Stop timer
self . grid . timer_running = False
self . grid . timer . Stop ( )
del self . grid . timer
else : # Start timer
self . grid . timer_running = True
self . grid . timer = wx . Timer ( self . grid )
self . grid . timer . Start ( config [ "timer_interval... |
def update ( self , values ) :
'''Add iterable * values * to the set''' | d = self . value_pickler . dumps
return self . cache . update ( tuple ( ( d ( v ) for v in values ) ) ) |
def searchcomplement ( table , * args , ** kwargs ) :
"""Perform a regular expression search , returning rows that * * do not * *
match a given pattern , either anywhere in the row or within a specific
field . E . g . : :
> > > import petl as etl
> > > table1 = [ [ ' foo ' , ' bar ' , ' baz ' ] ,
. . . [ ... | return search ( table , * args , complement = True , ** kwargs ) |
def cut_gmail_quote ( html_message ) :
'''Cuts the outermost block element with class gmail _ quote .''' | gmail_quote = cssselect ( 'div.gmail_quote' , html_message )
if gmail_quote and ( gmail_quote [ 0 ] . text is None or not RE_FWD . match ( gmail_quote [ 0 ] . text ) ) :
gmail_quote [ 0 ] . getparent ( ) . remove ( gmail_quote [ 0 ] )
return True |
def send ( self , data , registration_ids = None , ** kwargs ) :
"""Send a GCM message for one or more devices , using json data
registration _ ids : A list with the devices which will be receiving a message
data : The dict data which will be send
Optional params e . g . :
collapse _ key : A string to group... | if not isinstance ( data , dict ) :
data = { 'msg' : data }
registration_ids = registration_ids or [ ]
if len ( registration_ids ) > conf . GCM_MAX_RECIPIENTS :
ret = [ ]
for chunk in self . _chunks ( registration_ids , conf . GCM_MAX_RECIPIENTS ) :
ret . append ( self . send ( data , registration_i... |
def experiments_predictions_create ( self , model_id , name , api_url , arguments = { } , properties = None ) :
"""Create a new model run at the given SCO - API .
Parameters
model _ id : string
Unique model identifier
name : string
User - defined name for experiment
api _ url : string
Url to POST crea... | # Create experiment and return handle for created resource
return self . experiments_predictions_get ( ModelRunHandle . create ( api_url , model_id , name , arguments , properties = properties ) ) |
def deprecated ( alternative = None ) :
"""This is a decorator which can be used to mark functions
as deprecated . It will result in a warning being emitted
when the function is used .""" | def real_decorator ( func ) :
@ functools . wraps ( func )
def new_func ( * args , ** kwargs ) :
msg = "Call to deprecated function {0}." . format ( func . __name__ )
if alternative :
msg += " Use {0} instead" . format ( alternative )
warnings . warn_explicit ( msg , category... |
def find_substring ( substring , suffix_tree , edge_repo ) :
"""Returns the index if substring in tree , otherwise - 1.""" | assert isinstance ( substring , str )
assert isinstance ( suffix_tree , SuffixTree )
assert isinstance ( edge_repo , EventSourcedRepository )
if not substring :
return - 1
if suffix_tree . case_insensitive :
substring = substring . lower ( )
curr_node_id = suffix_tree . root_node_id
i = 0
while i < len ( substr... |
def set_window_title ( self , title : str ) -> None : # pragma : no cover
"""Set the terminal window title
IMPORTANT : This function will not set the title unless it can acquire self . terminal _ lock to avoid
writing to stderr while a command is running . Therefore it is best to acquire the lock
before calli... | if not vt100_support :
return
# Sanity check that can ' t fail if self . terminal _ lock was acquired before calling this function
if self . terminal_lock . acquire ( blocking = False ) :
try :
import colorama . ansi as ansi
sys . stderr . write ( ansi . set_title ( title ) )
except Attribut... |
def summarize_sec2hdrnts ( self , sec2d_hdrnts ) :
"""Given namedtuples in each sectin , get counts of header GO IDs and sections .""" | sec2d_hdrgos = [ ( s , set ( nt . GO for nt in nts ) ) for s , nts in sec2d_hdrnts ]
return self . summarize_sec2hdrgos ( sec2d_hdrgos ) |
def set_pointing_label ( self ) :
"""Let the label of the current pointing to the value in the plabel box""" | current = self . current
pointing = self . pointings [ current ]
self . delete_pointing ( None )
pointing [ "label" ] [ 'text' ] = self . plabel . get ( )
self . pointings . append ( pointing )
self . plot_pointings ( [ pointing ] )
self . current = current |
def process_tree_recur ( self , file_names , node ) :
"""Adds the names of all the files associated with the sub - tree rooted by ` node ` to ` file _ names ` in post - order .
: param file _ names : A global list containing all file names associated with a tree
: param node : The root of the current sub - tree... | # Process node ' s children
for child_node in node . children :
self . process_tree_recur ( file_names , child_node )
# Call children first in case a tiled thumbnail is needed
file_names . extend ( node . process_files ( ) ) |
def _limit_data ( self , data ) :
"""Find the per - day average of each series in the data over the last 7
days ; drop all but the top 10.
: param data : original graph data
: type data : dict
: return : dict containing only the top 10 series , based on average over
the last 7 days .
: rtype : dict""" | if len ( data . keys ( ) ) <= 10 :
logger . debug ( "Data has less than 10 keys; not limiting" )
return data
# average last 7 days of each series
avgs = { }
for k in data :
if len ( data [ k ] ) <= 7 :
vals = data [ k ]
else :
vals = data [ k ] [ - 7 : ]
avgs [ k ] = sum ( vals ) / l... |
def event_teams ( self , event , simple = False , keys = False ) :
"""Get list of teams at an event .
: param event : Event key to get data on .
: param simple : Get only vital data .
: param keys : Return list of team keys only rather than full data on every team .
: return : List of string keys or Team ob... | if keys :
return self . _get ( 'event/%s/teams/keys' % event )
else :
return [ Team ( raw ) for raw in self . _get ( 'event/%s/teams%s' % ( event , '/simple' if simple else '' ) ) ] |
def normalize_rows ( features ) :
"""This performs row normalization to 1 of community embedding features .
Input : - X in R ^ ( nxC _ n ) : The community indicator matrix .
Output : - X _ norm in R ^ ( nxC _ n ) : The row normalized community indicator matrix .""" | # Normalize each row of term frequencies to 1
features = features . tocsr ( )
features = normalize ( features , norm = "l2" )
# for i in range ( features . shape [ 0 ] ) :
# term _ frequency = features . getrow ( i ) . data
# if term _ frequency . size > 0:
# features . data [ features . indptr [ i ] : features . indpt... |
def parse_plotEnrichment ( self ) :
"""Find plotEnrichment output .""" | self . deeptools_plotEnrichment = dict ( )
for f in self . find_log_files ( 'deeptools/plotEnrichment' ) :
parsed_data = self . parsePlotEnrichment ( f )
for k , v in parsed_data . items ( ) :
if k in self . deeptools_plotEnrichment :
log . warning ( "Replacing duplicate sample {}." . format... |
def append ( self , request , response ) :
"""Add a request , response pair to this cassette""" | request = self . _before_record_request ( request )
if not request :
return
# Deepcopy is here because mutation of ` response ` will corrupt the
# real response .
response = copy . deepcopy ( response )
response = self . _before_record_response ( response )
if response is None :
return
self . data . append ( ( ... |
def hsize ( bytes ) :
"""converts a bytes to human - readable format""" | sizes = [ 'Bytes' , 'KB' , 'MB' , 'GB' , 'TB' ]
if bytes == 0 :
return '0 Byte'
i = int ( math . floor ( math . log ( bytes ) / math . log ( 1024 ) ) )
r = round ( bytes / math . pow ( 1024 , i ) , 2 )
return str ( r ) + '' + sizes [ i ] |
def append_to_list ( self , source , start = None , hasIndex = False ) :
'''Appends new list to self . nameDict
Argument :
source - - source of new name list ( filename or list )
start - - starting index of new list
hasIndex - - the file is already indexed''' | nfy = Numberify ( )
try :
if start is None :
if type ( source ) is str :
if hasIndex is True :
newList = self . get_from_indexedFile ( source )
else :
newList = nfy . numberify_data ( source , len ( self . nameDict ) + 1 )
else :
newList = nfy . nu... |
def format_size ( size ) :
"""Convert size to XB , XKB , XMB , XGB
: param size : length value
: return : string value with size unit""" | units = [ 'B' , 'KB' , 'MB' , 'GB' ]
unit = ''
n = size
old_n = n
value = size
for i in units :
old_n = n
x , y = divmod ( n , 1024 )
if x == 0 :
unit = i
value = y
break
n = x
unit = i
value = old_n
return str ( value ) + unit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.