signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def split_certificate ( certificate_path , destination_folder , password = None ) :
"""Splits a PKCS12 certificate into Base64 - encoded DER certificate and key .
This method splits a potentially password - protected
` PKCS12 < https : / / en . wikipedia . org / wiki / PKCS _ 12 > ` _ certificate
( format ` `... | try : # Attempt Linux and Darwin call first .
p = subprocess . Popen ( [ "openssl" , "version" ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE )
sout , serr = p . communicate ( )
openssl_executable_version = sout . decode ( ) . lower ( )
if not ( openssl_executable_version . startswith ( "op... |
def get_resolved_res_configs ( self , rid , config = None ) :
"""Return a list of resolved resource IDs with their corresponding configuration .
It has a similar return type as : meth : ` get _ res _ configs ` but also handles complex entries
and references .
Also instead of returning : class : ` ARSCResTable... | resolver = ARSCParser . ResourceResolver ( self , config )
return resolver . resolve ( rid ) |
def delete ( self , storagemodel ) :
"""delete existing Entity""" | modeldefinition = self . getmodeldefinition ( storagemodel , True )
pk = storagemodel . getPartitionKey ( )
rk = storagemodel . getRowKey ( )
try :
modeldefinition [ 'tableservice' ] . delete_entity ( modeldefinition [ 'tablename' ] , pk , rk )
storagemodel . _exists = False
except AzureMissingResourceHttpError... |
async def release_cursor ( self , cursor , in_transaction = False ) :
"""Release cursor coroutine . Unless in transaction ,
the connection is also released back to the pool .""" | conn = cursor . connection
await cursor . close ( )
if not in_transaction :
self . release ( conn ) |
def _find_player_id ( self , row ) :
"""Find the player ' s ID .
Find the player ' s ID as embedded in the ' data - append - csv ' attribute ,
such as ' zettehe01 ' for Henrik Zetterberg .
Parameters
row : PyQuery object
A PyQuery object representing a single row in a boxscore table for
a single player ... | player_id = row ( 'th' ) . attr ( 'data-append-csv' )
if not player_id :
player_id = row ( 'td' ) . attr ( 'data-append-csv' )
return player_id |
def _index_audio_cmu ( self , basename = None , replace_already_indexed = False ) :
"""Indexes audio with pocketsphinx . Beware that the output would not be
sufficiently accurate . Use this only if you don ' t want to upload your
files to IBM .
Parameters
basename : str , optional
A specific basename to b... | self . _prepare_audio ( basename = basename , replace_already_indexed = replace_already_indexed )
for staging_audio_basename in self . _list_audio_files ( sub_dir = "staging" ) :
original_audio_name = '' . join ( staging_audio_basename . split ( '.' ) [ : - 1 ] ) [ : - 3 ]
pocketsphinx_command = '' . join ( [ "... |
def set_params ( self , params ) :
"""Sets multiple GO - PCA Server parameters using a dictionary .
Parameters
params : dict
Dictionary containing the parameter values .
Returns
None""" | for k , v in params . iteritems ( ) :
self . set_param ( k , v ) |
def config_options ( self ) :
"""Generate a Trailets Config instance for shell widgets using our
config system
This lets us create each widget with its own config""" | # - - - - Jupyter config - - - -
try :
full_cfg = load_pyconfig_files ( [ 'jupyter_qtconsole_config.py' ] , jupyter_config_dir ( ) )
# From the full config we only select the JupyterWidget section
# because the others have no effect here .
cfg = Config ( { 'JupyterWidget' : full_cfg . JupyterWidget } )
... |
def run ( self ) :
"""Construct the document id from the date and the url .""" | document = { }
document [ '_id' ] = hashlib . sha1 ( '%s:%s' % ( self . date , self . url ) ) . hexdigest ( )
with self . input ( ) . open ( ) as handle :
document [ 'content' ] = handle . read ( ) . decode ( 'utf-8' , 'ignore' )
document [ 'url' ] = self . url
document [ 'date' ] = unicode ( self . date )
with sel... |
def algorithm ( G , method_name , ** kwargs ) :
"""Apply a ` ` method ` ` from NetworkX to all : ref : ` networkx . Graph < networkx : graph > ` objects in the
: class : ` . GraphCollection ` ` ` G ` ` .
For options , see the ` list of algorithms
< http : / / networkx . github . io / documentation / networkx ... | warnings . warn ( "To be removed in 0.8. Use GraphCollection.analyze instead." , DeprecationWarning )
return G . analyze ( method_name , ** kwargs ) |
def _query_wrap ( fun , * args , ** kwargs ) :
"""Wait until at least QUERY _ WAIT _ TIME seconds have passed
since the last invocation of this function , then call the given
function with the given arguments .""" | with _query_lock :
global _last_query_time
since_last_query = time . time ( ) - _last_query_time
if since_last_query < QUERY_WAIT_TIME :
time . sleep ( QUERY_WAIT_TIME - since_last_query )
_last_query_time = time . time ( )
return fun ( * args , ** kwargs ) |
def requests_url ( self , ptype , ** data ) :
"""这里包装了一个函数 , 发送post _ data
: param ptype : n 列表无歌曲 , 返回新列表
e 发送歌曲完毕
b 不再播放 , 返回新列表
s 下一首 , 返回新的列表
r 标记喜欢
u 取消标记喜欢""" | options = { 'type' : ptype , 'pt' : '3.1' , 'channel' : self . _channel_id , 'pb' : '320' , 'from' : 'mainsite' , 'r' : '' , 'kbps' : '320' , 'app_name' : 'radio_website' , 'client' : 's:mainsite|y:3.0' , 'version' : '100' }
if 'sid' in data :
options [ 'sid' ] = data [ 'sid' ]
url = 'https://douban.fm/j/v2/playlis... |
def create_resource ( self , parent_id = "" ) :
"""Create the specified resource .
Args :
parent _ id ( str ) : The resource ID of the parent resource in API Gateway""" | resource_name = self . trigger_settings . get ( 'resource' , '' )
resource_name = resource_name . replace ( '/' , '' )
if not self . resource_id :
created_resource = self . client . create_resource ( restApiId = self . api_id , parentId = parent_id , pathPart = resource_name )
self . resource_id = created_resou... |
def get_installed_version ( dist_name , working_set = None ) :
"""Get the installed version of dist _ name avoiding pkg _ resources cache""" | # Create a requirement that we ' ll look for inside of setuptools .
req = pkg_resources . Requirement . parse ( dist_name )
if working_set is None : # We want to avoid having this cached , so we need to construct a new
# working set each time .
working_set = pkg_resources . WorkingSet ( )
# Get the installed distri... |
def hdfs_connect ( host = 'localhost' , port = 50070 , protocol = 'webhdfs' , use_https = 'default' , auth_mechanism = 'NOSASL' , verify = True , session = None , ** kwds ) :
"""Connect to HDFS .
Parameters
host : str
Host name of the HDFS NameNode
port : int
NameNode ' s WebHDFS port
protocol : str ,
... | import requests
if session is None :
session = requests . Session ( )
session . verify = verify
if auth_mechanism in ( 'GSSAPI' , 'LDAP' ) :
if use_https == 'default' :
prefix = 'https'
else :
prefix = 'https' if use_https else 'http'
try :
import requests_kerberos
# noqa... |
def _use_html_if_available ( format_fn ) :
"""Use the value ' s HTML rendering if available , overriding format _ fn .""" | def format_using_as_html ( v , label = False ) :
if not label and hasattr ( v , 'as_html' ) :
return v . as_html ( )
else :
return format_fn ( v , label )
return format_using_as_html |
def save ( self , with_data = False ) :
"""Edits this Source""" | r = self . _client . request ( 'PUT' , self . url , json = self . _serialize ( with_data = with_data ) )
return self . _deserialize ( r . json ( ) , self . _manager ) |
def removeChild ( self , child , end_tag_too = True ) :
"""Remove subelement ( ` child ` ) specified by reference .
Note :
This can ' t be used for removing subelements by value ! If you want
to do such thing , try : :
for e in dom . find ( " value " ) :
dom . removeChild ( e )
Args :
child ( obj ) : ... | # if there are multiple childs , remove them
if _is_iterable ( child ) :
for x in child :
self . removeChild ( child = x , end_tag_too = end_tag_too )
return
if not self . childs :
return
end_tag = None
if end_tag_too :
end_tag = child . endtag
for e in self . childs :
if e != child :
... |
def setFlag ( self , flag , state = True ) :
"""Sets whether or not the given flag is enabled or disabled .
: param flag | < XExporter . Flags >""" | has_flag = self . testFlag ( flag )
if has_flag and not state :
self . setFlags ( self . flags ( ) ^ flag )
elif not has_flag and state :
self . setFlags ( self . flags ( ) | flag ) |
def parse_url ( url ) :
"""Parse the given url and update it with environment value if required .
: param basestring url :
: rtype : basestring
: raise : KeyError if environment variable is needed but not found .""" | # the url has to be a unicode by pystache ' s design , but the unicode concept has been rewamped in py3
# we use a try except to make the code compatible with py2 and py3
try :
url = unicode ( url )
except NameError :
url = url
parsed = pystache . parse ( url )
# pylint : disable = protected - access
variables ... |
def _loss_lr_subject ( self , data , labels , w , theta , bias ) :
"""Compute the Loss MLR for a single subject ( without regularization )
Parameters
data : array , shape = [ voxels , samples ]
The fMRI data of subject i for the classification task .
labels : array of int , shape = [ samples ]
The labels ... | if data is None :
return 0.0
samples = data . shape [ 1 ]
thetaT_wi_zi_plus_bias = theta . T . dot ( w . T . dot ( data ) ) + bias
sum_exp , max_value , _ = utils . sumexp_stable ( thetaT_wi_zi_plus_bias )
sum_exp_values = np . log ( sum_exp ) + max_value
aux = 0.0
for sample in range ( samples ) :
label = labe... |
def _on_write_request ( self , request ) :
"""Callback function called when a write request has been received .
It is executed in the baBLE working thread : should not be blocking .
Args :
request ( dict ) : Information about the request
- connection _ handle ( int ) : The connection handle that sent the re... | if request [ 'connection_handle' ] != self . _connection_handle :
return False
attribute_handle = request [ 'attribute_handle' ]
# If write to configure notification
config_handles = [ ReceiveHeaderChar . config_handle , ReceivePayloadChar . config_handle , StreamingChar . config_handle , TracingChar . config_handl... |
def delete ( filepath ) :
"""Delete the given file , directory or link .
It Should support undelete later on .
Args :
filepath ( str ) : Absolute full path to a file . e . g . / path / to / file""" | # Some files have ACLs , let ' s remove them recursively
remove_acl ( filepath )
# Some files have immutable attributes , let ' s remove them recursively
remove_immutable_attribute ( filepath )
# Finally remove the files and folders
if os . path . isfile ( filepath ) or os . path . islink ( filepath ) :
os . remove... |
def search_script_file ( self , path , file_name ) :
"""Open a script file and search it for library references
: param path :
: param file _ name :
: return : void""" | with open ( os . path . join ( path , file_name ) , "r" ) as script :
self . search_script ( script . read ( ) ) |
def clean ( self ) :
"""> > > import django . forms
> > > class MyForm ( CleanWhiteSpacesMixin , django . forms . Form ) :
. . . some _ field = django . forms . CharField ( )
> > > form = MyForm ( { ' some _ field ' : ' a weird value ' } )
> > > assert form . is _ valid ( )
> > > assert form . cleaned _ d... | cleaned_data = super ( CleanWhiteSpacesMixin , self ) . clean ( )
for k in self . cleaned_data :
if isinstance ( self . cleaned_data [ k ] , six . string_types ) :
cleaned_data [ k ] = re . sub ( extra_spaces_pattern , ' ' , self . cleaned_data [ k ] or '' ) . strip ( )
return cleaned_data |
def fetch_open_orders ( self , limit : int ) -> List [ Order ] :
"""Fetch latest open orders , must provide a limit .""" | return self . _fetch_orders_limit ( self . _open_orders , limit ) |
def get_profile_dir ( ) :
"""Return path where all profiles of current user are stored .""" | if os . name == 'nt' :
basedir = unicode ( os . environ [ "APPDATA" ] , nt_filename_encoding )
dirpath = os . path . join ( basedir , u"Opera" , u"Opera" )
elif os . name == 'posix' :
basedir = unicode ( os . environ [ "HOME" ] )
dirpath = os . path . join ( basedir , u".opera" )
return dirpath |
def get_datetimenow ( self ) :
"""get datetime now according to USE _ TZ and default time""" | value = timezone . datetime . utcnow ( )
if settings . USE_TZ :
value = timezone . localtime ( timezone . make_aware ( value , timezone . utc ) , timezone . get_default_timezone ( ) )
return value |
def getPeersByName ( self , name ) :
'''getPeersByName - Gets peers ( elements on same level ) with a given name
@ param name - Name to match
@ return - None if no parent element ( error condition ) , otherwise a TagCollection of peers that matched .''' | peers = self . peers
if peers is None :
return None
return TagCollection ( [ peer for peer in peers if peer . name == name ] ) |
def _fset ( self , name ) :
"""Build and returns the property ' s * fdel * method for the member defined by * name * .""" | def fset ( inst , value ) : # the setter uses the wrapped function as well
# to allow for value checks
value = self . fparse ( inst , value )
setattr ( inst , name , value )
return fset |
def add_lvl_to_ui ( self , level , header ) :
"""Insert the level and header into the ui .
: param level : a newly created level
: type level : : class : ` jukeboxcore . gui . widgets . browser . AbstractLevel `
: param header : a newly created header
: type header : QtCore . QWidget | None
: returns : No... | w = QtGui . QWidget ( self )
vbox = QtGui . QVBoxLayout ( )
vbox . setContentsMargins ( 0 , 0 , 0 , 0 )
w . setLayout ( vbox )
if header is not None :
vbox . addWidget ( header )
vbox . addWidget ( level )
self . splitter . addWidget ( w ) |
def parse_val ( cfg , section , option ) :
"""extract a single value from . cfg""" | vals = parse_vals ( cfg , section , option )
if len ( vals ) == 0 :
return ''
else :
assert len ( vals ) == 1 , ( section , option , vals , type ( vals ) )
return vals [ 0 ] |
def disable_napp ( mgr ) :
"""Disable a NApp .""" | if mgr . is_enabled ( ) :
LOG . info ( ' Disabling...' )
mgr . disable ( )
LOG . info ( ' Disabled.' )
else :
LOG . error ( " NApp isn't enabled." ) |
def onSiliconCheckList ( ra_deg , dec_deg , FovObj , padding_pix = DEFAULT_PADDING ) :
"""Check a list of positions .""" | dist = angSepVincenty ( FovObj . ra0_deg , FovObj . dec0_deg , ra_deg , dec_deg )
mask = ( dist < 90. )
out = np . zeros ( len ( dist ) , dtype = bool )
out [ mask ] = FovObj . isOnSiliconList ( ra_deg [ mask ] , dec_deg [ mask ] , padding_pix = padding_pix )
return out |
def partymode ( self ) :
"""Put all the speakers in the network in the same group , a . k . a Party
Mode .
This blog shows the initial research responsible for this :
http : / / blog . travelmarx . com / 2010/06 / exploring - sonos - via - upnp . html
The trick seems to be ( only tested on a two - speaker s... | # Tell every other visible zone to join this one
# pylint : disable = expression - not - assigned
[ zone . join ( self ) for zone in self . visible_zones if zone is not self ] |
def to_bytes ( s , encoding = None , errors = 'strict' ) :
"""Returns a bytestring version of ' s ' ,
encoded as specified in ' encoding ' .""" | encoding = encoding or 'utf-8'
if isinstance ( s , bytes ) :
if encoding != 'utf-8' :
return s . decode ( 'utf-8' , errors ) . encode ( encoding , errors )
else :
return s
if not is_string ( s ) :
s = string_type ( s )
return s . encode ( encoding , errors ) |
def to_json ( self , data ) :
"""Converts the given object to a pretty - formatted JSON string
: param data : the object to convert to JSON
: return : A pretty - formatted JSON string""" | # Don ' t forget the empty line at the end of the file
return ( json . dumps ( data , sort_keys = True , indent = 4 , separators = ( "," , ": " ) , default = self . json_converter , ) + "\n" ) |
def ObjectModifiedEventHandler ( obj , event ) :
"""Object has been modified""" | # only snapshot supported objects
if not supports_snapshots ( obj ) :
return
# take a new snapshot
take_snapshot ( obj , action = "edit" )
# reindex the object in the auditlog catalog
reindex_object ( obj ) |
def clear ( self , store = True ) :
"""Clears ( locks ) the achievement .
: rtype : bool""" | result = self . _iface . ach_lock ( self . name )
result and store and self . _store ( )
return result |
def _debug ( self , msg , * args , ** kwargs ) :
"""Emit debugging messages .""" | # Do nothing if debugging is disabled
if self . _debug_stream is None or self . _debug_stream is False :
return
# What are we passing to the format ?
if kwargs :
fmtargs = kwargs
else :
fmtargs = args
# Emit the message
print >> self . _debug_stream , msg % fmtargs |
def _table_arg_to_table_ref ( value , default_project = None ) :
"""Helper to convert a string or Table to TableReference .
This function keeps TableReference and other kinds of objects unchanged .""" | if isinstance ( value , six . string_types ) :
value = TableReference . from_string ( value , default_project = default_project )
if isinstance ( value , ( Table , TableListItem ) ) :
value = value . reference
return value |
def check_ds9 ( self ) :
"""Checks for DS9 compatibility .""" | if self . region_type not in regions_attributes :
raise ValueError ( "'{0}' is not a valid region type in this package" "supported by DS9" . format ( self . region_type ) )
if self . coordsys not in valid_coordsys [ 'DS9' ] :
raise ValueError ( "'{0}' is not a valid coordinate reference frame " "in astropy supp... |
def load_config ( path = None , defaults = None ) :
"""Loads and parses an INI style configuration file using Python ' s built - in
ConfigParser module .
If path is specified , load it .
If ` ` defaults ` ` ( a list of strings ) is given , try to load each entry as a
file , without throwing any error if the... | if defaults is None :
defaults = DEFAULT_FILES
config = configparser . SafeConfigParser ( allow_no_value = True )
if defaults :
config . read ( defaults )
if path :
with open ( path ) as fh :
config . readfp ( fh )
return config |
def track_heads ( self , cmd ) :
"""Track the repository heads given a CommitCommand .
: param cmd : the CommitCommand
: return : the list of parents in terms of commit - ids""" | # Get the true set of parents
if cmd . from_ is not None :
parents = [ cmd . from_ ]
else :
last_id = self . last_ids . get ( cmd . ref )
if last_id is not None :
parents = [ last_id ]
else :
parents = [ ]
parents . extend ( cmd . merges )
# Track the heads
self . track_heads_for_ref ( c... |
def _get_global_dbapi_info ( dbapi_module , conn ) :
"""Fetches all needed information from the top - level DBAPI module ,
guessing at the module if it wasn ' t passed as a parameter . Returns a
dictionary of all the needed variables . This is put in one place to
make sure the error message is clear if the mo... | module_given_msg = "The DBAPI2 module given ({0}) is missing the global\n" + "variable '{1}'. Please make sure you are supplying a module that\n" + "conforms to the DBAPI 2.0 standard (PEP 0249)."
module_not_given_msg = "Hello! I gave my best effort to find the\n" + "top-level module that the connection object you gave... |
def handle_event ( self , event ) :
"""When we get an ' event ' type from the bridge
handle it by invoking the handler and if needed
sending back the result .""" | result_id , ptr , method , args = event [ 1 ]
obj = None
result = None
try :
obj , handler = bridge . get_handler ( ptr , method )
result = handler ( * [ v for t , v in args ] )
except bridge . BridgeReferenceError as e : # : Log the event , don ' t blow up here
msg = "Error processing event: {} - {}" . for... |
def subscribe ( topic , protocol , endpoint , region = None , key = None , keyid = None , profile = None ) :
'''Subscribe to a Topic .
CLI example to delete a topic : :
salt myminion boto _ sns . subscribe mytopic https https : / / www . example . com / sns - endpoint region = us - east - 1''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
conn . subscribe ( get_arn ( topic , region , key , keyid , profile ) , protocol , endpoint )
log . info ( 'Subscribe %s %s to %s topic' , protocol , endpoint , topic )
try :
del __context__ [ _subscriptions_cache_key ( topic ) ]
e... |
def group_factory ( bridge , number , name , led_type ) :
"""Make a group .
: param bridge : Member of this bridge .
: param number : Group number ( 1-4 ) .
: param name : Name of group .
: param led _ type : Either ` RGBW ` , ` WRGB ` , ` RGBWW ` , ` WHITE ` , ` DIMMER ` or ` BRIDGE _ LED ` .
: returns :... | if led_type in [ RGBW , BRIDGE_LED ] :
return RgbwGroup ( bridge , number , name , led_type )
elif led_type == RGBWW :
return RgbwwGroup ( bridge , number , name )
elif led_type == WHITE :
return WhiteGroup ( bridge , number , name )
elif led_type == DIMMER :
return DimmerGroup ( bridge , number , name ... |
def _get_converter ( self , converter_str ) :
"""find converter function reference by name
find converter by name , converter name follows this convention :
Class . method
or :
method
The first type of converter class / function must be available in
current module .
The second type of converter must b... | ret = None
if converter_str is not None :
converter_desc_list = converter_str . split ( '.' )
if len ( converter_desc_list ) == 1 :
converter = converter_desc_list [ 0 ]
# default to ` converter `
ret = getattr ( cvt , converter , None )
if ret is None : # try module converter
... |
def connections ( self , origin , destination , dt = datetime . now ( ) , only_direct = False ) :
"""Find connections between two stations
Args :
origin ( str ) : origin station
destination ( str ) : destination station
dt ( datetime ) : date and time for query
only _ direct ( bool ) : only direct connect... | query = { 'S' : origin , 'Z' : destination , 'date' : dt . strftime ( "%d.%m.%y" ) , 'time' : dt . strftime ( "%H:%M" ) , 'start' : 1 , 'REQ0JourneyProduct_opt0' : 1 if only_direct else 0 }
rsp = requests . get ( 'http://mobile.bahn.de/bin/mobil/query.exe/dox?' , params = query )
return parse_connections ( rsp . text ) |
def active_vectors ( self ) :
"""The active vectors array""" | field , name = self . active_vectors_info
if name :
if field is POINT_DATA_FIELD :
return self . point_arrays [ name ]
if field is CELL_DATA_FIELD :
return self . cell_arrays [ name ] |
def get_param_map ( word , required_keys = None ) :
"""get the optional arguments on a line
Example
> > > iline = 0
> > > word = ' elset , instance = dummy2 , generate '
> > > params = get _ param _ map ( iline , word , required _ keys = [ ' instance ' ] )
params = {
' elset ' : None ,
' instance ' : ... | if required_keys is None :
required_keys = [ ]
words = word . split ( "," )
param_map = { }
for wordi in words :
if "=" not in wordi :
key = wordi . strip ( )
value = None
else :
sword = wordi . split ( "=" )
assert len ( sword ) == 2 , sword
key = sword [ 0 ] . strip... |
def visit_keyword ( self , node , parent ) :
"""visit a Keyword node by returning a fresh instance of it""" | newnode = nodes . Keyword ( node . arg , parent = parent )
newnode . postinit ( self . visit ( node . value , newnode ) )
return newnode |
def _cleanup_unregistered_flag_from_module_dicts ( self , flag_obj ) :
"""Cleans up unregistered flags from all module - > [ flags ] dictionaries .
If flag _ obj is registered under either its long name or short name , it
won ' t be removed from the dictionaries .
Args :
flag _ obj : Flag , the Flag instanc... | if self . _flag_is_registered ( flag_obj ) :
return
for flags_by_module_dict in ( self . flags_by_module_dict ( ) , self . flags_by_module_id_dict ( ) , self . key_flags_by_module_dict ( ) ) :
for flags_in_module in six . itervalues ( flags_by_module_dict ) : # While ( as opposed to if ) takes care of multiple ... |
def apply_complement ( self , a , return_Ya = False ) :
"""Apply the complementary projection to an array .
: param z : array with ` ` shape = = ( N , m ) ` ` .
: return : : math : ` P _ { \\ mathcal { Y } ^ \\ perp , \\ mathcal { X } } z =
z - P _ { \\ mathcal { X } , \\ mathcal { Y } ^ \\ perp } z ` .""" | # is projection the zero operator ? - - > complement is identity
if self . V . shape [ 1 ] == 0 :
if return_Ya :
return a . copy ( ) , numpy . zeros ( ( 0 , a . shape [ 1 ] ) )
return a . copy ( )
if return_Ya :
x , Ya = self . _apply ( a , return_Ya = True )
else :
x = self . _apply ( a )
z = a... |
def run_as_pydevd_daemon_thread ( func , * args , ** kwargs ) :
'''Runs a function as a pydevd daemon thread ( without any tracing in place ) .''' | t = PyDBDaemonThread ( target_and_args = ( func , args , kwargs ) )
t . name = '%s (pydevd daemon thread)' % ( func . __name__ , )
t . start ( )
return t |
def _extract_text_dict ( self , raw_text ) :
"""Parse the TEXT segment of the FCS file into a python dictionary .""" | delimiter = raw_text [ 0 ]
if raw_text [ - 1 ] != delimiter :
raw_text = raw_text . strip ( )
if raw_text [ - 1 ] != delimiter :
msg = ( u'The first two characters were:\n {}. The last two characters were: {}\n' u'Parser expects the same delimiter character in beginning ' u'and end of TEXT segment' . fo... |
def autosave_all ( self ) :
"""Autosave all opened files .""" | for index in range ( self . stack . get_stack_count ( ) ) :
self . autosave ( index ) |
def sign ( message , gpg_home = None , gpg_signing_key = None , ** config ) :
"""Insert a new field into the message dict and return it .
The new field is :
- ' signature ' - the computed GPG message digest of the JSON repr
of the ` msg ` field .""" | if gpg_home is None or gpg_signing_key is None :
raise ValueError ( "You must set the gpg_home \
and gpg_signing_key keyword arguments." )
message [ 'crypto' ] = 'gpg'
signature = _ctx . sign ( fedmsg . encoding . dumps ( message [ 'msg' ] ) , gpg_signing_key , homedir = gpg_home )
return d... |
def to_numpy ( X ) :
"""Generic function to convert a pytorch tensor to numpy .
Returns X when it already is a numpy array .""" | if isinstance ( X , np . ndarray ) :
return X
if is_pandas_ndframe ( X ) :
return X . values
if not is_torch_data_type ( X ) :
raise TypeError ( "Cannot convert this data type to a numpy array." )
if X . is_cuda :
X = X . cpu ( )
if X . requires_grad :
X = X . detach ( )
return X . numpy ( ) |
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 :
return yaml . load ( projex . text . nativestring ( db_value ) )
else :
return db_value |
def request_data_url ( url , headers = None , num_retries = NUM_RETRIES , timeout = TIMEOUT , params_request = None , json_req = False , ** kwargs_req ) :
"""Realiza sucesivos intentos de request a una url dada , intentándolo hasta que recibe un status 200 ( OK )
y el texto recibido es mayor que MIN _ LEN _ REQU... | count , status , response = 0 , - 1 , None
kwargs_req . update ( timeout = timeout )
while count < num_retries :
try :
resp = requests . get ( url , headers = headers , params = params_request , ** kwargs_req )
status = resp . status_code
if status == 200 :
if json_req :
... |
def _load_hooks ( path ) :
"""Load hook module and register signals .
: param path : Absolute or relative path to module .
: return : module""" | module = imp . load_source ( os . path . splitext ( os . path . basename ( path ) ) [ 0 ] , path )
if not check_hook_mechanism_is_intact ( module ) : # no hooks - do nothing
log . debug ( 'No valid hook configuration: \'%s\'. Not using hooks!' , path )
else :
if check_register_present ( module ) : # register th... |
def get_plan_id ( kwargs = None , call = None ) :
'''Returns the Linode Plan ID .
label
The label , or name , of the plan to get the ID from .
CLI Example :
. . code - block : : bash
salt - cloud - f get _ plan _ id linode label = " Linode 1024"''' | if call == 'action' :
raise SaltCloudException ( 'The show_instance action must be called with -f or --function.' )
if kwargs is None :
kwargs = { }
label = kwargs . get ( 'label' , None )
if label is None :
raise SaltCloudException ( 'The get_plan_id function requires a \'label\'.' )
label = _decode_linode... |
def dmsToDeg ( sign , deg , min , sec ) :
"""Convert dec sign , degrees , minutes , seconds into a signed angle in
degrees .""" | return sign * ( deg + min * degPerDmsMin + sec * degPerDmsSec ) |
def roman2int ( s ) :
"""Decode roman number
: param s : string representing a roman number between 1 and 9999
: returns : the decoded roman number
: complexity : linear ( if that makes sense for constant bounded input size )""" | val = 0
pos10 = 1000
beg = 0
for pos in range ( 3 , - 1 , - 1 ) :
for digit in range ( 9 , - 1 , - 1 ) :
r = roman [ pos ] [ digit ]
if s . startswith ( r , beg ) : # footnote 1
beg += len ( r )
val += digit * pos10
break
pos10 //= 10
return val |
def create_current_version_unique_identity_indexes ( app_name , database = None ) :
"""Add partial unique indexes for the the identity column of versionable
models .
This enforces that no two * current * versions can have the same identity .
This will only try to create indexes if they do not exist in the dat... | indexes_created = 0
connection = database_connection ( database )
with connection . cursor ( ) as cursor :
for model in versionable_models ( app_name ) :
if getattr ( model . _meta , 'managed' , True ) :
table_name = model . _meta . db_table
index_name = '%s_%s_identity_v_uniq' % ( a... |
def partition_payload ( data , key , thresh ) :
"""Yield partitions of a payload
e . g . with a threshold of 2:
{ " dataElements " : [ 1 , 2 , 3 ] }
{ " dataElements " : [ 1 , 2 ] }
and
{ " dataElements " : [ 3 ] }
: param data : the payload
: param key : the key of the dict to partition
: param thr... | data = data [ key ]
for i in range ( 0 , len ( data ) , thresh ) :
yield { key : data [ i : i + thresh ] } |
def start ( self ) :
"""Activate the TypingStream on stdout""" | self . streams . append ( sys . stdout )
sys . stdout = self . stream |
def NewTagClass ( class_name : str , tag : str = None , bases : Union [ type , Iterable ] = ( Tag , ) , ** kwargs : Any ) -> type :
"""Generate and return new ` ` Tag ` ` class .
If ` ` tag ` ` is empty , lower case of ` ` class _ name ` ` is used for a tag name of
the new class . ` ` bases ` ` should be a tupl... | if tag is None :
tag = class_name . lower ( )
if not isinstance ( type , tuple ) :
if isinstance ( bases , Iterable ) :
bases = tuple ( bases )
elif isinstance ( bases , type ) :
bases = ( bases , )
else :
TypeError ( 'Invalid base class: {}' . format ( str ( bases ) ) )
kwargs [... |
def getconf ( self , path , conf = None , logger = None ) :
"""Parse a configuration path with input conf and returns
parameters by param name .
: param str path : conf resource path to parse and from get parameters .
: param Configuration conf : conf to fill with path values and
conf param names .
: para... | result = conf
pathconf = None
rscpaths = self . rscpaths ( path = path )
for rscpath in rscpaths :
pathconf = self . _getconf ( rscpath = rscpath , logger = logger , conf = conf )
if pathconf is not None :
if result is None :
result = pathconf
else :
result . update ( pat... |
def organization_subscription_create ( self , data , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / organization _ subscriptions # create - organization - subscription" | api_path = "/api/v2/organization_subscriptions.json"
return self . call ( api_path , method = "POST" , data = data , ** kwargs ) |
def virtual_machine_capture ( name , destination_name , resource_group , prefix = 'capture-' , overwrite = False , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Captures the VM by copying virtual hard disks of the VM and outputs
a template that can be used to create similar VMs .
: param name : The name of t... | # pylint : disable = invalid - name
VirtualMachineCaptureParameters = getattr ( azure . mgmt . compute . models , 'VirtualMachineCaptureParameters' )
compconn = __utils__ [ 'azurearm.get_client' ] ( 'compute' , ** kwargs )
try : # pylint : disable = invalid - name
vm = compconn . virtual_machines . capture ( resour... |
def parse ( self , filename ) :
"""Parses a file into an AstromData structure .
Args :
filename : str
The name of the file whose contents will be parsed .
Returns :
data : AstromData
The file contents extracted into a data structure for programmatic
access .""" | filehandle = storage . open_vos_or_local ( filename , "rb" )
assert filehandle is not None , "Failed to open file {} " . format ( filename )
filestr = filehandle . read ( )
filehandle . close ( )
assert filestr is not None , "File contents are None"
observations = self . _parse_observation_list ( filestr )
self . _pars... |
def collectfiles ( path , filt = None ) :
"""Collects some files based on the given filename .
: param path | < str >
filt | < method >
: return [ ( < str > name , < str > filepath ) , . . ]""" | if not os . path . isdir ( path ) :
path = os . path . dirname ( path )
output = [ ]
for name in sorted ( os . listdir ( path ) ) :
filepath = os . path . join ( path , name )
if os . path . isfile ( filepath ) :
if not filt or filt ( name ) :
output . append ( ( name , filepath ) )
retu... |
def pegasus_elimination_order ( n , coordinates = False ) :
'''Produces a variable elimination order for a pegasus P ( n ) graph , which provides an upper bound on the treewidth .
Simple pegasus variable elimination order rules :
- eliminate vertical qubits , one column at a time
- eliminate horizontal qubits... | m = n
l = 12
# ordering for horizontal qubits in each tile , from east to west :
h_order = [ 4 , 5 , 6 , 7 , 0 , 1 , 2 , 3 , 8 , 9 , 10 , 11 ]
order = [ ]
for n_i in range ( n ) : # for each tile offset
# eliminate vertical qubits :
for l_i in range ( 0 , l , 2 ) :
for l_v in range ( l_i , l_i + 2 ) :
... |
def fit1d ( samples , e , remove_zeros = False , ** kw ) :
"""Fits a 1D distribution with splines .
Input :
samples : Array
Array of samples from a probability distribution
e : Array
Edges that define the events in the probability
distribution . For example , e [ 0 ] < x < = e [ 1 ] is
the range of va... | samples = samples [ ~ np . isnan ( samples ) ]
length = len ( e ) - 1
hist , _ = np . histogramdd ( samples , ( e , ) )
hist = hist / sum ( hist )
basis , knots = spline_base1d ( length , marginal = hist , ** kw )
non_zero = hist > 0
model = linear_model . BayesianRidge ( )
if remove_zeros :
model . fit ( basis [ n... |
def download_file ( url , destpath , filename = None , baseurl = None , subpath = None , middleware_callbacks = None , middleware_kwargs = None , request_fn = sess . get ) :
"""Download a file from a URL , into a destination folder , with optional use of relative paths and middleware processors .
- If ` filename ... | relative_file_url , subpath , filename = calculate_relative_url ( url , filename = filename , baseurl = baseurl , subpath = subpath )
# ensure that the destination directory exists
fulldestpath = os . path . join ( destpath , * subpath )
os . makedirs ( fulldestpath , exist_ok = True )
# make the actual request to the ... |
def multiple_directory_files_loader ( * args ) :
"""Loads all the files in each directory as values in a dict with the key
being the relative file path of the directory . Updates the value if
subsequent file paths are the same .""" | d = dict ( )
def load_files ( folder ) :
for ( dirpath , dirnames , filenames ) in os . walk ( folder ) :
for f in filenames :
filepath = os . path . join ( dirpath , f )
with open ( filepath , 'r' ) as f :
key = filepath [ len ( os . path . commonprefix ( [ root , fi... |
def _set_trigger_mode ( self , v , load = False ) :
"""Setter method for trigger _ mode , mapped from YANG variable / rbridge _ id / event _ handler / activate / name / trigger _ mode ( enumeration )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ trigger _ mode is cons... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'each-instance' : { 'value' : 1 } , u'only-once' : { 'value' : 3 } , u'on-first-instance' : { 'value' : 2 } } , ) , default = un... |
def p0f_impersonate ( pkt , osgenre = None , osdetails = None , signature = None , extrahops = 0 , mtu = 1500 , uptime = None ) :
"""Modifies pkt so that p0f will think it has been sent by a
specific OS . If osdetails is None , then we randomly pick up a
personality matching osgenre . If osgenre and signature a... | pkt = pkt . copy ( )
# pkt = pkt . _ _ class _ _ ( raw ( pkt ) )
while pkt . haslayer ( IP ) and pkt . haslayer ( TCP ) :
pkt = pkt . getlayer ( IP )
if isinstance ( pkt . payload , TCP ) :
break
pkt = pkt . payload
if not isinstance ( pkt , IP ) or not isinstance ( pkt . payload , TCP ) :
raise... |
def setup ( self , environ ) :
'''Called once only to setup the WSGI application handler .
Check : ref : ` lazy wsgi handler < wsgi - lazy - handler > `
section for further information .''' | request = wsgi_request ( environ )
cfg = request . cache . cfg
loop = request . cache . _loop
self . store = create_store ( cfg . data_store , loop = loop )
pubsub = self . store . pubsub ( protocol = Protocol ( ) )
channel = '%s_webchat' % self . name
ensure_future ( pubsub . subscribe ( channel ) , loop = loop )
retu... |
def _vectorize_single_raster ( self , raster , data_transform , crs , timestamp = None ) :
"""Vectorizes a data slice of a single time component
: param raster : Numpy array or shape ( height , width , channels )
: type raster : numpy . ndarray
: param data _ transform : Object holding a transform vector ( i ... | mask = None
if self . values :
mask = np . zeros ( raster . shape , dtype = np . bool )
for value in self . values :
mask [ raster == value ] = True
geo_list = [ ]
value_list = [ ]
for idx in range ( raster . shape [ - 1 ] ) :
for geojson , value in rasterio . features . shapes ( raster [ ... , idx ... |
def plot ( self , origin = ( 0 , 0 ) , ax = None , fill = False , ** kwargs ) :
"""Plot the ` BoundingBox ` on a matplotlib ` ~ matplotlib . axes . Axes `
instance .
Parameters
origin : array _ like , optional
The ` ` ( x , y ) ` ` position of the origin of the displayed
image .
ax : ` matplotlib . axes... | aper = self . to_aperture ( )
aper . plot ( origin = origin , ax = ax , fill = fill , ** kwargs ) |
def record_launch ( self , queue_id ) : # retcode ) :
"""Save submission""" | self . launches . append ( AttrDict ( queue_id = queue_id , mpi_procs = self . mpi_procs , omp_threads = self . omp_threads , mem_per_proc = self . mem_per_proc , timelimit = self . timelimit ) )
return len ( self . launches ) |
def predict ( self , Xstar , n = 0 , noise = False , return_std = True , return_cov = False , full_output = False , return_samples = False , num_samples = 1 , samp_kwargs = { } , return_mean_func = False , use_MCMC = False , full_MC = False , rejection_func = None , ddof = 1 , output_transform = None , ** kwargs ) :
... | if use_MCMC :
res = self . predict_MCMC ( Xstar , n = n , noise = noise , return_std = return_std or full_output , return_cov = return_cov or full_output , return_samples = full_output and ( return_samples or rejection_func ) , return_mean_func = full_output and return_mean_func , num_samples = num_samples , samp_k... |
def submit ( jman , command , arguments , deps = [ ] , array = None ) :
"""An easy submission option for grid - enabled scripts . Create the log
directories using random hash codes . Use the arguments as parsed by the main
script .""" | logdir = os . path . join ( os . path . realpath ( arguments . logdir ) , tools . random_logdir ( ) )
jobname = os . path . splitext ( os . path . basename ( command [ 0 ] ) ) [ 0 ]
cmd = tools . make_shell ( sys . executable , command )
if arguments . dryrun :
return DryRunJob ( cmd , cwd = arguments . cwd , queue... |
def end_container ( self , header_buf ) :
"""Add a node containing the container ' s header to the current subtree .
This node will be added as the leftmost leaf of the subtree that was
started by the matching call to start _ container .
Args :
header _ buf ( bytearray ) : bytearray containing the container... | if not self . __container_nodes :
raise ValueError ( "Attempted to end container with none active." )
# Header needs to be the first node visited on this subtree .
self . __container_node . add_leaf ( _Node ( header_buf ) )
self . __container_node = self . __container_nodes . pop ( )
parent_container_length = self ... |
def _document_path ( self ) :
"""Create and cache the full path for this document .
Of the form :
` ` projects / { project _ id } / databases / { database _ id } / . . .
documents / { document _ path } ` `
Returns :
str : The full document path .
Raises :
ValueError : If the current document reference... | if self . _document_path_internal is None :
if self . _client is None :
raise ValueError ( "A document reference requires a `client`." )
self . _document_path_internal = _get_document_path ( self . _client , self . _path )
return self . _document_path_internal |
def vecangle ( v1 , v2 , deg = True ) :
"""Calculate the angle between two vectors
: param v1 : coordinates of vector v1
: param v2 : coordinates of vector v2
: returns : angle in degree or rad""" | if np . array_equal ( v1 , v2 ) :
return 0.0
dm = np . dot ( v1 , v2 )
cm = np . linalg . norm ( v1 ) * np . linalg . norm ( v2 )
angle = np . arccos ( round ( dm / cm , 10 ) )
# Round here to prevent floating point errors
return np . degrees ( [ angle , ] ) [ 0 ] if deg else angle |
def __apply ( self , migration = None , run_all = False ) :
"""If a migration is supplied , runs that migration and appends to state .
If run _ all = = True , runs all migrations .
Raises a ValueError if neither " migration " nor " run _ all " are provided .""" | out = StringIO ( )
trace = None
migrate_kwargs = { 'interactive' : False , 'stdout' : out , 'database' : self . _database_name , }
if migration is not None :
migrate_kwargs . update ( { 'app_label' : migration [ 0 ] , 'migration_name' : migration [ 1 ] , } )
elif not run_all :
raise ValueError ( 'Either a migra... |
def _query ( self , x , result ) :
'''Same as self . query , but uses a provided list to accumulate results into .''' | if self . single_interval is None : # Empty
return
elif self . single_interval != 0 : # Single interval , just check whether x is in it
if self . single_interval [ 0 ] <= x < self . single_interval [ 1 ] :
result . append ( self . single_interval )
elif x < self . center : # Normal tree , query point to... |
def run ( self , args = None ) :
"""Parse comand line arguments / flags and run program""" | args = args or self . parser . parse_args ( )
super ( Program , self ) . run ( args )
# Read configuration file if any
if args . config is not None :
filepath = args . config
self . config . read ( filepath )
# Start workers then wait until they finish work
[ w . start ( ) for w in self . workers ]
[ w . join (... |
def path_exists ( self , path ) :
"""Does the API - style path ( directory ) actually exist ?
Parameters
path : string
The path to check . This is an API path ( ` / ` separated ,
relative to base notebook - dir ) .
Returns
exists : bool
Whether the path is indeed a directory .""" | path = path . strip ( '/' )
if path != '' :
spec = { 'path' : path }
count = self . _connect_collection ( self . notebook_collection ) . find ( spec ) . count ( )
else :
count = 1
return count > 0 |
def slugs_navigation_encode ( self , u_m , phi_c , theta_c , psiDot_c , ay_body , totalDist , dist2Go , fromWP , toWP , h_c ) :
'''Data used in the navigation algorithm .
u _ m : Measured Airspeed prior to the nav filter in m / s ( float )
phi _ c : Commanded Roll ( float )
theta _ c : Commanded Pitch ( float... | return MAVLink_slugs_navigation_message ( u_m , phi_c , theta_c , psiDot_c , ay_body , totalDist , dist2Go , fromWP , toWP , h_c ) |
def __rst2graph ( self , rs3_xml_tree ) :
"""Reads an RST tree ( from an ElementTree representation of an RS3
XML file ) and adds all segments ( nodes representing text ) and
groups ( nonterminal nodes in an RST tree ) as well as the
relationships that hold between them ( typed edges ) to this
RSTGraph .
... | doc_root = rs3_xml_tree . getroot ( )
for segment in doc_root . iter ( 'segment' ) :
self . __add_segment ( segment )
for group in doc_root . iter ( 'group' ) :
self . __add_group ( group ) |
def _adjust_log_file_override ( overrides , default_log_file ) :
'''Adjusts the log _ file based on the log _ dir override''' | if overrides . get ( 'log_dir' ) : # Adjust log _ file if a log _ dir override is introduced
if overrides . get ( 'log_file' ) :
if not os . path . isabs ( overrides [ 'log_file' ] ) : # Prepend log _ dir if log _ file is relative
overrides [ 'log_file' ] = os . path . join ( overrides [ 'log_di... |
def persist ( arg , depth = Ellipsis , on_mutable = None ) :
'''persist ( x ) yields a persistent version of x if possible , or yields x itself .
The transformations performed by persist ( x ) are as follows :
* If x is an immutable object , yields x . persist ( )
* If x is a set , yield a frozenset of of per... | from . immutable import ( is_imm , imm_copy )
# Parse the on _ mutable argument
if on_mutable is None :
on_mutable = lambda x : x
elif on_mutable == 'error' :
def _raise ( x ) :
raise ValueError ( 'non-persistable: %s' % x )
on_mutable = _raise
if depth in ( None , Ellipsis ) :
depth_next = dept... |
def verify ( self ) -> None :
"""Raises a | RuntimeError | if at least one of the required values
of a | Variable | object is | None | or | numpy . nan | . The descriptor
` mask ` defines , which values are considered to be necessary .
Example on a 0 - dimensional | Variable | :
> > > from hydpy . core . va... | nmbnan : int = numpy . sum ( numpy . isnan ( numpy . array ( self . value ) [ self . mask ] ) )
if nmbnan :
if nmbnan == 1 :
text = 'value has'
else :
text = 'values have'
raise RuntimeError ( f'For variable {objecttools.devicephrase(self)}, ' f'{nmbnan} required {text} not been set yet.' ) |
def _class_tags ( cls ) : # pylint : disable = no - self - argument
"""Collect the tags from all base classes .""" | class_tags = set ( )
for base in cls . mro ( ) [ 1 : ] : # pylint : disable = no - member
class_tags . update ( getattr ( base , '_class_tags' , set ( ) ) )
return class_tags |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.