signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def make_extra_json_fields ( args ) :
"""From the parsed command - line arguments , generate a dictionary of additional
fields to be inserted into JSON logs ( logstash _ formatter module )""" | extra_json_fields = { 'data_group' : _get_data_group ( args . query ) , 'data_type' : _get_data_type ( args . query ) , 'data_group_data_type' : _get_data_group_data_type ( args . query ) , 'query' : _get_query_params ( args . query ) , }
if "path_to_json_file" in args . query :
extra_json_fields [ 'path_to_query' ... |
def lrem ( self , name , value , num = 1 ) :
"""Remove first occurrence of value .
Can ' t use redis - py interface . It ' s inconstistent between
redis . Redis and redis . StrictRedis in terms of the kwargs .
Better to use the underlying execute _ command instead .
: param name : str the name of the redis ... | with self . pipe as pipe :
value = self . valueparse . encode ( value )
return pipe . execute_command ( 'LREM' , self . redis_key ( name ) , num , value ) |
def update ( self , new_inputs , strip_prefix = True ) :
"""Updates the inputs dictionary with the key / value pairs from new _ inputs , overwriting existing keys .""" | if strip_prefix and self . input_name_prefix is not None :
for i in new_inputs :
if i . startswith ( self . input_name_prefix ) :
self . inputs [ i [ len ( self . input_name_prefix ) : ] ] = new_inputs [ i ]
else :
self . inputs . update ( new_inputs ) |
def BDEVolumeOpen ( bde_volume , path_spec , file_object , key_chain ) :
"""Opens the BDE volume using the path specification .
Args :
bde _ volume ( pybde . volume ) : BDE volume .
path _ spec ( PathSpec ) : path specification .
file _ object ( FileIO ) : file - like object .
key _ chain ( KeyChain ) : k... | password = key_chain . GetCredential ( path_spec , 'password' )
if password :
bde_volume . set_password ( password )
recovery_password = key_chain . GetCredential ( path_spec , 'recovery_password' )
if recovery_password :
bde_volume . set_recovery_password ( recovery_password )
startup_key = key_chain . GetCred... |
def _set_m2ms ( self , old_m2ms ) :
"""Creates the same m2m relationships that the old
object had .""" | for k , v in old_m2ms . items ( ) :
if v :
setattr ( self , k , v ) |
def host_port_prefix ( host , port , prefix ) :
"""Return URI composed of scheme , server , port , and prefix .""" | uri = "http://" + host
if ( port != 80 ) :
uri += ':' + str ( port )
if ( prefix ) :
uri += '/' + prefix
return uri |
def changed ( self , selection = 'all' ) :
'''Returns the list of changed values .
The key is added to each item .
selection
Specifies the desired changes .
Supported values are
` ` all ` ` - all changed items are included in the output
` ` intersect ` ` - changed items present in both lists are include... | changed = [ ]
if selection == 'all' :
for recursive_item in self . _get_recursive_difference ( type = 'all' ) : # We want the unset values as well
recursive_item . ignore_unset_values = False
key_val = six . text_type ( recursive_item . past_dict [ self . _key ] ) if self . _key in recursive_item . ... |
def get_lldp_neighbor_detail_input_request_type_get_rbridge_specific_rbridge_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_lldp_neighbor_detail = ET . Element ( "get_lldp_neighbor_detail" )
config = get_lldp_neighbor_detail
input = ET . SubElement ( get_lldp_neighbor_detail , "input" )
request_type = ET . SubElement ( input , "request-type" )
get_rbridge_specific = ET . SubElement ( request_type , "ge... |
def contexts ( self ) :
"""Returns known contexts by exposing as a read - only property .""" | if not hasattr ( self , "_contexts" ) :
cs = { }
for cr in self . doc [ "contexts" ] :
cs [ cr [ "name" ] ] = copy . deepcopy ( cr [ "context" ] )
self . _contexts = cs
return self . _contexts |
def attend_on_question ( self , query : torch . Tensor , encoder_outputs : torch . Tensor , encoder_output_mask : torch . Tensor ) -> Tuple [ torch . Tensor , torch . Tensor ] :
"""Given a query ( which is typically the decoder hidden state ) , compute an attention over the
output of the question encoder , and re... | # ( group _ size , question _ length )
question_attention_weights = self . _input_attention ( query , encoder_outputs , encoder_output_mask )
# ( group _ size , encoder _ output _ dim )
attended_question = util . weighted_sum ( encoder_outputs , question_attention_weights )
return attended_question , question_attention... |
def on_hover ( self , callback , remove = False ) :
'''The hover callback takes an unpacked set of keyword arguments .''' | self . _hover_callbacks . register_callback ( callback , remove = remove ) |
def modify_image_attribute ( DryRun = None , ImageId = None , Attribute = None , OperationType = None , UserIds = None , UserGroups = None , ProductCodes = None , Value = None , LaunchPermission = None , Description = None ) :
"""Modifies the specified attribute of the specified AMI . You can specify only one attri... | pass |
def copy ( self , strip = None , deep = 'ref' ) :
"""Return another instance of the object , with the same attributes
If deep = True , all attributes themselves are also copies""" | dd = self . to_dict ( strip = strip , deep = deep )
return self . __class__ ( fromdict = dd ) |
def update ( self ) :
"""Update quicklook stats using the input method .""" | # Init new stats
stats = self . get_init_value ( )
# Grab quicklook stats : CPU , MEM and SWAP
if self . input_method == 'local' : # Get the latest CPU percent value
stats [ 'cpu' ] = cpu_percent . get ( )
stats [ 'percpu' ] = cpu_percent . get ( percpu = True )
# Use the psutil lib for the memory ( virtual... |
def add_text ( self , value ) :
"""Adds text corresponding to ` value ` into ` self . pieces ` .""" | if isinstance ( value , ( list , tuple ) ) :
self . pieces . extend ( value )
else :
self . pieces . append ( value ) |
def temp_dir ( sub_dir = 'work' ) :
"""Obtain the temporary working directory for the operating system .
An inasafe subdirectory will automatically be created under this and
if specified , a user subdirectory under that .
. . note : : You can use this together with unique _ filename to create
a file in a te... | user = getpass . getuser ( ) . replace ( ' ' , '_' )
current_date = date . today ( )
date_string = current_date . isoformat ( )
if 'INASAFE_WORK_DIR' in os . environ :
new_directory = os . environ [ 'INASAFE_WORK_DIR' ]
else : # Following 4 lines are a workaround for tempfile . tempdir ( )
# unreliabilty
handle... |
def get_supported_binary_ops ( ) :
'''Returns a dictionary of the Weld supported binary ops , with values being their Weld symbol .''' | binary_ops = { }
binary_ops [ np . add . __name__ ] = '+'
binary_ops [ np . subtract . __name__ ] = '-'
binary_ops [ np . multiply . __name__ ] = '*'
binary_ops [ np . divide . __name__ ] = '/'
return binary_ops |
def splittable ( src ) :
""": returns : True if the source is splittable , False otherwise""" | return ( src . __class__ . __iter__ is not BaseSeismicSource . __iter__ and getattr ( src , 'mutex_weight' , 1 ) == 1 and src . splittable ) |
def parse_args ( ) :
"""Parse the command line arguments .""" | import argparse
import textwrap
parser = argparse . ArgumentParser ( formatter_class = argparse . RawDescriptionHelpFormatter , description = textwrap . dedent ( '''\
Command line utility to generate .svg badges.
This utility can be used to generate .svg badge images, using configurable
thresholds for coloring. Value... |
async def click ( self , i = None , j = None , * , text = None , filter = None , data = None ) :
"""Calls ` telethon . tl . custom . messagebutton . MessageButton . click `
for the specified button .
Does nothing if the message has no buttons .
Args :
i ( ` int ` ) :
Clicks the i ' th button ( starting fr... | if data :
if not await self . get_input_chat ( ) :
return None
try :
return await self . _client ( functions . messages . GetBotCallbackAnswerRequest ( peer = self . _input_chat , msg_id = self . id , data = data ) )
except errors . BotTimeout :
return None
if sum ( int ( x is not No... |
def NewFromYiq ( y , i , q , alpha = 1.0 , wref = _DEFAULT_WREF ) :
'''Create a new instance based on the specifed YIQ values .
Parameters :
The Y component value [ 0 . . . 1]
The I component value [ 0 . . . 1]
The Q component value [ 0 . . . 1]
: alpha :
The color transparency [ 0 . . . 1 ] , default i... | return Color ( Color . YiqToRgb ( y , i , q ) , 'rgb' , alpha , wref ) |
def main ( ) :
"""Main Function""" | num_blocks = int ( sys . argv [ 1 ] ) if len ( sys . argv ) == 2 else 3
clear_db ( )
for block_id in generate_scheduling_block_id ( num_blocks = num_blocks , project = 'sip' ) :
config = { "id" : block_id , "sub_array_id" : str ( random . choice ( range ( 3 ) ) ) , "processing_blocks" : [ ] }
for i in range ( r... |
def categories ( self , * category_slugs ) :
"""Return the entries with the given category slugs .
When multiple tags are provided , they operate as " OR " query .""" | categories_field = getattr ( self . model , 'categories' , None )
if categories_field is None :
raise AttributeError ( "The {0} does not include CategoriesEntryMixin" . format ( self . model . __name__ ) )
if issubclass ( categories_field . rel . model , TranslatableModel ) : # Needs a different field , assume slug... |
def create_build_job ( user , project , config , code_reference , configmap_refs = None , secret_refs = None ) :
"""Get or Create a build job based on the params .
If a build job already exists , then we check if the build has already an image created .
If the image does not exists , and the job is already done... | build_job , rebuild = BuildJob . create ( user = user , project = project , config = config , code_reference = code_reference , configmap_refs = configmap_refs , secret_refs = secret_refs )
if build_job . succeeded and not rebuild :
return build_job , True , False
if build_job . is_done :
build_job , _ = BuildJ... |
def gps_raw_int_encode ( self , time_usec , fix_type , lat , lon , alt , eph , epv , vel , cog , satellites_visible ) :
'''The global position , as returned by the Global Positioning System
( GPS ) . This is NOT the global position
estimate of the system , but rather a RAW sensor value .
See message GLOBAL _ ... | return MAVLink_gps_raw_int_message ( time_usec , fix_type , lat , lon , alt , eph , epv , vel , cog , satellites_visible ) |
def set_cell_value ( self , row , index , value ) :
"""Sets the value for the cell at row [ index ] .""" | if self . _set_cell_value :
self . _set_cell_value ( row , index , value )
else :
row [ index ] = value |
def execv ( self , argv , ** kwargs ) :
"""Starts a new process for debugging .
This method uses a list of arguments . To use a command line string
instead , use L { execl } .
@ see : L { attach } , L { detach }
@ type argv : list ( str . . . )
@ param argv : List of command line arguments to pass to the ... | if type ( argv ) in ( str , compat . unicode ) :
raise TypeError ( "Debug.execv expects a list, not a string" )
lpCmdLine = self . system . argv_to_cmdline ( argv )
return self . execl ( lpCmdLine , ** kwargs ) |
def newDtd ( self , name , ExternalID , SystemID ) :
"""Creation of a new DTD for the external subset . To create an
internal subset , use xmlCreateIntSubset ( ) .""" | ret = libxml2mod . xmlNewDtd ( self . _o , name , ExternalID , SystemID )
if ret is None :
raise treeError ( 'xmlNewDtd() failed' )
__tmp = xmlDtd ( _obj = ret )
return __tmp |
def from_ctor ( ctor , ) :
"""desc : >
Turns a class constructor into an instance of DocString .
Pass in either Class . _ _ init _ _ , a factory function ,
or factory static method .
args :
- name : ctor
desc : The constructor method or function to use for
generating a DocString instance
type : func... | _docstring = inspect . getdoc ( ctor )
assert _docstring is not None , "No docstring for {}" . format ( ctor )
obj = yaml . load ( _docstring )
docstring = unmarshal_json ( obj , DocString )
argspec = getargspec ( ctor )
args , varargs , defaults = ( argspec . args , argspec . varargs , argspec . defaults , )
if args [... |
def beam_kev ( self , get_error = False ) :
"""Get the beam energy in kev , based on typical biases :
itw ( or ite bias ) - bias15 - platform bias
if get _ error : fetch error in value , rather than value""" | # get epics pointer
epics = self . epics
# fetch stds
if get_error :
attr = 'std'
else :
attr = 'mean'
# get inital beam energy in keV
beam = getattr ( epics . target_bias , attr ) / 1000.
# get RB cell voltage
bias15 = getattr ( epics . bias15 , attr ) / 1000.
# get platform bias
if self . area == 'BNMR' :
... |
def get_robotstxt_parser ( url , session = None ) :
"""Get a RobotFileParser for the given robots . txt URL .""" | rp = robotparser . RobotFileParser ( )
try :
req = urlopen ( url , session , max_content_bytes = MaxContentBytes , raise_for_status = False )
except Exception : # connect or timeout errors are treated as an absent robots . txt
rp . allow_all = True
else :
if req . status_code >= 400 :
rp . allow_all... |
def find_graphviz ( ) :
"""Locate Graphviz ' s executables in the system .
Tries three methods :
First : Windows Registry ( Windows only )
This requires Mark Hammond ' s pywin32 is installed .
Secondly : Search the path
It will look for ' dot ' , ' twopi ' and ' neato ' in all the directories
specified ... | # Method 1 ( Windows only )
if os . sys . platform == 'win32' :
HKEY_LOCAL_MACHINE = 0x80000002
KEY_QUERY_VALUE = 0x0001
RegOpenKeyEx = None
RegQueryValueEx = None
RegCloseKey = None
try :
import win32api
RegOpenKeyEx = win32api . RegOpenKeyEx
RegQueryValueEx = win32api .... |
def read ( cls , data ) :
"""Reads data from URL or OrderedDict .
Args :
data : can be a URL pointing to a JSONstat file , a JSON string
or an OrderedDict .
Returns :
An object of class Collection populated with data .""" | if isinstance ( data , OrderedDict ) :
return cls ( data )
elif isinstance ( data , basestring ) and data . startswith ( ( "http://" , "https://" , "ftp://" , "ftps://" ) ) :
return cls ( request ( data ) )
elif isinstance ( data , basestring ) :
try :
json_dict = json . loads ( data , object_pairs_... |
def handle_delayed_messages ( self ) :
"""Enqueue any delayed messages whose eta has passed .""" | for eta , message in iter_queue ( self . delay_queue ) :
if eta > current_millis ( ) :
self . delay_queue . put ( ( eta , message ) )
self . delay_queue . task_done ( )
break
queue_name = q_name ( message . queue_name )
new_message = message . copy ( queue_name = queue_name )
del... |
def get_home ( ) :
"""Find user ' s home directory if possible . Otherwise raise error .
: return : user ' s home directory
: rtype : : py : obj : ` str `
New in PyTango 7.1.4""" | path = ''
try :
path = os . path . expanduser ( "~" )
except :
pass
if not os . path . isdir ( path ) :
for evar in ( 'HOME' , 'USERPROFILE' , 'TMP' ) :
try :
path = os . environ [ evar ]
if os . path . isdir ( path ) :
break
except :
pass
... |
def run_online_mode ( args ) :
"""Run jobs .
: param args : arguments resulting from program ArgumentParser .
: return : None
This reads messages containing job descriptions from standard input ,
and writes messages to standard output containing the result .
Messages can be encoded as either JSON or Messa... | print ( "\033[47;30m Netherlands\033[48;2;0;174;239;37m▌" "\033[38;2;255;255;255me\u20d2Science\u20d2\033[37m▐" "\033[47;30mcenter \033[m Noodles worker" , file = sys . stderr )
if args . n == 1 :
registry = look_up ( args . registry ) ( )
finish = None
input_stream = JSONObjectReader ( registry , sys . std... |
def main ( self ) :
"""Main arbiter function : :
* Set logger
* Init daemon
* Launch modules
* Endless main process loop
: return : None""" | try : # Start the daemon
if not self . verify_only and not self . do_daemon_init_and_start ( ) :
self . exit_on_error ( message = "Daemon initialization error" , exit_code = 3 )
if self . verify_only :
self . setup_alignak_logger ( )
# Load monitoring configuration files
self . load_moni... |
def currentFolder ( self , value ) :
"""gets / sets the current folder name""" | if value in self . folders :
if value . lower ( ) != 'root' :
self . _currentFolder = value
self . _location = "%s/%s" % ( self . root , value )
else :
self . _currentFolder = value
self . _location = self . root
self . __init ( folder = value ) |
def _clear ( self ) :
"""Helper that clears the composition .""" | draw = ImageDraw . Draw ( self . _background_image )
draw . rectangle ( self . _device . bounding_box , fill = "black" )
del draw |
def set_permissions ( filename , uid = None , gid = None , mode = 0775 ) :
"""Set pemissions for given ` filename ` .
Args :
filename ( str ) : name of the file / directory
uid ( int , default proftpd ) : user ID - if not set , user ID of ` proftpd `
is used
gid ( int ) : group ID , if not set , it is not... | if uid is None :
uid = get_ftp_uid ( )
if gid is None :
gid = - 1
os . chown ( filename , uid , gid )
os . chmod ( filename , mode ) |
def config_file ( kind = "local" ) :
"""Get the filename of the distutils , local , global , or per - user config
` kind ` must be one of " local " , " global " , or " user " """ | if kind == 'local' :
return 'setup.cfg'
if kind == 'global' :
return os . path . join ( os . path . dirname ( distutils . __file__ ) , 'distutils.cfg' )
if kind == 'user' :
dot = os . name == 'posix' and '.' or ''
return os . path . expanduser ( convert_path ( "~/%spydistutils.cfg" % dot ) )
raise Value... |
def check ( text ) :
"""Check the text .""" | err = "links.valid"
msg = u"Broken link: {}"
regex = re . compile ( r"""(?i)\b((?:https?://|www\d{0,3}[.]
|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+
|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)
|[^\s`!()\[\]{};:\'".,<>?\xab\xbb\u201c\u201d\u2018\u2019\u21a9]))""" , r... |
def get_billing_report_firmware_updates ( self , month , ** kwargs ) : # noqa : E501
"""Get raw billing data of the firmware updates for the month . # noqa : E501
Fetch raw billing data of the firmware updates for the currently authenticated commercial non - subtenant account . This is supplementary data for the ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . get_billing_report_firmware_updates_with_http_info ( month , ** kwargs )
# noqa : E501
else :
( data ) = self . get_billing_report_firmware_updates_with_http_info ( month , ** kwargs )
# noqa : E501
return ... |
def response ( self , component_id , component = None , ** kwargs ) :
"""Add a response which can be referenced .
: param str component _ id : ref _ id to use as reference
: param dict component : response fields
: param dict kwargs : plugin - specific arguments""" | if component_id in self . _responses :
raise DuplicateComponentNameError ( 'Another response with name "{}" is already registered.' . format ( component_id ) )
component = component or { }
ret = component . copy ( )
# Execute all helpers from plugins
for plugin in self . _plugins :
try :
ret . update ( ... |
def keys_in_dict ( d , parent_key , keys ) :
"""Create a list of keys from a dict recursively .""" | for key , value in d . iteritems ( ) :
if isinstance ( value , dict ) :
keys_in_dict ( value , key , keys )
else :
if parent_key :
prefix = parent_key + "."
else :
prefix = ""
keys . append ( prefix + key )
return keys |
def monitor ( self , target ) :
"""Start monitoring the online status of a user . Returns whether or not the server supports monitoring .""" | if 'monitor-notify' in self . _capabilities and not self . is_monitoring ( target ) :
yield from self . rawmsg ( 'MONITOR' , '+' , target )
self . _monitoring . add ( target )
return True
else :
return False |
def get_record_sets ( record ) :
"""Find matching sets .""" | # get lists of sets with search _ pattern equals to None but already in the
# set list inside the record
record_sets = set ( record . get ( '_oai' , { } ) . get ( 'sets' , [ ] ) )
for spec in _build_cache ( ) :
if spec in record_sets :
yield spec
# get list of sets that match using percolator
index , doc_ty... |
def qteBindKeyGlobal ( self , keysequence , macroName : str ) :
"""Associate ` ` macroName ` ` with ` ` keysequence ` ` in all current
applets .
This method will bind ` ` macroName ` ` to ` ` keysequence ` ` in the
global key map and * * all * * local key maps . This also applies
for all applets ( and their... | # Convert the key sequence into a QtmacsKeysequence object , or
# raise an QtmacsOtherError if the conversion is impossible .
keysequence = QtmacsKeysequence ( keysequence )
# Sanity check : the macro must have been registered
# beforehand .
if not self . qteIsMacroRegistered ( macroName ) :
msg = 'Cannot globally ... |
def _patch_prebuild ( cls ) :
"""Patch a setuptools command to depend on ` prebuild `""" | orig_run = cls . run
def new_run ( self ) :
self . run_command ( "prebuild" )
orig_run ( self )
cls . run = new_run |
def compute_shadows ( self ) :
"""Computes the shadoing for the ` ` pyny . Space ` ` stored in
` ` . space ` ` for the time intervals and Sun positions stored in
` ` . arg _ t ` ` and ` ` . sun _ pos ` ` , respectively .
The generated information is stored in :
* * * . light _ vor * * ( * ndarray ( dtype = ... | from pyny3d . utils import sort_numpy , bool2index , index2bool
state = pyny . Polygon . verify
pyny . Polygon . verify = False
model = self . space
light = [ ]
for sun in self . vor_centers : # Rotation of the whole ` ` pyny . Space ` `
polygons_photo , _ , points_to_eval = model . photo ( sun , False )
# Auxi... |
def version ( ) :
'''Return server version ( ` ` apachectl - v ` ` )
CLI Example :
. . code - block : : bash
salt ' * ' apache . version''' | cmd = '{0} -v' . format ( _detect_os ( ) )
out = __salt__ [ 'cmd.run' ] ( cmd ) . splitlines ( )
ret = out [ 0 ] . split ( ': ' )
return ret [ 1 ] |
def parameters_to_datetime ( self , p ) :
"""Given a dictionary of parameters , will extract the ranged task parameter value""" | dt = p [ self . _param_name ]
return datetime ( dt . year , dt . month , dt . day ) |
def probConn ( self , preCellsTags , postCellsTags , connParam ) :
from . . import sim
'''Generates connections between all pre and post - syn cells based on probability values''' | if sim . cfg . verbose :
print ( 'Generating set of probabilistic connections (rule: %s) ...' % ( connParam [ 'label' ] ) )
allRands = self . generateRandsPrePost ( preCellsTags , postCellsTags )
# get list of params that have a lambda function
paramsStrFunc = [ param for param in [ p + 'Func' for p in self . connS... |
def set_sink_nodes ( self , sink_nodes ) :
r"""Set multiple sink nodes and compute their t - weights .
Parameters
sink _ nodes : sequence of integers
Declare the sink nodes via their ids .
Raises
ValueError
If a passed node id does not refer to any node of the graph
( i . e . it is either higher than ... | if max ( sink_nodes ) >= self . __nodes or min ( sink_nodes ) < 0 :
raise ValueError ( 'Invalid node id of {} or {}. Valid values are 0 to {}.' . format ( max ( sink_nodes ) , min ( sink_nodes ) , self . __nodes - 1 ) )
# set the node - to - sink weights ( t - weights )
for snode in sink_nodes :
self . __graph ... |
def api_client ( connection , client_class = xbahn . api . Client ) :
"""Establishes an API client for one - way communication
connection with an API Server
Arguments :
- connection ( xbahn . connection . Connection )
Keyword Arguments :
- client _ class ( xbahn . api . Client ) : if supplied use this cla... | return client_class ( link = xbahn . connection . link . Link ( # use the connection receive messages ( server responses )
receive = connection , # use the connection to send messages ( initiate requests to server )
send = connection ) ) |
def _set_peripheral_update_option ( self , v , load = False ) :
"""Setter method for peripheral _ update _ option , mapped from YANG variable / firmware / peripheral _ update _ option ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ peripheral _ update _ op... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = peripheral_update_option . peripheral_update_option , is_container = 'container' , presence = False , yang_name = "peripheral-update-option" , rest_name = "peripheral-update" , parent = self , path_helper = self . _path_helpe... |
def _rewrite_col ( self , col ) :
"""Django > = 1.7 column name rewriting""" | if isinstance ( col , Col ) :
new_name = rewrite_lookup_key ( self . model , col . target . name )
if col . target . name != new_name :
new_field = self . model . _meta . get_field ( new_name )
if col . target is col . source :
col . source = new_field
col . target = new_fiel... |
def pass_conditions ( all_info , current_path , conditions , unknown_as_pass_condition = False ) :
"""Pass all conditions ?
: param all _ info :
: param current _ path :
: param conditions :
: param unknown _ as _ pass _ condition : Consider an undetermined condition as passed
: return :""" | result = False
if len ( conditions ) == 0 :
return True
condition_operator = conditions . pop ( 0 )
for condition in conditions :
if condition [ 0 ] in condition_operators :
res = pass_conditions ( all_info , current_path , condition , unknown_as_pass_condition )
else : # Conditions are formed as " ... |
def find_prime_polynomials ( generator = 2 , c_exp = 8 , fast_primes = False , single = False ) :
'''Compute the list of prime polynomials for the given generator and galois field characteristic exponent .''' | # fast _ primes will output less results but will be significantly faster .
# single will output the first prime polynomial found , so if all you want is to just find one prime polynomial to generate the LUT for Reed - Solomon to work , then just use that .
# A prime polynomial ( necessarily irreducible ) is necessary ... |
def getmsg ( option , lenout = _default_len_out ) :
"""Retrieve the current short error message ,
the explanation of the short error message , or the
long error message .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / getmsg _ c . html
: param option : Indicates type of erro... | option = stypes . stringToCharP ( option )
lenout = ctypes . c_int ( lenout )
msg = stypes . stringToCharP ( lenout )
libspice . getmsg_c ( option , lenout , msg )
return stypes . toPythonString ( msg ) |
def run_symmetrized_readout ( self , program : Program , trials : int ) -> np . ndarray :
"""Run a quil program in such a way that the readout error is made collectively symmetric
This means the probability of a bitstring ` ` b ` ` being mistaken for a bitstring ` ` c ` ` is
the same as the probability of ` ` n... | flipped_program = _get_flipped_protoquil_program ( program )
if trials % 2 != 0 :
raise ValueError ( "Using symmetrized measurement functionality requires that you " "take an even number of trials." )
half_trials = trials // 2
flipped_program = flipped_program . wrap_in_numshots_loop ( shots = half_trials )
flipped... |
def port_list ( br ) :
'''Lists all of the ports within bridge .
Args :
br : A string - bridge name .
Returns :
List of bridges ( or empty list ) , False on failure .
. . versionadded : : 2016.3.0
CLI Example :
. . code - block : : bash
salt ' * ' openvswitch . port _ list br0''' | cmd = 'ovs-vsctl list-ports {0}' . format ( br )
result = __salt__ [ 'cmd.run_all' ] ( cmd )
retcode = result [ 'retcode' ]
stdout = result [ 'stdout' ]
return _stdout_list_split ( retcode , stdout ) |
def refine_peaks ( arr , ipeaks , window_width ) :
"""Refine the peak location previously found by find _ peaks _ indexes
Parameters
arr : 1d numpy array , float
Input 1D spectrum .
ipeaks : 1d numpy array ( int )
Indices of the input array arr in which the peaks were initially found .
window _ width : ... | _check_window_width ( window_width )
step = window_width // 2
ipeaks = filter_array_margins ( arr , ipeaks , window_width )
winoff = numpy . arange ( - step , step + 1 , dtype = 'int' )
peakwin = ipeaks [ : , numpy . newaxis ] + winoff
ycols = arr [ peakwin ]
ww = return_weights ( window_width )
coff2 = numpy . dot ( w... |
def get_gosubdag ( gosubdag = None ) :
"""Gets a GoSubDag initialized for use by a Grouper object .""" | if gosubdag is not None :
if gosubdag . rcntobj is not None :
return gosubdag
else :
gosubdag . init_auxobjs ( )
return gosubdag
else :
go2obj = get_godag ( )
return GoSubDag ( None , go2obj , rcntobj = True ) |
def get_argument_parser ( ) :
"""Get a parser that is able to parse program arguments .
: return : instance of arparse . ArgumentParser""" | parser = argparse . ArgumentParser ( description = project . get_description ( ) , epilog = _ ( 'Visit us at {website}.' ) . format ( website = project . WEBSITE_MAIN ) )
parser . add_argument ( '--version' , action = 'version' , version = '{project} {version}' . format ( project = project . PROJECT_TITLE , version = p... |
def _probe_characteristics ( self , conn , services , timeout = 5.0 ) :
"""Probe gatt services for all associated characteristics in a BLE device
Args :
conn ( int ) : the connection handle to probe
services ( dict ) : a dictionary of services produced by probe _ services ( )
timeout ( float ) : the maximum... | for service in services . values ( ) :
success , result = self . _enumerate_handles ( conn , service [ 'start_handle' ] , service [ 'end_handle' ] )
if not success :
return False , None
attributes = result [ 'attributes' ]
service [ 'characteristics' ] = { }
last_char = None
for handle ,... |
def setup_zmq ( self ) :
"""Set up a PUSH and a PULL socket . The PUSH socket will push out
requests to the workers . The PULL socket will receive responses from
the workers and reply through the server socket .""" | self . context = zmq . Context ( )
self . push = self . context . socket ( zmq . PUSH )
self . push_port = self . push . bind_to_random_port ( "tcp://%s" % self . host )
# start a listener for the pull socket
eventlet . spawn ( self . zmq_pull )
eventlet . sleep ( 0 ) |
def _dump_inline_table ( section ) :
"""Preserve inline table in its compact syntax instead of expanding
into subsection .
https : / / github . com / toml - lang / toml # user - content - inline - table""" | retval = ""
if isinstance ( section , dict ) :
val_list = [ ]
for k , v in section . items ( ) :
val = _dump_inline_table ( v )
val_list . append ( k + " = " + val )
retval += "{ " + ", " . join ( val_list ) + " }\n"
return retval
else :
return str ( _dump_value ( section ) ) |
def VerifyStructure ( self , parser_mediator , lines ) :
"""Verify that this file is a Google Drive Sync log file .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
lines ( str ) : one or more lines from the text file .
... | try :
structure = self . _GDS_LINE . parseString ( lines )
except pyparsing . ParseException as exception :
logger . debug ( 'Not a Google Drive Sync log file: {0!s}' . format ( exception ) )
return False
date_time = dfdatetime_time_elements . TimeElementsInMilliseconds ( )
try :
datetime_iso8601 = self... |
def go_to_buffer ( self , buffer_name ) :
"""Go to one of the open buffers .""" | assert isinstance ( buffer_name , string_types )
for i , eb in enumerate ( self . editor_buffers ) :
if ( eb . location == buffer_name or ( buffer_name . isdigit ( ) and int ( buffer_name ) == i ) ) :
self . show_editor_buffer ( eb )
break |
def get_flanker ( group , query ) :
"""> > > get _ flanker ( [ ( 370 , 15184 ) , ( 372 , 15178 ) , ( 373 , 15176 ) , ( 400 , 15193 ) ] , 385)
( ( 373 , 15176 ) , ( 400 , 15193 ) , True )
> > > get _ flanker ( [ ( 124 , 13639 ) , ( 137 , 13625 ) ] , 138)
( ( 137 , 13625 ) , ( 137 , 13625 ) , False )""" | group . sort ( )
pos = bisect_left ( group , ( query , 0 ) )
left_flanker = group [ 0 ] if pos == 0 else group [ pos - 1 ]
right_flanker = group [ - 1 ] if pos == len ( group ) else group [ pos ]
# pick the closest flanker
if abs ( query - left_flanker [ 0 ] ) < abs ( query - right_flanker [ 0 ] ) :
flanker , other... |
def oboTermParser ( filepath ) :
"""Read a obo file and yield ' [ Term ] ' entries .
: param filepath : file path of the . obo file
: yields : lists containing all lines from a obo ' [ Term ] ' entry . Lines are not
processed and still contain the newline character .""" | with io . open ( filepath ) as openfile :
lineIter = iter ( [ i . rstrip ( ) for i in openfile . readlines ( ) ] )
# Iterate through lines until the first obo " [ Term ] " is encountered
try :
line = next ( lineIter )
while line != '[Term]' :
line = next ( lineIter )
header = line
# Remove
... |
def GetClassesByArtifact ( cls , artifact_name ) :
"""Get the classes that support parsing a given artifact .""" | return [ cls . classes [ c ] for c in cls . classes if artifact_name in cls . classes [ c ] . supported_artifacts ] |
def preloop ( self ) :
"""Initialization before prompting user for commands .
Despite the claims in the Cmd documentaion , Cmd . preloop ( ) is not a stub""" | Cmd . preloop ( self )
# sets up command completion
self . _hist = [ ]
# No history yet
self . _locals = { }
# Initialize execution namespace for user
self . _globals = { } |
def _get_goslimids_norel ( self , dagslim ) :
"""Get all GO slim GO IDs that do not have a relationship .""" | go_slims = set ( )
go2obj = self . gosubdag . go2obj
for goid in dagslim :
goobj = go2obj [ goid ]
if not goobj . relationship :
go_slims . add ( goobj . id )
return go_slims |
def multiply_first_even_odd ( numbers ) :
"""The function calculates the product of the first even and the first odd numbers in a given list .
Args :
numbers ( List [ int ] ) : The input list of numbers .
Returns :
int : The product of the first even and odd numbers .
Examples :
> > > multiply _ first _... | first_even_element = next ( ( element for element in numbers if element % 2 == 0 ) , - 1 )
first_odd_element = next ( ( element for element in numbers if element % 2 != 0 ) , - 1 )
return first_even_element * first_odd_element |
def map_kegg_all_genes ( organism_code , target_db ) :
"""Map all of an organism ' s gene IDs to the target database .
This is faster than supplying a specific list of genes to map ,
plus there seems to be a limit on the number you can map with a manual REST query anyway .
Args :
organism _ code : the three... | mapping = bs_kegg . conv ( target_db , organism_code )
# strip the organism code from the keys and the identifier in the values
new_mapping = { }
for k , v in mapping . items ( ) :
new_mapping [ k . replace ( organism_code + ':' , '' ) ] = str ( v . split ( ':' ) [ 1 ] )
return new_mapping |
def getopenfilename ( parent = None , caption = '' , basedir = '' , filters = '' , selectedfilter = '' , options = None ) :
"""Wrapper around QtGui . QFileDialog . getOpenFileName static method
Returns a tuple ( filename , selectedfilter ) - - when dialog box is canceled ,
returns a tuple of empty strings
Com... | return _qfiledialog_wrapper ( 'getOpenFileName' , parent = parent , caption = caption , basedir = basedir , filters = filters , selectedfilter = selectedfilter , options = options ) |
def new ( self ) : # type : ( ) - > None
'''Create a new Extended Attribute Record .
Parameters :
None .
Returns :
Nothing .''' | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'This XARecord is already initialized!' )
# FIXME : we should allow the user to set these
self . _group_id = 0
self . _user_id = 0
self . _attributes = 0
self . _filenum = 0
self . _initialized = True |
def _validate_lattice_spacing ( self , lattice_spacing ) :
"""Ensure that lattice spacing is provided and correct .
_ validate _ lattice _ spacing will ensure that the lattice spacing
provided are acceptable values . Additional Numpy errors can also occur
due to the conversion to a Numpy array .
Exceptions ... | dataType = np . float64
if lattice_spacing is not None :
lattice_spacing = np . asarray ( lattice_spacing , dtype = dataType )
lattice_spacing = lattice_spacing . reshape ( ( 3 , ) )
if np . shape ( lattice_spacing ) != ( self . dimension , ) :
raise ValueError ( 'Lattice spacing should be a vector ... |
def _get_msg_class ( code ) :
"""Get the message class based on the message code .""" | msg_classes = { }
msg_classes = _add_msg_class ( msg_classes , MESSAGE_STANDARD_MESSAGE_RECEIVED_0X50 , StandardReceive )
msg_classes = _add_msg_class ( msg_classes , MESSAGE_EXTENDED_MESSAGE_RECEIVED_0X51 , ExtendedReceive )
msg_classes = _add_msg_class ( msg_classes , MESSAGE_X10_MESSAGE_RECEIVED_0X52 , X10Received )... |
def comp_idat ( self , idat ) :
"""Generator that produce compressed IDAT chunks from IDAT data""" | # http : / / www . w3 . org / TR / PNG / # 11IDAT
if self . compression is not None :
compressor = zlib . compressobj ( self . compression )
else :
compressor = zlib . compressobj ( )
for dat in idat :
compressed = compressor . compress ( dat )
if len ( compressed ) :
yield compressed
flushed = ... |
def add_bridge ( name , datapath_type = None ) :
'''Add the named bridge to openvswitch''' | log ( 'Creating bridge {}' . format ( name ) )
cmd = [ "ovs-vsctl" , "--" , "--may-exist" , "add-br" , name ]
if datapath_type is not None :
cmd += [ '--' , 'set' , 'bridge' , name , 'datapath_type={}' . format ( datapath_type ) ]
subprocess . check_call ( cmd ) |
def count_slow ( self , page_size = 10 , vtimeout = 10 ) :
"""Deprecated . This is the old ' count ' method that actually counts
the messages by reading them all . This gives an accurate count but
is very slow for queues with non - trivial number of messasges .
Instead , use get _ attribute ( ' ApproximateNum... | n = 0
l = self . get_messages ( page_size , vtimeout )
while l :
for m in l :
n += 1
l = self . get_messages ( page_size , vtimeout )
return n |
def cell_strings ( term ) :
"""Return the strings that represent each possible living cell state .
Return the most colorful ones the terminal supports .""" | num_colors = term . number_of_colors
if num_colors >= 16 :
funcs = term . on_bright_red , term . on_bright_green , term . on_bright_cyan
elif num_colors >= 8 :
funcs = term . on_red , term . on_green , term . on_blue
else : # For black and white , use the checkerboard cursor from the vt100
# alternate charset :... |
def get_cancellation_status ( brain_or_object , default = "active" ) :
"""Get the ` cancellation _ state ` of an object
: param brain _ or _ object : A single catalog brain or content object
: type brain _ or _ object : ATContentType / DexterityContentType / CatalogBrain
: returns : Value of the review _ stat... | if is_brain ( brain_or_object ) :
return getattr ( brain_or_object , "cancellation_state" , default )
workflows = get_workflows_for ( brain_or_object )
if 'bika_cancellation_workflow' not in workflows :
return default
return get_workflow_status_of ( brain_or_object , 'cancellation_state' ) |
def _get_covariance_symbol ( self , q_counter , sp1_idx , sp2_idx ) :
r"""Compute second order moments i . e . variances and covariances
Covariances equal to 0 in univariate case
: param q _ counter : moment matrix
: param sp1 _ idx : index of one species
: param sp2 _ idx : index of another species
: ret... | # The diagonal positions in the matrix are the variances
if sp1_idx == sp2_idx :
return [ q . symbol for q in q_counter if q . n_vector [ sp1_idx ] == 2 and q . order == 2 ] [ 0 ]
# Covariances are found if the moment order is 2 and the moment vector contains double 1
return [ q . symbol for q in q_counter if q . n... |
def _build_var ( var , property_path = None ) :
"""Builds a schema definition for a given config var .
: param attr . _ make . Attribute var : The var to generate a schema definition for
: param List [ str ] property _ path : The property path of the current type ,
defaults to None , optional
: raises Value... | if not property_path :
property_path = [ ]
if not is_config_var ( var ) :
raise ValueError ( f"var {var!r} is not a config var" )
entry = var . metadata [ CONFIG_KEY ]
var_name = entry . name if entry . name else var . name
schema = { "$id" : f"#/{'/'.join(property_path)}/{var_name}" }
if var . default is not N... |
def insertAcquisitionEra ( self , businput ) :
"""Input dictionary has to have the following keys :
acquisition _ era _ name , creation _ date , create _ by , start _ date , end _ date .
it builds the correct dictionary for dao input and executes the dao""" | conn = self . dbi . connection ( )
tran = conn . begin ( )
try :
businput [ "acquisition_era_id" ] = self . sm . increment ( conn , "SEQ_AQE" , tran )
businput [ "acquisition_era_name" ] = businput [ "acquisition_era_name" ]
# self . logger . warning ( businput )
self . acqin . execute ( conn , businput... |
def open_store_variable ( self , name , var ) :
"""Turn CDMRemote variable into something like a numpy . ndarray .""" | data = indexing . LazilyOuterIndexedArray ( CDMArrayWrapper ( name , self ) )
return Variable ( var . dimensions , data , { a : getattr ( var , a ) for a in var . ncattrs ( ) } ) |
def _to_integral ( self , output_array ) :
"""Convert an array produced by this classifier into an array of integer
labels and a missing value label .""" | if self . dtype == int64_dtype :
group_labels = output_array
null_label = self . missing_value
elif self . dtype == categorical_dtype : # Coerce LabelArray into an isomorphic array of ints . This is
# necessary because np . where doesn ' t know about LabelArrays or the
# void dtype .
group_labels = output_a... |
def is_equal ( a , b , tol ) :
"""Ratio test to check if two floating point numbers are equal .
Parameters
a : float
The first floating point number .
b : float
The second floating point number .
tol : float
The tolerance used .
Returns
bool
Whether or not the two numbers are deemed equal .""" | if a == b or abs ( a - b ) <= tol * max ( abs ( a ) , abs ( b ) ) :
return True
else :
return False |
def validate_tag ( key , value ) :
"""Validate a tag .
Keys must be less than 128 chars and values must be less than 256 chars .""" | # Note , parse _ sql does not include a keys if the value is an empty string
# ( e . g . ' key = & test = a ' ) , and thus technically we should not get strings
# which have zero length .
klen = len ( key )
vlen = len ( value )
return klen > 0 and klen < 256 and vlen > 0 and vlen < 256 |
def lib_dir ( self ) :
"""Return standard library directory path used by RPM libs .
TODO : Support non - system RPM .""" | if not self . _lib_dir :
rpm_lib_dir = None
cmd = '{0} -ql rpm-libs' . format ( self . rpm_path )
out = Cmd . sh_e_out ( cmd )
lines = out . split ( '\n' )
for line in lines :
if 'librpm.so' in line :
rpm_lib_dir = os . path . dirname ( line )
break
self . _lib_di... |
async def get_auth ( request ) :
"""Returns the user _ id associated with a particular request .
Args :
request : aiohttp Request object .
Returns :
The user _ id associated with the request , or None if no user is
associated with the request .
Raises :
RuntimeError : Middleware is not installed""" | auth_val = request . get ( AUTH_KEY )
if auth_val :
return auth_val
auth_policy = request . get ( POLICY_KEY )
if auth_policy is None :
raise RuntimeError ( 'auth_middleware not installed' )
request [ AUTH_KEY ] = await auth_policy . get ( request )
return request [ AUTH_KEY ] |
def parse_request_start_line ( line : str ) -> RequestStartLine :
"""Returns a ( method , path , version ) tuple for an HTTP 1 . x request line .
The response is a ` collections . namedtuple ` .
> > > parse _ request _ start _ line ( " GET / foo HTTP / 1.1 " )
RequestStartLine ( method = ' GET ' , path = ' / ... | try :
method , path , version = line . split ( " " )
except ValueError : # https : / / tools . ietf . org / html / rfc7230 # section - 3.1.1
# invalid request - line SHOULD respond with a 400 ( Bad Request )
raise HTTPInputError ( "Malformed HTTP request line" )
if not re . match ( r"^HTTP/1\.[0-9]$" , version ... |
def get_variable ( self , key , per_reference = None , access_key = None , default = None ) :
"""Fetches the value of a global variable
: param key : the key of the global variable to be fetched
: param bool per _ reference : a flag to decide if the variable should be stored per reference or per value
: param... | key = str ( key )
if self . variable_exist ( key ) :
unlock = True
if self . is_locked ( key ) :
if self . __access_keys [ key ] == access_key :
unlock = False
else :
if not access_key :
access_key = self . lock_variable ( key , block = True )
... |
def reversed ( self ) :
"""returns a copy of the Path object with its orientation reversed .""" | newpath = [ seg . reversed ( ) for seg in self ]
newpath . reverse ( )
return Path ( * newpath ) |
def set_fig_x_label ( self , xlabel , ** kwargs ) :
"""Set overall figure x .
Set label for x axis on overall figure . This is not for a specific plot .
It will place the label on the figure at the left with a call to ` ` fig . text ` ` .
Args :
xlabel ( str ) : xlabel for entire figure .
Keyword Argument... | prop_default = { 'x' : 0.01 , 'y' : 0.51 , 'fontsize' : 20 , 'rotation' : 'vertical' , 'va' : 'center' , }
for prop , default in prop_default . items ( ) :
kwargs [ prop ] = kwargs . get ( prop , default )
self . _set_fig_label ( 'x' , xlabel , ** kwargs )
return |
def get_repository ( name ) :
'''Get the details of a local PSGet repository
: param name : Name of the repository
: type name : ` ` str ` `
CLI Example :
. . code - block : : bash
salt ' win01 ' psget . get _ repository MyRepo''' | # Putting quotes around the parameter protects against command injection
cmd = 'Get-PSRepository "{0}"' . format ( name )
no_ret = _pshell ( cmd )
return name not in list_modules ( ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.