signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def insert_many ( self , it ) :
"""Inserts a collection of objects into the table .""" | unique_indexes = self . _uniqueIndexes
# [ ind for ind in self . _ indexes . values ( ) if ind . is _ unique ]
NO_SUCH_ATTR = object ( )
new_objs = list ( it )
if unique_indexes :
for ind in unique_indexes :
ind_attr = ind . attr
new_keys = dict ( ( getattr ( obj , ind_attr , NO_SUCH_ATTR ) , obj ) ... |
def insert ( self , doc_or_docs , manipulate = True , safe = True , check_keys = True , callback = None , ** kwargs ) :
"""Insert a document ( s ) into this collection .
If ` manipulate ` is set , the document ( s ) are manipulated using
any : class : ` ~ pymongo . son _ manipulator . SONManipulator ` instances... | if not isinstance ( safe , bool ) :
raise TypeError ( "safe must be an instance of bool" )
docs = doc_or_docs
# return _ one = False
if isinstance ( docs , dict ) : # return _ one = True
docs = [ docs ]
# if manipulate :
# docs = [ self . _ _ database . _ fix _ incoming ( doc , self ) for doc in docs ]
self . _... |
def parse_changes ( json ) :
"""Gets price changes from JSON
Args :
json : JSON data as a list of dict dates , where the keys are
the raw market statistics .
Returns :
List of floats of price changes between entries in JSON .""" | changes = [ ]
dates = len ( json )
for date in range ( 1 , dates ) :
last_close = json [ date - 1 ] [ 'close' ]
now_close = json [ date ] [ 'close' ]
changes . append ( now_close - last_close )
logger . debug ( 'Market Changes (from JSON):\n{0}' . format ( changes ) )
return changes |
def delete_job ( job_id , connection = None ) :
"""Deletes a job .
: param job _ id : unique identifier for this job
> > > delete _ job ( ' http : / / example . com / test ' )""" | if connection is None :
connection = r
with connection . pipeline ( ) as pipe :
pipe . delete ( job_key ( job_id ) )
pipe . zrem ( REDIS_KEY , job_id )
pipe . execute ( ) |
def parse ( self , text , fn = None ) :
"""Parse the Mapfile""" | if PY2 and not isinstance ( text , unicode ) : # specify Unicode for Python 2.7
text = unicode ( text , 'utf-8' )
if self . expand_includes :
text = self . load_includes ( text , fn = fn )
try :
self . _comments [ : ] = [ ]
# clear any comments from a previous parse
tree = self . lalr . parse ( text... |
def publishItems ( self , items_info ) :
"""Publishes a list of items .
Args :
items _ info ( list ) : A list of JSON configuration items to publish .
Returns :
list : A list of results from : py : meth : ` arcrest . manageorg . _ content . User . addItem ` .""" | if self . securityhandler is None :
print ( "Security handler required" )
return
itemInfo = None
item_results = None
item_info = None
admin = None
try :
admin = arcrest . manageorg . Administration ( securityHandler = self . _securityHandler )
item_results = [ ]
for item_info in items_info :
... |
def absolute_magnitude ( distance_modulus , g , r , prob = None ) :
"""Calculate the absolute magnitude from a set of bands""" | V = g - 0.487 * ( g - r ) - 0.0249
flux = np . sum ( 10 ** ( - ( V - distance_modulus ) / 2.5 ) )
Mv = - 2.5 * np . log10 ( flux )
return Mv |
def __start_waiting_for_events ( self ) :
'''This waits until the whole chain of callback methods triggered by
" trigger _ connection _ to _ rabbit _ etc ( ) " has finished , and then starts
waiting for publications .
This is done by starting the ioloop .
Note : In the pika usage example , these things are ... | # Start ioloop if connection object ready :
if self . thread . _connection is not None :
try :
logdebug ( LOGGER , 'Starting ioloop...' )
logtrace ( LOGGER , 'ioloop is owned by connection %s...' , self . thread . _connection )
# Tell the main thread that we ' re now open for events .
... |
def make_compute_file ( self ) :
"""Make the compute file from the self . vardict and self . vardictformat""" | string = ""
try :
vardict_items = self . vardict . iteritems ( )
except AttributeError :
vardict_items = self . vardict . items ( )
for key , val in vardict_items : # get default
default_format = get_default_format ( val )
string_format = "\\newcommand{{\\{}}}{{" + self . vardictformat . get ( key , def... |
def send_frame ( self , frame ) :
"""Send the data frame .
frame : frame data created by ABNF . create _ frame
> > > ws = create _ connection ( " ws : / / echo . websocket . org / " )
> > > frame = ABNF . create _ frame ( " Hello " , ABNF . OPCODE _ TEXT )
> > > ws . send _ frame ( frame )
> > > cont _ fr... | if self . get_mask_key :
frame . get_mask_key = self . get_mask_key
data = frame . format ( )
length = len ( data )
trace ( "send: " + repr ( data ) )
with self . lock :
while data :
l = self . _send ( data )
data = data [ l : ]
return length |
def _srels_for ( phys_reader , source_uri ) :
"""Return | _ SerializedRelationships | instance populated with
relationships for source identified by * source _ uri * .""" | rels_xml = phys_reader . rels_xml_for ( source_uri )
return _SerializedRelationships . load_from_xml ( source_uri . baseURI , rels_xml ) |
def install ( pkg , channel = None , refresh = False ) :
'''Install the specified snap package from the specified channel .
Returns a dictionary of " result " and " output " .
pkg
The snap package name
channel
Optional . The snap channel to install from , eg " beta "
refresh : False
If True , use " sn... | args = [ ]
ret = { 'result' : None , 'output' : "" }
if refresh :
cmd = 'refresh'
else :
cmd = 'install'
if channel :
args . append ( '--channel=' + channel )
try : # Try to run it , merging stderr into output
ret [ 'output' ] = subprocess . check_output ( [ SNAP_BINARY_NAME , cmd , pkg ] + args , stder... |
def _set_vc_peer_state ( self , v , load = False ) :
"""Setter method for vc _ peer _ state , mapped from YANG variable / vc _ peer _ state ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ vc _ peer _ state is considered as a private
method . Backends loo... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = vc_peer_state . vc_peer_state , is_container = 'container' , presence = False , yang_name = "vc-peer-state" , rest_name = "vc-peer-state" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods ,... |
def count_vowels ( word : str ) -> int :
"""This function counts the number of vowels in the provided string .
' a ' , ' e ' , ' i ' , ' o ' , ' u ' and ' y ' ( if it ' s at the end of the word ) are considered vowels .
: param word : The word in which vowels are to be counted
: type word : str
: return : T... | word = word . lower ( )
vowels = "aeiou"
count = sum ( 1 for letter in word if letter in vowels )
if word . endswith ( 'y' ) :
count += 1
return count |
def _validate_file_format ( self , file_format ) :
"""Validates file format , raising error if invalid .""" | if file_format not in self . valid_file_formats :
raise InvalidFileFormatError ( "{} is not a valid file format" . format ( file_format ) )
return file_format |
def write_metadata ( self , fp ) :
"""Adds data to the metadata that ' s written .
Parameters
fp : pycbc . inference . io . BaseInferenceFile instance
The inference file to write to .""" | super ( BaseDataModel , self ) . write_metadata ( fp )
fp . write_stilde ( self . data ) |
def _stash_user ( cls , user ) :
"""Now , be aware , the following is quite ugly , let me explain :
Even if the user credentials match , the authentication can fail because
Django ' s default ModelBackend calls user _ can _ authenticate ( ) , which
checks ` is _ active ` . Now , earlier versions of allauth di... | global _stash
ret = getattr ( _stash , 'user' , None )
_stash . user = user
return ret |
def GetEventTaggingRules ( self ) :
"""Retrieves the event tagging rules from the tagging file .
Returns :
dict [ str , FilterObject ] : tagging rules , that consists of one or more
filter objects per label .
Raises :
TaggingFileError : if a filter expression cannot be compiled .""" | tagging_rules = { }
label_name = None
with io . open ( self . _path , 'r' , encoding = 'utf-8' ) as tagging_file :
for line in tagging_file . readlines ( ) :
line = line . rstrip ( )
stripped_line = line . lstrip ( )
if not stripped_line or stripped_line [ 0 ] == '#' :
continue
... |
def format_message ( self , msg ) :
"""format message .""" | return { 'timestamp' : int ( msg . created * 1000 ) , 'message' : self . format ( msg ) , 'stream' : self . log_stream or msg . name , 'group' : self . log_group } |
def emphasis ( node ) :
"""An italicized section""" | o = nodes . emphasis ( )
for n in MarkDown ( node ) :
o += n
return o |
def get_anchor ( self ) :
"""Find anchor variable with highest sum of dependence with the rest .""" | temp = np . empty ( [ self . n_nodes , 2 ] )
temp [ : , 0 ] = np . arange ( self . n_nodes , dtype = int )
temp [ : , 1 ] = np . sum ( abs ( self . tau_matrix ) , 1 )
anchor = int ( temp [ 0 , 0 ] )
return anchor |
def get_provider ( self , provider ) :
"""Get instance of the OAuth client for this provider .""" | if self . provider is not None :
return self . provider
return providers . by_id ( provider ) |
def write_this ( func ) :
"""Decorator that writes the bytes to the wire""" | @ wraps ( func )
def wrapper ( self , * args , ** kwargs ) :
byte_array = func ( self , * args , ** kwargs )
self . write_bytes ( byte_array )
return wrapper |
def run ( self , batch : Batch , train : bool = False , stream : StreamWrapper = None ) -> Batch :
"""Run all the models in - order and return accumulated outputs .
N - th model is fed with the original inputs and outputs of all the models that were run before it .
. . warning : :
: py : class : ` Sequence ` ... | if train :
raise ValueError ( 'Ensemble model cannot be trained.' )
self . _load_models ( )
# run all the models in - order
current_batch = dict ( copy . deepcopy ( batch ) )
for model in self . _models :
current_batch . update ( model . run ( current_batch , False , None ) )
return { key : current_batch [ key ... |
def _physical_column ( self , cube , column_name ) :
"""Return the SQLAlchemy Column object matching a given , possibly
qualified , column name ( i . e . : ' table . column ' ) . If no table is named ,
the fact table is assumed .""" | table_name = self . model . fact_table_name
if '.' in column_name :
table_name , column_name = column_name . split ( '.' , 1 )
table = cube . _load_table ( table_name )
if column_name not in table . columns :
raise BindingException ( 'Column %r does not exist on table %r' % ( column_name , table_name ) , table ... |
def load_dsdl ( * paths , ** args ) :
"""Loads the DSDL files under the given directory / directories , and creates
types for each of them in the current module ' s namespace .
If the exclude _ dist argument is not present , or False , the DSDL
definitions installed with this package will be loaded first .
... | global DATATYPES , TYPENAMES
paths = list ( paths )
# Try to prepend the built - in DSDL files
# TODO : why do we need try / except here ?
# noinspection PyBroadException
try :
if not args . get ( "exclude_dist" , None ) :
dsdl_path = pkg_resources . resource_filename ( __name__ , "dsdl_files" )
# @... |
def _update_attachments_to_cloud ( self ) :
"""Push new , unsaved attachments to the cloud and remove removed
attachments . This method should not be called for non draft messages .""" | url = self . build_url ( self . _endpoints . get ( 'attachments' ) . format ( id = self . _parent . object_id ) )
# ! potentially several api requests can be made by this method .
for attachment in self . __attachments :
if attachment . on_cloud is False : # upload attachment :
response = self . _parent . c... |
def get_custom_fields ( self , search = None , start = 1 , limit = 50 ) :
"""Get custom fields . Evaluated on 7.12
: param search : str
: param start : long Default : 1
: param limit : int Default : 50
: return :""" | url = 'rest/api/2/customFields'
params = { }
if search :
params [ 'search' ] = search
if start :
params [ 'startAt' ] = start
if limit :
params [ 'maxResults' ] = limit
return self . get ( url , params = params ) |
def get_subcellular_locations ( self , entry ) :
"""get list of models . SubcellularLocation object from XML node entry
: param entry : XML node entry
: return : list of : class : ` pyuniprot . manager . models . SubcellularLocation ` object""" | subcellular_locations = [ ]
query = './comment/subcellularLocation/location'
sls = { x . text for x in entry . iterfind ( query ) }
for sl in sls :
if sl not in self . subcellular_locations :
self . subcellular_locations [ sl ] = models . SubcellularLocation ( location = sl )
subcellular_locations . app... |
def change_course ( self , select_courses = None , delete_courses = None ) :
"""修改个人的课程
@ structure [ { ' 费用 ' : float , ' 教学班号 ' : str , ' 课程名称 ' : str , ' 课程代码 ' : str , ' 学分 ' : float , ' 课程类型 ' : str } ]
: param select _ courses : 形如 ` ` [ { ' kcdm ' : ' 9900039X ' , ' jxbhs ' : { ' 0001 ' , ' 0002 ' } } ] ... | # 框架重构后调整接口的调用
t = self . get_system_status ( )
if t [ '当前轮数' ] is None :
raise ValueError ( '当前为 %s,选课系统尚未开启' , t [ '当前学期' ] )
if not ( select_courses or delete_courses ) :
raise ValueError ( 'select_courses, delete_courses 参数不能都为空!' )
# 参数处理
select_courses = select_courses or [ ]
delete_courses = { l . upper ... |
def _audience_condition_deserializer ( obj_dict ) :
"""Deserializer defining how dict objects need to be decoded for audience conditions .
Args :
obj _ dict : Dict representing one audience condition .
Returns :
List consisting of condition key with corresponding value , type and match .""" | return [ obj_dict . get ( 'name' ) , obj_dict . get ( 'value' ) , obj_dict . get ( 'type' ) , obj_dict . get ( 'match' ) ] |
def convert_unicode_field ( string ) :
"""Convert a Unicode field into the corresponding list of Unicode strings .
The ( input ) Unicode field is a Unicode string containing
one or more Unicode codepoints ( ` ` xxxx ` ` or ` ` U + xxxx ` ` or ` ` xxxx _ yyyy ` ` ) ,
separated by a space .
: param str string... | values = [ ]
for codepoint in [ s for s in string . split ( DATA_FILE_CODEPOINT_SEPARATOR ) if ( s != DATA_FILE_VALUE_NOT_AVAILABLE ) and ( len ( s ) > 0 ) ] :
values . append ( u"" . join ( [ hex_to_unichr ( c ) for c in codepoint . split ( DATA_FILE_CODEPOINT_JOINER ) ] ) )
return values |
def rhypo_to_rjb ( rhypo , mag ) :
"""Converts hypocentral distance to an equivalent Joyner - Boore distance
dependent on the magnitude""" | epsilon = rhypo - ( 4.853 + 1.347E-6 * ( mag ** 8.163 ) )
rjb = np . zeros_like ( rhypo )
idx = epsilon >= 3.
rjb [ idx ] = np . sqrt ( ( epsilon [ idx ] ** 2. ) - 9.0 )
rjb [ rjb < 0.0 ] = 0.0
return rjb |
def get_requires ( ) :
"""Read requirements . txt .""" | requirements = open ( "requirements.txt" , "r" ) . read ( )
return list ( filter ( lambda x : x != "" , requirements . split ( ) ) ) |
def _authenticate_plain ( credentials , sock_info ) :
"""Authenticate using SASL PLAIN ( RFC 4616)""" | source = credentials . source
username = credentials . username
password = credentials . password
payload = ( '\x00%s\x00%s' % ( username , password ) ) . encode ( 'utf-8' )
cmd = SON ( [ ( 'saslStart' , 1 ) , ( 'mechanism' , 'PLAIN' ) , ( 'payload' , Binary ( payload ) ) , ( 'autoAuthorize' , 1 ) ] )
sock_info . comma... |
def _call_marginalizevlos ( self , o , ** kwargs ) :
"""Call the DF , marginalizing over line - of - sight velocity""" | # Get d , l , vperp
l = o . ll ( obs = [ 1. , 0. , 0. ] , ro = 1. ) * _DEGTORAD
vperp = o . vll ( ro = 1. , vo = 1. , obs = [ 1. , 0. , 0. , 0. , 0. , 0. ] )
R = o . R ( use_physical = False )
phi = o . phi ( use_physical = False )
# Get local circular velocity , projected onto the perpendicular
# direction
vcirc = R *... |
def normalize_whitespace ( self , value ) :
"""Normalizes whitespace ; called if ` ` ignore _ ws ` ` is true .""" | if isinstance ( value , unicode ) :
return u" " . join ( x for x in re . split ( r'\s+' , value , flags = re . UNICODE ) if len ( x ) )
else :
return " " . join ( value . split ( ) ) |
def set_peers ( * peers , ** options ) :
'''Configures a list of NTP peers on the device .
: param peers : list of IP Addresses / Domain Names
: param test ( bool ) : discard loaded config . By default ` ` test ` ` is False
( will not dicard the changes )
: commit commit ( bool ) : commit loaded config . By... | test = options . pop ( 'test' , False )
commit = options . pop ( 'commit' , True )
return __salt__ [ 'net.load_template' ] ( 'set_ntp_peers' , peers = peers , test = test , commit = commit , inherit_napalm_device = napalm_device ) |
def from_python_file ( cls , python_file , lambdas_path , json_filename : str , stem : str ) :
"""Builds GrFN object from Python file .""" | with open ( python_file , "r" ) as f :
pySrc = f . read ( )
return cls . from_python_src ( pySrc , lambdas_path , json_filename , stem ) |
def plot_pointings ( self , pointings = None ) :
"""Plot pointings on canavs""" | if pointings is None :
pointings = self . pointings
i = 0
for pointing in pointings :
items = [ ]
i = i + 1
label = { }
label [ 'text' ] = pointing [ 'label' ] [ 'text' ]
for ccd in numpy . radians ( pointing [ "camera" ] . geometry ) :
if len ( ccd ) == 4 :
ccd = numpy . rad... |
def encrypt ( self , value ) :
"""Encrypt session data .""" | timestamp = str ( int ( time . time ( ) ) )
value = base64 . b64encode ( value . encode ( self . encoding ) )
signature = create_signature ( self . secret , value + timestamp . encode ( ) , encoding = self . encoding )
return "|" . join ( [ value . decode ( self . encoding ) , timestamp , signature ] ) |
def ifind_first_object ( self , ObjectClass , ** kwargs ) :
"""Retrieve the first object of type ` ` ObjectClass ` ` ,
matching the specified filters in ` ` * * kwargs ` ` - - case insensitive .
| If USER _ IFIND _ MODE is ' nocase _ collation ' this method maps to find _ first _ object ( ) .
| If USER _ IFIN... | # Call regular find ( ) if USER _ IFIND _ MODE is nocase _ collation
if self . user_manager . USER_IFIND_MODE == 'nocase_collation' :
return self . find_first_object ( ObjectClass , ** kwargs )
# Convert each name / value pair in ' kwargs ' into a filter
query = ObjectClass . query
for field_name , field_value in k... |
def get_all_tags ( self , item ) :
"""Get all tags of an item
: param item : an item
: type item : Item
: return : list of tags
: rtype : list""" | all_tags = item . get_templates ( )
for template_id in item . templates :
template = self . templates [ template_id ]
all_tags . append ( template . name )
all_tags . extend ( self . get_all_tags ( template ) )
return list ( set ( all_tags ) ) |
def edges_unique ( self ) :
"""The unique edges of the mesh .
Returns
edges _ unique : ( n , 2 ) int
Vertex indices for unique edges""" | unique , inverse = grouping . unique_rows ( self . edges_sorted )
edges_unique = self . edges_sorted [ unique ]
# edges _ unique will be added automatically by the decorator
# additional terms generated need to be added to the cache manually
self . _cache [ 'edges_unique_idx' ] = unique
self . _cache [ 'edges_unique_in... |
def sync_update_heaters ( self ) :
"""Request data .""" | loop = asyncio . get_event_loop ( )
task = loop . create_task ( self . update_heaters ( ) )
loop . run_until_complete ( task ) |
def set_buzzer_and_led_to_active ( self , duration_in_ms = 300 ) :
"""Turn on buzzer and set LED to red only . The timeout here must exceed
the total buzzer / flash duration defined in bytes 5-8.""" | duration_in_tenths_of_second = min ( duration_in_ms / 100 , 255 )
timeout_in_seconds = ( duration_in_tenths_of_second + 1 ) / 10.0
data = "FF00400D04{:02X}000101" . format ( duration_in_tenths_of_second )
self . ccid_xfr_block ( bytearray . fromhex ( data ) , timeout = timeout_in_seconds ) |
def verify ( self , digest , signature , ** kwargs ) :
"""Verifies given signature on given digest
Returns True if Ok , False if don ' t match
Keyword arguments allows to set algorithm - specific
parameters""" | ctx = libcrypto . EVP_PKEY_CTX_new ( self . key , None )
if ctx is None :
raise PKeyError ( "Initailizing verify context" )
if libcrypto . EVP_PKEY_verify_init ( ctx ) < 1 :
raise PKeyError ( "verify_init" )
self . _configure_context ( ctx , kwargs )
ret = libcrypto . EVP_PKEY_verify ( ctx , signature , len ( s... |
def get_sourced_from ( entry ) :
"""Get a list of values from the source _ from attribute""" | sourced_from = 'http://worldmodelers.com/DataProvenance#sourced_from'
if sourced_from in entry :
values = entry [ sourced_from ]
values = [ i [ '@id' ] for i in values ]
return values |
def _set_up_savefolder ( self ) :
"""Create catalogs for different file output to clean up savefolder .""" | if not os . path . isdir ( self . cells_path ) :
os . mkdir ( self . cells_path )
if not os . path . isdir ( self . figures_path ) :
os . mkdir ( self . figures_path )
if not os . path . isdir ( self . populations_path ) :
os . mkdir ( self . populations_path ) |
def keyPressEvent ( self , keyEvent ) :
"""Insert the character at the current cursor position .
This method also adds another undo - object to the undo - stack .""" | undoObj = UndoSelfInsert ( self , keyEvent . text ( ) )
self . qteUndoStack . push ( undoObj ) |
def netconf_session_end_username ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
netconf_session_end = ET . SubElement ( config , "netconf-session-end" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-notifications" )
username = ET . SubElement ( netconf_session_end , "username" )
username . text = kwargs . pop ( 'username' )
callback = kwargs . pop ( 'callback... |
def _teardown_log_prefix ( self ) :
"""Tear down custom warning notification .""" | self . _logger_console_fmtter . prefix = ''
self . _logger_console_fmtter . plugin_id = ''
self . _logger_file_fmtter . prefix = ' '
self . _logger_file_fmtter . plugin_id = '' |
def is_valid_ipv6 ( ip ) :
"""Return True if given ip is a valid IPv6 address .""" | # XXX this is not complete : check ipv6 and ipv4 semantics too here
if not ( _ipv6_re . match ( ip ) or _ipv6_ipv4_re . match ( ip ) or _ipv6_abbr_re . match ( ip ) or _ipv6_ipv4_abbr_re . match ( ip ) ) :
return False
return True |
def parse_mailto ( mailto_str ) :
"""Interpret mailto - string
: param mailto _ str : the string to interpret . Must conform to : rfc : 2368.
: type mailto _ str : str
: return : the header fields and the body found in the mailto link as a tuple
of length two
: rtype : tuple ( dict ( str - > list ( str ) ... | if mailto_str . startswith ( 'mailto:' ) :
import urllib . parse
to_str , parms_str = mailto_str [ 7 : ] . partition ( '?' ) [ : : 2 ]
headers = { }
body = u''
to = urllib . parse . unquote ( to_str )
if to :
headers [ 'To' ] = [ to ]
for s in parms_str . split ( '&' ) :
key ... |
def _create_and_rotate_coordinate_arrays ( self , x , y , orientation ) :
"""Create pattern matrices from x and y vectors , and rotate them
to the specified orientation .""" | # Using this two - liner requires that x increase from left to
# right and y decrease from left to right ; I don ' t think it
# can be rewritten in so little code otherwise - but please
# prove me wrong .
pattern_y = np . subtract . outer ( np . cos ( orientation ) * y , np . sin ( orientation ) * x )
pattern_x = np . ... |
def _compute_betas ( y , x ) :
"""compute MLE coefficients using iwls routine
Methods : p189 , Iteratively ( Re ) weighted Least Squares ( IWLS ) ,
Fotheringham , A . S . , Brunsdon , C . , & Charlton , M . ( 2002 ) .
Geographically weighted regression : the analysis of spatially varying relationships .""" | xT = x . T
xtx = spdot ( xT , x )
xtx_inv = la . inv ( xtx )
xtx_inv = sp . csr_matrix ( xtx_inv )
xTy = spdot ( xT , y , array_out = False )
betas = spdot ( xtx_inv , xTy )
return betas |
def add_to_bashrc ( self , line , match_regexp = None , note = None , loglevel = logging . DEBUG ) :
"""Takes care of adding a line to everyone ' s bashrc
( / etc / bash . bashrc ) .
@ param line : Line to add .
@ param match _ regexp : See add _ line _ to _ file ( )
@ param note : See send ( )
@ return :... | shutit = self . shutit
shutit . handle_note ( note )
if not shutit_util . check_regexp ( match_regexp ) :
shutit . fail ( 'Illegal regexp found in add_to_bashrc call: ' + match_regexp )
# pragma : no cover
if self . whoami ( ) == 'root' :
shutit . add_line_to_file ( line , '/root/.bashrc' , match_regexp = m... |
def get_longest_orf ( orfs ) :
"""Find longest ORF from the given list of ORFs .""" | sorted_orf = sorted ( orfs , key = lambda x : len ( x [ 'sequence' ] ) , reverse = True ) [ 0 ]
return sorted_orf |
def set ( self , instance , value , ** kwargs ) :
"""Adds the value to the existing text stored in the field ,
along with a small divider showing username and date of this entry .""" | if not value :
return
value = value . strip ( )
date = DateTime ( ) . rfc822 ( )
user = getSecurityManager ( ) . getUser ( )
username = user . getUserName ( )
divider = "=== {} ({})" . format ( date , username )
existing_remarks = instance . getRawRemarks ( )
remarks = '\n' . join ( [ divider , value , existing_rem... |
def _determine_validator_type ( self , data_type , value , has_default ) :
"""Returns validator string for given data type , else None .""" | data_type , nullable = unwrap_nullable ( data_type )
validator = None
if is_list_type ( data_type ) :
item_validator = self . _determine_validator_type ( data_type . data_type , value , False )
item_validator = item_validator if item_validator else 'nil'
validator = '{}:{}' . format ( fmt_validator ( data_t... |
def set_contents_from_file ( self , fp , headers = None , replace = True , cb = None , num_cb = 10 , policy = None , md5 = None , reduced_redundancy = False , query_args = None , encrypt_key = False , callback = None ) :
"""Store an object in S3 using the name of the Key object as the
key in S3 and the contents o... | provider = self . bucket . connection . provider
if headers is None :
headers = { }
if policy :
headers [ provider . acl_header ] = policy
if encrypt_key :
headers [ provider . server_side_encryption_header ] = 'AES256'
if reduced_redundancy :
self . storage_class = 'REDUCED_REDUNDANCY'
if provider ... |
def alias_ip_address ( ip_address , interface , aws = False ) :
"""Adds an IP alias to a specific interface
Adds an ip address as an alias to the specified interface on
Linux systems .
: param ip _ address : ( str ) IP address to set as an alias
: param interface : ( str ) The interface number or full devic... | log = logging . getLogger ( mod_logger + '.alias_ip_address' )
# Validate args
if not isinstance ( ip_address , basestring ) :
msg = 'ip_address argument is not a string'
log . error ( msg )
raise TypeError ( msg )
# Validate the IP address
if not validate_ip_address ( ip_address ) :
msg = 'The provided... |
def generate_support_dump ( self , information , timeout = - 1 ) :
"""Generates a support dump for the logical enclosure with the specified ID . A logical enclosure support dump
includes content for logical interconnects associated with that logical enclosure . By default , it also contains
appliance support du... | uri = "{}/support-dumps" . format ( self . data [ "uri" ] )
return self . _helper . create ( information , uri = uri , timeout = timeout ) |
def _get_master_uri ( master_ip , master_port , source_ip = None , source_port = None ) :
'''Return the ZeroMQ URI to connect the Minion to the Master .
It supports different source IP / port , given the ZeroMQ syntax :
/ / Connecting using a IP address and bind to an IP address
rc = zmq _ connect ( socket , ... | from salt . utils . zeromq import ip_bracket
master_uri = 'tcp://{master_ip}:{master_port}' . format ( master_ip = ip_bracket ( master_ip ) , master_port = master_port )
if source_ip or source_port :
if LIBZMQ_VERSION_INFO >= ( 4 , 1 , 6 ) and ZMQ_VERSION_INFO >= ( 16 , 0 , 1 ) : # The source : port syntax for Zero... |
def raw_corpus_chrf ( hypotheses : Iterable [ str ] , references : Iterable [ str ] ) -> float :
"""Simple wrapper around sacreBLEU ' s chrF implementation , without tokenization .
: param hypotheses : Hypotheses stream .
: param references : Reference stream .
: return : chrF score as float between 0 and 1."... | return sacrebleu . corpus_chrf ( hypotheses , references , order = sacrebleu . CHRF_ORDER , beta = sacrebleu . CHRF_BETA , remove_whitespace = True ) |
def doIt ( rh ) :
"""Perform the requested function by invoking the subfunction handler .
Input :
Request Handle
Output :
Request Handle updated with parsed input .
Return code - 0 : ok , non - zero : error""" | rh . printSysLog ( "Enter cmdVM.doIt" )
# Show the invocation parameters , if requested .
if 'showParms' in rh . parms and rh . parms [ 'showParms' ] is True :
rh . printLn ( "N" , "Invocation parameters: " )
rh . printLn ( "N" , " Routine: cmdVM." + str ( subfuncHandler [ rh . subfunction ] [ 0 ] ) + "(reqHan... |
def show_big_file ( dir_path , threshold ) :
"""Print all file path that file size greater and equal than
` ` # threshold ` ` .""" | fc = FileCollection . from_path_by_size ( dir_path , min_size = threshold )
fc . sort_by ( "size_on_disk" )
lines = list ( )
lines . append ( "Results:" )
for winfile in fc . iterfiles ( ) :
lines . append ( " %s - %s" % ( string_SizeInBytes ( winfile . size_on_disk ) , winfile ) )
lines . append ( "Above are file... |
def project ( vx , vy ) :
"""Project the velocity field to be approximately mass - conserving ,
using a few iterations of Gauss - Seidel .""" | p = np . zeros ( vx . shape )
h = 1.0 / vx . shape [ 0 ]
div = - 0.5 * h * ( np . roll ( vx , - 1 , axis = 0 ) - np . roll ( vx , 1 , axis = 0 ) + np . roll ( vy , - 1 , axis = 1 ) - np . roll ( vy , 1 , axis = 1 ) )
for k in range ( 10 ) :
p = ( div + np . roll ( p , 1 , axis = 0 ) + np . roll ( p , - 1 , axis = 0... |
def export_tree ( lookup , tree , path ) :
"""Exports the given tree object to path .
: param lookup : Function to retrieve objects for SHA1 hashes .
: param tree : Tree to export .
: param path : Output path .""" | FILE_PERM = S_IRWXU | S_IRWXG | S_IRWXO
for name , mode , hexsha in tree . iteritems ( ) :
dest = os . path . join ( path , name )
if S_ISGITLINK ( mode ) :
log . error ( 'Ignored submodule {}; submodules are not yet supported.' . format ( name ) )
# raise ValueError ( ' Does not support submodu... |
def density_matrix_from_state_vector ( state : Sequence , indices : Iterable [ int ] = None ) -> np . ndarray :
r"""Returns the density matrix of the wavefunction .
Calculate the density matrix for the system on the given qubit
indices , with the qubits not in indices that are present in state
traced out . If... | n_qubits = _validate_num_qubits ( state )
if indices is None :
return np . outer ( state , np . conj ( state ) )
indices = list ( indices )
_validate_indices ( n_qubits , indices )
state = np . asarray ( state ) . reshape ( ( 2 , ) * n_qubits )
sum_inds = np . array ( range ( n_qubits ) )
sum_inds [ indices ] += n_... |
def build_epsf ( self , stars , init_epsf = None ) :
"""Iteratively build an ePSF from star cutouts .
Parameters
stars : ` EPSFStars ` object
The stars used to build the ePSF .
init _ epsf : ` EPSFModel ` object , optional
The initial ePSF model . If not input , then the ePSF will be
built from scratch ... | iter_num = 0
center_dist_sq = self . center_accuracy_sq + 1.
centers = stars . cutout_center_flat
n_stars = stars . n_stars
fit_failed = np . zeros ( n_stars , dtype = bool )
dx_dy = np . zeros ( ( n_stars , 2 ) , dtype = np . float )
epsf = init_epsf
dt = 0.
while ( iter_num < self . maxiters and np . max ( center_dis... |
def getLocationRepresentation ( self ) :
"""Get the full population representation of the location layer .""" | activeCells = np . array ( [ ] , dtype = "uint32" )
totalPrevCells = 0
for module in self . L6aModules :
activeCells = np . append ( activeCells , module . getActiveCells ( ) + totalPrevCells )
totalPrevCells += module . numberOfCells ( )
return activeCells |
def visibility ( cls , orb , ** kwargs ) :
"""Visibility from a topocentric frame
see : py : meth : ` Propagator . iter ( ) < beyond . propagators . base . Propagator . iter > `
for description of arguments handling .
Args :
orb ( Orbit ) : Orbit to compute visibility from the station with
Keyword Args : ... | from . . orbits . listeners import stations_listeners , Listener
listeners = kwargs . setdefault ( 'listeners' , [ ] )
events = kwargs . pop ( 'events' , None )
event_classes = tuple ( )
if events : # Handling of the listeners passed in the ' events ' kwarg
# and merging them with the ` listeners ` kwarg
if isinsta... |
def find_matches ( text ) :
r"""Find matching files for text .
For this completer to function in Unix systems , the readline module must not
treat \ and / as delimiters .""" | path = os . path . expanduser ( text )
if os . path . isdir ( path ) and not path . endswith ( '/' ) :
return [ text + '/' ]
pattern = path + '*'
is_implicit_cwd = not ( path . startswith ( '/' ) or path . startswith ( './' ) )
if is_implicit_cwd :
pattern = './' + pattern
rawlist = glob . glob ( pattern )
ret ... |
def as_dict ( self ) :
"""Return all child objects in nested dict .""" | dicts = [ x . as_dict for x in self . children ]
return { '{0} {1}' . format ( self . name , self . value ) : dicts } |
def write_messages ( ax , messages ) :
"""Write text on canvas , usually on the top right corner .""" | tc = "gray"
axt = ax . transAxes
yy = .95
for msg in messages :
ax . text ( .95 , yy , msg , color = tc , transform = axt , ha = "right" )
yy -= .05 |
def _get_removed ( self ) :
"""Manage removed packages by extra options""" | removed , packages = [ ] , [ ]
if "--tag" in self . extra :
for pkg in find_package ( "" , self . meta . pkg_path ) :
for tag in self . binary :
if pkg . endswith ( tag ) :
removed . append ( split_package ( pkg ) [ 0 ] )
packages . append ( pkg )
if not remov... |
def p_rvalue ( self , p ) :
'rvalue : expression' | p [ 0 ] = Rvalue ( p [ 1 ] , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def _parse_row ( row ) :
"""Parses HTML row
: param row : HTML row
: return : list of values in row""" | data = [ ]
labels = HtmlTable . _get_row_tag ( row , "th" )
if labels :
data += labels
columns = HtmlTable . _get_row_tag ( row , "td" )
if columns :
data += columns
return data |
def set_initial_status ( self , response ) :
"""Process first response after initiating long running
operation and set self . status attribute .
: param requests . Response response : initial REST call response .""" | self . _raise_if_bad_http_status_and_method ( response )
if self . _is_empty ( response ) :
self . resource = None
else :
try :
self . resource = self . _deserialize ( response )
except DeserializationError :
self . resource = None
self . set_async_url_if_present ( response )
if response . s... |
def insert ( args ) :
"""% prog insert candidates . bed gaps . bed chrs . fasta unplaced . fasta
Insert scaffolds into assembly .""" | from jcvi . formats . agp import mask , bed
from jcvi . formats . sizes import agp
p = OptionParser ( insert . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 4 :
sys . exit ( not p . print_help ( ) )
candidates , gapsbed , chrfasta , unplacedfasta = args
refinedbed = refine ( [ candidates , gaps... |
def fulfill ( self , value ) :
"""Fulfill the promise with a given value .""" | assert self . _state == self . PENDING
self . _state = self . FULFILLED ;
self . value = value
for callback in self . _callbacks :
try :
callback ( value )
except Exception : # Ignore errors in callbacks
pass
# We will never call these callbacks again , so allow
# them to be garbage collected . ... |
def vserver_servicegroup_add ( v_name , sg_name , ** connection_args ) :
'''Bind a servicegroup to a vserver
CLI Example :
. . code - block : : bash
salt ' * ' netscaler . vserver _ servicegroup _ add ' vserverName ' ' serviceGroupName ' ''' | ret = True
if vserver_servicegroup_exists ( v_name , sg_name , ** connection_args ) :
return False
nitro = _connect ( ** connection_args )
if nitro is None :
return False
vsg = NSLBVServerServiceGroupBinding ( )
vsg . set_name ( v_name )
vsg . set_servicegroupname ( sg_name )
try :
NSLBVServerServiceGroupBi... |
def sync_all ( name , ** kwargs ) :
'''Performs the same task as saltutil . sync _ all module
See : mod : ` saltutil module for full list of options < salt . modules . saltutil > `
. . code - block : : yaml
sync _ everything :
saltutil . sync _ all :
- refresh : True''' | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
if __opts__ [ 'test' ] :
ret [ 'result' ] = None
ret [ 'comment' ] = "saltutil.sync_all would have been run"
return ret
try :
sync_status = __salt__ [ 'saltutil.sync_all' ] ( ** kwargs )
for key , value in sync_status . ite... |
def import_staging ( self , source , staging_start = None , as_qual = False , test_filename = None , test_rater = None ) :
"""Action : import an external sleep staging file .
Parameters
source : str
Name of program where staging was exported . One of ' alice ' ,
' compumedics ' , ' domino ' , ' remlogic ' ,... | if self . annot is None : # remove if buttons are disabled
msg = 'No score file loaded'
self . parent . statusBar ( ) . showMessage ( msg )
lg . info ( msg )
return
if self . parent . info . dataset is None :
msg = 'No dataset loaded'
self . parent . statusBar ( ) . showMessage ( msg )
lg . ... |
def open ( self , path , mode = 'r' ) :
"""Open stream , returning ` ` Stream ` ` object""" | entry = self . find ( path )
if entry is None :
if mode == 'r' :
raise ValueError ( "stream does not exists: %s" % path )
entry = self . create_dir_entry ( path , 'stream' , None )
else :
if not entry . isfile ( ) :
raise ValueError ( "can only open stream type DirEntry's" )
if mode == '... |
def parse_from_iterable ( inputs , server = default_erg_server , params = None , headers = None ) :
"""Request parses for all * inputs * .
Args :
inputs ( iterable ) : sentences to parse
server ( str ) : the url for the server ( the default LOGON server
is used by default )
params ( dict ) : a dictionary ... | client = DelphinRestClient ( server )
for input in inputs :
yield client . parse ( input , params = params , headers = headers ) |
def receive ( self , x , mesh_axis , source_pcoord ) :
"""Collective receive in groups .
Each group contains the processors that differ only in mesh _ axis .
` ` ` python
group _ size = self . shape [ mesh _ axis ] . size
Args :
x : a LaidOutTensor
mesh _ axis : an integer
source _ pcoord : a list of ... | x = x . to_laid_out_tensor ( )
shape = x . tensor_list [ 0 ] . shape
dtype = x . tensor_list [ 0 ] . dtype
def _collective_receive ( tensor_list , device_list ) :
ret = [ ]
for pcoord , device in enumerate ( device_list ) :
with tf . device ( device ) :
if source_pcoord [ pcoord ] is None :
... |
def main ( argString = None ) :
"""The main function of the module . .
Here are the steps for duplicated samples :
1 . Prints the options .
2 . Reads the ` ` map ` ` file to gather marker ' s position
( : py : func : ` readMAP ` ) .
3 . Reads the ` ` tfam ` ` file ( : py : func : ` readTFAM ` ) .
4 . Fi... | # Getting and checking the options
args = parseArgs ( argString )
checkArgs ( args )
logger . info ( "Options used:" )
for key , value in vars ( args ) . iteritems ( ) :
logger . info ( " --{} {}" . format ( key . replace ( "_" , "-" ) , value ) )
# Reading the map file
logger . info ( "Reading MAP file" )
mapF = ... |
def apply ( self , fn , * column_or_columns ) :
"""Apply ` ` fn ` ` to each element or elements of ` ` column _ or _ columns ` ` .
If no ` ` column _ or _ columns ` ` provided , ` fn ` ` is applied to each row .
Args :
` ` fn ` ` ( function ) - - The function to apply .
` ` column _ or _ columns ` ` : Colum... | if not column_or_columns :
return np . array ( [ fn ( row ) for row in self . rows ] )
else :
if len ( column_or_columns ) == 1 and _is_non_string_iterable ( column_or_columns [ 0 ] ) :
warnings . warn ( "column lists are deprecated; pass each as an argument" , FutureWarning )
column_or_columns ... |
def iter_genotypes ( self ) :
"""Iterates on available markers .
Returns :
Genotypes instances .""" | # Seeking at the beginning of the file
self . _impute2_file . seek ( 0 )
# Parsing each lines of the IMPUTE2 file
for i , line in enumerate ( self . _impute2_file ) :
genotypes = self . _parse_impute2_line ( line )
variant_info = None
if self . has_index :
variant_info = self . _impute2_index . iloc... |
def update_multi_precision ( self , index , weight , grad , state ) :
"""Updates the given parameter using the corresponding gradient and state .
Mixed precision version .
Parameters
index : int
The unique index of the parameter into the individual learning
rates and weight decays . Learning rates and wei... | if self . multi_precision and weight . dtype == numpy . float16 : # Wrapper for mixed precision
weight_master_copy = state [ 0 ]
original_state = state [ 1 ]
grad32 = grad . astype ( numpy . float32 )
self . update ( index , weight_master_copy , grad32 , original_state )
cast ( weight_master_copy , ... |
def source_range_tuple ( start , end , nr_var_dict ) :
"""Given a range of source numbers , as well as a dictionary
containing the numbers of each source , returns a dictionary
containing tuples of the start and end index
for each source variable type .""" | starts = np . array ( [ 0 for nr_var in SOURCE_VAR_TYPES . itervalues ( ) ] )
ends = np . array ( [ nr_var_dict [ nr_var ] if nr_var in nr_var_dict else 0 for nr_var in SOURCE_VAR_TYPES . itervalues ( ) ] )
sum_counts = np . cumsum ( ends )
idx = np . arange ( len ( starts ) )
# Find the intervals containing the
# star... |
def execute_notebook ( self , data ) :
"""Execute input notebook and save it to file .
If no output path given , the output will be printed to stdout .
If any errors occur from executing the notebook ' s paragraphs , they will
be displayed in stderr .""" | self . create_notebook ( data )
self . run_notebook ( )
self . wait_for_notebook_to_execute ( )
body = self . get_executed_notebook ( )
err = False
output = [ ]
for paragraph in body [ 'paragraphs' ] :
if 'results' in paragraph and paragraph [ 'results' ] [ 'code' ] == 'ERROR' :
output . append ( paragraph ... |
def describe_ingredient ( self ) :
"""apple . tart apple with vinegar .""" | resp = random . choice ( ingredients )
if random . random ( ) < .2 :
resp = random . choice ( foodqualities ) + " " + resp
if random . random ( ) < .2 :
resp += " with " + self . describe_additive ( )
return resp |
def _print_image ( self , line , size ) :
"""Print formatted image""" | i = 0
cont = 0
buffer = ""
self . _raw ( S_RASTER_N )
buffer = "%02X%02X%02X%02X" % ( ( ( size [ 0 ] / size [ 1 ] ) / 8 ) , 0 , size [ 1 ] , 0 )
self . _raw ( buffer . decode ( 'hex' ) )
buffer = ""
while i < len ( line ) :
hex_string = int ( line [ i : i + 8 ] , 2 )
buffer += "%02X" % hex_string
i += 8
... |
def _generic_binary_op ( self , other , op ) :
"""Perform the method operation specified in the op parameter on the values
within the instance ' s time series values and either another time series
or a constant number value .
: param other : Time series of values or a constant number to use in calculations wi... | output = { }
if isinstance ( other , TimeSeries ) :
for key , value in self . items ( ) :
if key in other :
try :
result = op ( value , other [ key ] )
if result is NotImplemented :
other_type = type ( other [ key ] )
other_... |
def softmax ( X , axis = 0 ) :
"""Pass X through a softmax function in a numerically stable way using the
log - sum - exp trick .
This transformation is :
. . math : :
\\ frac { \ exp \ { X _ k \ } } { \ sum ^ K _ { j = 1 } \ exp \ { X _ j \ } }
and is appliedx to each row / column , ` k ` , of X .
Para... | if axis == 1 :
return np . exp ( X - logsumexp ( X , axis = 1 ) [ : , np . newaxis ] )
elif axis == 0 :
return np . exp ( X - logsumexp ( X , axis = 0 ) )
else :
raise ValueError ( "This only works on 2D arrays for now." ) |
def console_type ( self , console_type ) :
"""Sets the console type for this node .
: param console _ type : console type ( string )""" | if console_type != self . _console_type : # get a new port if the console type change
self . _manager . port_manager . release_tcp_port ( self . _console , self . _project )
if console_type == "vnc" : # VNC is a special case and the range must be 5900-6000
self . _console = self . _manager . port_manage... |
def _lemmatise_assims ( self , f , * args , ** kwargs ) :
"""Lemmatise un mot f avec son assimilation
: param f : Mot à lemmatiser
: param pos : Récupère la POS
: param get _ lemma _ object : Retrieve Lemma object instead of string representation of lemma
: param results : Current results""" | forme_assimilee = self . assims ( f )
if forme_assimilee != f :
for proposal in self . _lemmatise ( forme_assimilee , * args , ** kwargs ) :
yield proposal |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.