signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def append_user_agent ( self , user_agent ) :
"""Append text to the User - Agent header for the request .
Use this method to update the User - Agent header by appending the
given string to the session ' s User - Agent header separated by a space .
: param user _ agent : A string to append to the User - Agent ... | old_ua = self . session . headers . get ( 'User-Agent' , '' )
ua = old_ua + ' ' + user_agent
self . session . headers [ 'User-Agent' ] = ua . strip ( ) |
def as_sorted_list ( options ) :
"""Returns all options in a list sorted according to their option numbers .
: return : the sorted list""" | if len ( options ) > 0 :
options = sorted ( options , key = lambda o : o . number )
return options |
def reload_images ( self ) :
"""Load the map images from disk
This method will use the image loader passed in the constructor
to do the loading or will use a generic default , in which case no
images will be loaded .
: return : None""" | self . images = [ None ] * self . maxgid
# iterate through tilesets to get source images
for ts in self . tilesets : # skip tilesets without a source
if ts . source is None :
continue
path = os . path . join ( os . path . dirname ( self . filename ) , ts . source )
colorkey = getattr ( ts , 'trans' ... |
def get_oldest_commit_date ( self ) :
'''Get datetime of oldest commit involving this file
: returns : Datetime of oldest commit''' | oldest_commit = self . get_oldest_commit ( )
return self . git . get_commit_date ( oldest_commit , self . tz_name ) |
def collect ( self ) :
"""Collect network interface stats .""" | # Initialize results
results = { }
if os . access ( self . PROC , os . R_OK ) : # Open File
file = open ( self . PROC )
# Build Regular Expression
greed = ''
if str_to_bool ( self . config [ 'greedy' ] ) :
greed = '\S*'
exp = ( ( '^(?:\s*)((?:%s)%s):(?:\s*)' + '(?P<rx_bytes>\d+)(?:\s*)' + '(... |
def ajDesinence ( self , d ) :
"""Ajoute la désinence d dans la map des désinences .""" | self . lemmatiseur . _desinences [ deramise ( d . gr ( ) ) ] . append ( d ) |
def GetValueAndReset ( self ) :
"""Gets stream buffer since the last GetValueAndReset ( ) call .""" | if not self . _stream :
raise ArchiveAlreadyClosedError ( "Attempting to get a value from a closed stream." )
value = self . _stream . getvalue ( )
self . _stream . seek ( 0 )
self . _stream . truncate ( )
return value |
def line_is_installable ( self ) : # type : ( ) - > bool
"""This is a safeguard against decoy requirements when a user installs a package
whose name coincides with the name of a folder in the cwd , e . g . install * alembic *
when there is a folder called * alembic * in the working directory .
In this case we... | line = self . line
if is_file_url ( line ) :
link = create_link ( line )
line = link . url_without_fragment
line , _ = split_ref_from_uri ( line )
if ( is_vcs ( line ) or ( is_valid_url ( line ) and ( not is_file_url ( line ) or is_installable_file ( line ) ) ) or is_installable_file ( line ) ) :
return... |
def get_number_of_current_players ( self , appID , format = None ) :
"""Request the current number of players for a given app .
appID : The app ID
format : Return format . None defaults to json . ( json , xml , vdf )""" | parameters = { 'appid' : appID }
if format is not None :
parameters [ 'format' ] = format
url = self . create_request_url ( self . interface , 'GetNumberOfCurrentPlayers' , 1 , parameters )
data = self . retrieve_request ( url )
return self . return_data ( data , format = format ) |
def cfgGetBool ( theObj , name , dflt ) :
"""Get a stringified val from a ConfigObj obj and return it as bool""" | strval = theObj . get ( name , None )
if strval is None :
return dflt
return strval . lower ( ) . strip ( ) == 'true' |
def Interpolate ( self ) :
"""Interpolates the pattern .
Yields :
All possible interpolation results .""" | for var_config in collection . DictProduct ( self . _var_bindings ) :
for scope_config in collection . DictProduct ( self . _scope_bindings ) :
subst = Substitution ( var_config = var_config , scope_config = scope_config )
yield subst . Substitute ( self . _pattern ) |
def XYZ_to_RGB ( cobj , target_rgb , * args , ** kwargs ) :
"""XYZ to RGB conversion .""" | temp_X = cobj . xyz_x
temp_Y = cobj . xyz_y
temp_Z = cobj . xyz_z
logger . debug ( " \- Target RGB space: %s" , target_rgb )
target_illum = target_rgb . native_illuminant
logger . debug ( " \- Target native illuminant: %s" , target_illum )
logger . debug ( " \- XYZ color's illuminant: %s" , cobj . illuminant )
# If ... |
def generateMethods ( self ) :
"""Generate some member functions""" | for i in range ( 1 , 5 ) : # adds member function grid _ ixi _ slot ( self )
self . make_grid_slot ( i , i )
for cl in self . mvision_classes :
self . make_mvision_slot ( cl ) |
def tabulate ( obj , v_level_indexes = None , h_level_indexes = None , v_level_visibility = None , h_level_visibility = None , v_level_sort_keys = None , h_level_sort_keys = None , v_level_titles = None , h_level_titles = None , empty = "" , ) :
"""Render a nested data structure into a two - dimensional table .
A... | level_keys = breadth_first ( obj )
v_level_indexes , h_level_indexes = validate_level_indexes ( len ( level_keys ) , v_level_indexes , h_level_indexes )
if v_level_visibility is None :
v_level_visibility = [ True ] * len ( v_level_indexes )
if h_level_visibility is None :
h_level_visibility = [ True ] * len ( h... |
def load ( self , path ) :
"""Load report from XML file .""" | with open ( path , 'rb' ) as f :
self . data = f . read ( )
self . root = et . fromstring ( self . data ) |
def make_apps_dir ( self ) :
"""Creates an empty directory for symlinks to Django applications .
: rtype : str
: return : created directory path""" | self . logger . info ( 'Creating a directory for symlinks to your Django applications `%s` ...' % self . apps_path )
try :
os . mkdir ( self . apps_path )
except OSError :
pass
# Already exists .
return self . apps_path |
def replace ( self , html ) :
"""Perform replacements on given HTML fragment .""" | self . html = html
text = html . text ( )
positions = [ ]
def perform_replacement ( match ) :
offset = sum ( positions )
start , stop = match . start ( ) + offset , match . end ( ) + offset
s = self . html [ start : stop ]
if self . _is_replacement_allowed ( s ) :
repl = match . expand ( self . ... |
def apply_range_set ( self , hist : Hist ) -> None :
"""Apply the associated range set to the axis of a given hist .
Note :
The min and max values should be bins , not user ranges ! For more , see the binning
explanation in ` ` apply _ func _ to _ find _ bin ( . . . ) ` ` .
Args :
hist : Histogram to whic... | # Do individual assignments to clarify which particular value is causing an error here .
axis = self . axis ( hist )
# logger . debug ( f " axis : { axis } , axis ( ) : { axis . GetName ( ) } " )
# Help out mypy
assert not isinstance ( self . min_val , float )
assert not isinstance ( self . max_val , float )
# Evaluate... |
def apply ( self , matrix ) :
"""Slices the supplied matrix and applies any transform bound to this window""" | view = matrix [ self . indices ( ) ]
return self . transform ( view ) if self . transform != None else view |
def _create ( self ) :
"""Create new object on IxNetwork .
: return : IXN object reference .""" | if 'name' in self . _data :
obj_ref = self . api . add ( self . obj_parent ( ) , self . obj_type ( ) , name = self . obj_name ( ) )
else :
obj_ref = self . api . add ( self . obj_parent ( ) , self . obj_type ( ) )
self . api . commit ( )
return self . api . remapIds ( obj_ref ) |
def get_global_count ( self ) :
"""Return global count ( used for naming of . json and . png files )
Returns
int
Global count""" | # Check current number of json files in results directory and dump current json in new file
path_to_json = self . results_folder_name + '/'
json_files = [ pos_json for pos_json in os . listdir ( path_to_json ) if pos_json . endswith ( '.json' ) ]
Wrapper . global_count = len ( json_files ) + 1
return Wrapper . global_c... |
def value_to_string ( self , obj ) :
"""Convert a field value to a string .
Returns the state name .""" | statefield = self . to_python ( self . value_from_object ( obj ) )
return statefield . state . name |
def __reset_vars ( self ) :
"""Reset vars ( for init or gc )""" | self . __button_caps_storage = list ( )
self . usages_storage = dict ( )
self . report_set = dict ( )
self . ptr_preparsed_data = None
self . hid_handle = None
# don ' t clean up the report queue because the
# consumer & producer threads might needed it
self . __evt_handlers = dict ( )
# other
self . __reading_thread =... |
def remove_record ( self , record ) :
"""Remove an already accepted record from the community .
: param record : Record object .
: type record : ` invenio _ records . api . Record `""" | if not self . has_record ( record ) :
current_app . logger . warning ( 'Community removal: record {uuid} was not in community ' '"{comm}"' . format ( uuid = record . id , comm = self . id ) )
else :
key = current_app . config [ 'COMMUNITIES_RECORD_KEY' ]
record [ key ] = [ c for c in record [ key ] if c != ... |
def command ( self , rs_id , command , * args ) :
"""Call a ReplicaSet method .""" | rs = self . _storage [ rs_id ]
try :
return getattr ( rs , command ) ( * args )
except AttributeError :
raise ValueError ( "Cannot issue the command %r to ReplicaSet %s" % ( command , rs_id ) ) |
def grep_full_py_identifiers ( tokens ) :
""": param typing . Iterable [ ( str , str ) ] tokens :
: rtype : typing . Iterator [ str ]""" | global py_keywords
tokens = list ( tokens )
i = 0
while i < len ( tokens ) :
token_type , token = tokens [ i ]
i += 1
if token_type != "id" :
continue
while i + 1 < len ( tokens ) and tokens [ i ] == ( "op" , "." ) and tokens [ i + 1 ] [ 0 ] == "id" :
token += "." + tokens [ i + 1 ] [ 1 ... |
def dispatch_message ( self , message_type , client_id , client_storage , args , kwargs ) :
"""Calls callback functions""" | logger . debug ( "Backend message ({message_type}) : {args} {kwargs}" . format ( message_type = dict ( MESSAGES_TYPES ) [ message_type ] , args = args , kwargs = kwargs ) )
if message_type in [ ON_OPEN , ON_CLOSE , ON_RECEIVE ] : # Find if client exists in clients _ list
client = next ( ( c for c in self . factory ... |
def read_word_data ( self , i2c_addr , register , force = None ) :
"""Read a single word ( 2 bytes ) from a given register .
: param i2c _ addr : i2c address
: type i2c _ addr : int
: param register : Register to read
: type register : int
: param force :
: type force : Boolean
: return : 2 - byte wor... | self . _set_address ( i2c_addr , force = force )
msg = i2c_smbus_ioctl_data . create ( read_write = I2C_SMBUS_READ , command = register , size = I2C_SMBUS_WORD_DATA )
ioctl ( self . fd , I2C_SMBUS , msg )
return msg . data . contents . word |
def get_contained_in_ID_output_contained_in_ID ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_contained_in_ID = ET . Element ( "get_contained_in_ID" )
config = get_contained_in_ID
output = ET . SubElement ( get_contained_in_ID , "output" )
contained_in_ID = ET . SubElement ( output , "contained-in-ID" )
contained_in_ID . text = kwargs . pop ( 'contained_in_ID' )
callback =... |
def filter_by_col ( self , column_names ) :
"""filters sheet / table by columns ( input is column header )
The routine returns the serial numbers with values > 1 in the selected
columns .
Args :
column _ names ( list ) : the column headers .
Returns :
pandas . DataFrame""" | if not isinstance ( column_names , ( list , tuple ) ) :
column_names = [ column_names , ]
sheet = self . table
identity = self . db_sheet_cols . id
exists = self . db_sheet_cols . exists
criterion = True
for column_name in column_names :
_criterion = sheet . loc [ : , column_name ] > 0
_exists = sheet . loc... |
def _get_mapping ( self , line , parser = None , previous = None ) :
'''mapping will take the command from a Dockerfile and return a map
function to add it to the appropriate place . Any lines that don ' t
cleanly map are assumed to be comments .
Parameters
line : the list that has been parsed into parts wi... | # Split the command into cleanly the command and rest
if not isinstance ( line , list ) :
line = self . _split_line ( line )
# No line we will give function to handle empty line
if len ( line ) == 0 :
return None
cmd = line [ 0 ] . upper ( )
mapping = { "ADD" : self . _add , "ARG" : self . _arg , "COPY" : self ... |
def get ( key , default = - 1 ) :
"""Backport support for original codes .""" | if isinstance ( key , int ) :
return EtherType ( key )
if key not in EtherType . _member_map_ :
extend_enum ( EtherType , key , default )
return EtherType [ key ] |
def markdown ( value , arg = '' ) :
"""Runs Markdown over a given value , optionally using various
extensions python - markdown supports .
Derived from django . contrib . markdown , which was deprecated from django .
ALWAYS CLEAN INPUT BEFORE TRUSTING IT .
Syntax : :
{ { value | markdown : " extension1 _ ... | import warnings
warnings . warn ( 'The markdown filter has been deprecated' , category = DeprecationWarning )
try :
import markdown
except ImportError :
if settings . DEBUG :
raise template . TemplateSyntaxError ( "Error in 'markdown' filter: The Python markdown library isn't installed." )
return fo... |
def init_widget ( self ) :
"""Initialize the underlying widget .""" | super ( AndroidTextClock , self ) . init_widget ( )
d = self . declaration
if d . format_12_hour :
self . set_format_12_hour ( d . format_12_hour )
if d . format_24_hour :
self . set_format_24_hour ( d . format_24_hour )
if d . time_zone :
self . set_time_zone ( d . time_zone ) |
def sg_reshape ( tensor , opt ) :
r"""Reshapes a tensor .
See ` tf . reshape ( ) ` in tensorflow .
Args :
tensor : A ` Tensor ` ( automatically given by chain ) .
opt :
shape : A tuple / list of integers . The destination shape .
name : If provided , replace current tensor ' s name .
Returns :
A ` T... | assert opt . shape is not None , 'shape is mandatory.'
return tf . reshape ( tensor , opt . shape , name = opt . name ) |
def user_list ( database = None , user = None , password = None , host = None , port = None ) :
'''List cluster admins or database users .
If a database is specified : it will return database users list .
If a database is not specified : it will return cluster admins list .
database
The database to list the... | client = _client ( user = user , password = password , host = host , port = port )
if not database :
return client . get_list_cluster_admins ( )
client . switch_database ( database )
return client . get_list_users ( ) |
def _computeInferenceMode ( self , feedforwardInput , lateralInputs ) :
"""Inference mode : if there is some feedforward activity , perform
spatial pooling on it to recognize previously known objects , then use
lateral activity to activate a subset of the cells with feedforward
support . If there is no feedfo... | prevActiveCells = self . activeCells
# Calculate the feedforward supported cells
overlaps = self . proximalPermanences . rightVecSumAtNZGteThresholdSparse ( feedforwardInput , self . connectedPermanenceProximal )
feedforwardSupportedCells = numpy . where ( overlaps >= self . minThresholdProximal ) [ 0 ]
# Calculate the... |
def _parse_args ( args , cls ) :
"""Parse a docopt dictionary of arguments""" | d = _create_djset ( args , cls )
key_value_pair = args . get ( '<key>=<value>' )
key = args . get ( '<key>' )
func = None
if args . get ( 'add' ) and key_value_pair :
fargs = tuple ( args . get ( '<key>=<value>' ) . split ( '=' ) )
if fargs [ 1 ] :
func = d . set
elif args . get ( 'remove' ) and key :
... |
async def sonar_read ( self , command ) :
"""This method retrieves the last sonar data value that was cached .
This is a polling method . After sonar config , sonar _ data _ reply messages will be sent automatically .
: param command : { " method " : " sonar _ read " , " params " : [ TRIGGER _ PIN ] }
: retur... | pin = int ( command [ 0 ] )
val = await self . core . sonar_data_retrieve ( pin )
reply = json . dumps ( { "method" : "sonar_read_reply" , "params" : [ pin , val ] } )
await self . websocket . send ( reply ) |
def update_configuration ( self , timeout = - 1 ) :
"""Asynchronously applies or re - applies the logical interconnect configuration to all managed interconnects .
Args :
timeout : Timeout in seconds . Wait for task completion by default . The timeout does not abort the operation
in OneView ; it just stops wa... | uri = "{}/configuration" . format ( self . data [ "uri" ] )
return self . _helper . update ( None , uri = uri , timeout = timeout ) |
def create_private_key ( path = None , text = False , bits = 2048 , passphrase = None , cipher = 'aes_128_cbc' , verbose = True ) :
'''Creates a private key in PEM format .
path :
The path to write the file to , either ` ` path ` ` or ` ` text ` `
are required .
text :
If ` ` True ` ` , return the PEM tex... | if not path and not text :
raise salt . exceptions . SaltInvocationError ( 'Either path or text must be specified.' )
if path and text :
raise salt . exceptions . SaltInvocationError ( 'Either path or text must be specified, not both.' )
if verbose :
_callback_func = M2Crypto . RSA . keygen_callback
else :
... |
def initArgosApplicationSettings ( app ) : # TODO : this is Argos specific . Move somewhere else .
"""Sets Argos specific attributes , such as the OrganizationName , so that the application
persistent settings are read / written to the correct settings file / winreg . It is therefore
important to call this func... | assert app , "app undefined. Call QtWidgets.QApplication.instance() or QtCor.QApplication.instance() first."
logger . debug ( "Setting Argos QApplication settings." )
app . setApplicationName ( info . REPO_NAME )
app . setApplicationVersion ( info . VERSION )
app . setOrganizationName ( info . ORGANIZATION_NAME )
app .... |
def get_suggestions ( self , iteration_config = None ) :
"""Return a list of suggestions / arms based on hyperband .""" | if not iteration_config or not isinstance ( iteration_config , HyperbandIterationConfig ) :
raise ValueError ( 'Hyperband get suggestions requires an iteration.' )
bracket = self . get_bracket ( iteration = iteration_config . iteration )
n_configs = self . get_n_configs ( bracket = bracket )
n_resources = self . ge... |
def get_pid ( self , uri ) :
"""Get the pid for the property in this wikibase instance ( the one at ` sparql _ endpoint _ url ` ) ,
that corresponds to ( i . e . has the equivalent property ) ` uri `""" | # if the wikibase is wikidata , and we give a wikidata uri or a PID with no URI specified :
if ( self . sparql_endpoint_url == 'https://query.wikidata.org/sparql' and ( uri . startswith ( "P" ) or uri . startswith ( "http://www.wikidata.org/entity/" ) ) ) : # don ' t look up anything , just return the same value
re... |
def handle ( self , sock , read_data , path , headers ) :
"Sends back a static error page ." | try :
sock . sendall ( "HTTP/1.0 %s %s\r\nConnection: close\r\nContent-length: 0\r\n\r\n" % ( self . code , responses . get ( self . code , "Unknown" ) ) )
except socket . error , e :
if e . errno != errno . EPIPE :
raise |
def remove ( self , value , _sa_initiator = None ) :
"""Remove an item by value , consulting the keyfunc for the key .""" | key = self . keyfunc ( value )
# Let self [ key ] raise if key is not in this collection
# testlib . pragma exempt : _ _ ne _ _
if not self . __contains__ ( key ) or value not in self [ key ] :
raise sa_exc . InvalidRequestError ( "Can not remove '%s': collection holds '%s' for key '%s'. " "Possible cause: is the M... |
def thumbnail ( self , remote_path , height , width , quality = 100 , ** kwargs ) :
"""获取指定图片文件的缩略图 .
: param remote _ path : 源图片的路径 , 路径必须以 / apps / 开头 。
. . warning : :
* 路径长度限制为1000;
* 径中不能包含以下字符 : ` ` \\ \\ ? | " > < : * ` ` ;
* 文件名或路径名开头结尾不能是 ` ` . ` `
或空白字符 , 空白字符包括 :
` ` \\ r , \\ n , \\ t , 空格... | params = { 'path' : remote_path , 'height' : height , 'width' : width , 'quality' : quality , }
return self . _request ( 'thumbnail' , 'generate' , extra_params = params , ** kwargs ) |
def update ( self , client = None ) :
"""Sends all properties in a PUT request .
Updates the ` ` _ properties ` ` with the response from the backend .
If : attr : ` user _ project ` is set , bills the API request to that project .
: type client : : class : ` ~ google . cloud . storage . client . Client ` or
... | client = self . _require_client ( client )
query_params = self . _query_params
query_params [ "projection" ] = "full"
api_response = client . _connection . api_request ( method = "PUT" , path = self . path , data = self . _properties , query_params = query_params , _target_object = self , )
self . _set_properties ( api... |
def _toolkit_get_topk_bottomk ( values , k = 5 ) :
"""Returns a tuple of the top k values from the positive and
negative values in a SArray
Parameters
values : SFrame of model coefficients
k : Maximum number of largest positive and k lowest negative numbers to return
Returns
( topk _ positive , bottomk ... | top_values = values . topk ( 'value' , k = k )
top_values = top_values [ top_values [ 'value' ] > 0 ]
bottom_values = values . topk ( 'value' , k = k , reverse = True )
bottom_values = bottom_values [ bottom_values [ 'value' ] < 0 ]
return ( top_values , bottom_values ) |
def sell_pnl ( self ) :
"""[ float ] 卖方向累计盈亏""" | return ( self . _sell_avg_open_price - self . last_price ) * self . sell_quantity * self . contract_multiplier |
def disableEffect ( self , name ) :
"""Disable an effect .""" | try :
del self . _effects [ name ]
self . __getattribute__ ( '_effectdisable_%s' % name . replace ( "-" , "_" ) ) ( )
except KeyError :
pass
except AttributeError :
pass |
def load ( self , image = None ) :
'''load an image , either an actual path on the filesystem or a uri .
Parameters
image : the image path or uri to load ( e . g . , docker : / / ubuntu''' | from spython . image import Image
from spython . instance import Instance
self . simage = Image ( image )
if image is not None :
if image . startswith ( 'instance://' ) :
self . simage = Instance ( image )
bot . info ( self . simage ) |
def save_as ( self ) :
"""Dialog for getting name , location of dataset export .""" | filename = splitext ( self . filename ) [ 0 ]
filename , _ = QFileDialog . getSaveFileName ( self , 'Export events' , filename )
if filename == '' :
return
self . filename = filename
short_filename = short_strings ( basename ( self . filename ) )
self . idx_filename . setText ( short_filename ) |
def on_success ( self , metadata ) :
"""Called when a SUCCESS message has been received .""" | handler = self . handlers . get ( "on_success" )
if callable ( handler ) :
handler ( metadata )
handler = self . handlers . get ( "on_summary" )
if callable ( handler ) :
handler ( ) |
def sort_objs_by_attr ( objs , key , reverse = False ) :
"""对原生不支持比较操作的对象根据属性排序
: param :
* objs : ( list ) 需要排序的对象列表
* key : ( string ) 需要进行排序的对象属性
* reverse : ( bool ) 排序结果是否进行反转 , 默认为 False , 不进行反转
: return :
* result : ( list ) 排序后的对象列表
举例如下 : :
print ( ' - - - sorted _ objs _ by _ attr demo - -... | if len ( objs ) == 0 :
return [ ]
if not hasattr ( objs [ 0 ] , key ) :
raise AttributeError ( '{0} object has no attribute {1}' . format ( type ( objs [ 0 ] ) , key ) )
result = sorted ( objs , key = attrgetter ( key ) , reverse = reverse )
return result |
def get_wrapped_stream ( stream , encoding = None , errors = "replace" ) :
"""Given a stream , wrap it in a ` StreamWrapper ` instance and return the wrapped stream .
: param stream : A stream instance to wrap
: param str encoding : The encoding to use for the stream
: param str errors : The error handler to ... | if stream is None :
raise TypeError ( "must provide a stream to wrap" )
stream = _get_binary_buffer ( stream )
if stream is not None and encoding is None :
encoding = "utf-8"
if not encoding :
encoding = get_output_encoding ( stream )
else :
encoding = get_canonical_encoding_name ( encoding )
return Str... |
def move ( self , to_project_id , ** kwargs ) :
"""Move the issue to another project .
Args :
to _ project _ id ( int ) : ID of the target project
* * kwargs : Extra options to send to the server ( e . g . sudo )
Raises :
GitlabAuthenticationError : If authentication is not correct
GitlabUpdateError : I... | path = '%s/%s/move' % ( self . manager . path , self . get_id ( ) )
data = { 'to_project_id' : to_project_id }
server_data = self . manager . gitlab . http_post ( path , post_data = data , ** kwargs )
self . _update_attrs ( server_data ) |
def cross ( self ) :
"""Return cross join""" | self . query . do_join ( Join ( self . item , JoinType . cross ) )
return self . query |
def splits ( cls , text_field , root = '.data' , train = 'wiki.train.tokens' , validation = 'wiki.valid.tokens' , test = 'wiki.test.tokens' , ** kwargs ) :
"""Create dataset objects for splits of the WikiText - 2 dataset .
This is the most flexible way to use the dataset .
Arguments :
text _ field : The field... | return super ( WikiText2 , cls ) . splits ( root = root , train = train , validation = validation , test = test , text_field = text_field , ** kwargs ) |
def nested_dict_to_list ( path , dic , exclusion = None ) :
"""Transform nested dict to list""" | result = [ ]
exclusion = [ '__self' ] if exclusion is None else exclusion
for key , value in dic . items ( ) :
if not any ( [ exclude in key for exclude in exclusion ] ) :
if isinstance ( value , dict ) :
aux = path + key + "/"
result . extend ( nested_dict_to_list ( aux , value ) )
... |
def create ( self , request , * args , ** kwargs ) :
"""Create a resource .""" | self . define_contributor ( request )
try :
return super ( ) . create ( request , * args , ** kwargs )
except IntegrityError as ex :
return Response ( { 'error' : str ( ex ) } , status = status . HTTP_409_CONFLICT ) |
def scale_voltage_current_power ( data , voltage = 1 , current = 1 ) :
"""Scales the voltage , current , and power of the DataFrames
returned by : py : func : ` singlediode ` and : py : func : ` sapm ` .
Parameters
data : DataFrame
Must contain columns ` ' v _ mp ' , ' v _ oc ' , ' i _ mp ' , ' i _ x ' , ' ... | # as written , only works with a DataFrame
# could make it work with a dict , but it would be more verbose
data = data . copy ( )
voltages = [ 'v_mp' , 'v_oc' ]
currents = [ 'i_mp' , 'i_x' , 'i_xx' , 'i_sc' ]
data [ voltages ] *= voltage
data [ currents ] *= current
data [ 'p_mp' ] *= voltage * current
return data |
def apply_groupby_func ( func , * args ) :
"""Apply a dataset or datarray level function over GroupBy , Dataset ,
DataArray , Variable and / or ndarray objects .""" | from . groupby import GroupBy , peek_at
from . variable import Variable
groupbys = [ arg for arg in args if isinstance ( arg , GroupBy ) ]
assert groupbys , 'must have at least one groupby to iterate over'
first_groupby = groupbys [ 0 ]
if any ( not first_groupby . _group . equals ( gb . _group ) for gb in groupbys [ 1... |
def _in_tag ( self , tagname , attributes = None ) :
"""Determine if we are already in a certain tag .
If we give attributes , make sure they match .""" | node = self . cur_node
while not node is None :
if node . tag == tagname :
if attributes and node . attrib == attributes :
return True
elif attributes :
return False
return True
node = node . getparent ( )
return False |
def from_path ( kls , vertices ) :
"""Given an Nx3 array of vertices that constitute a single path ,
generate a skeleton with appropriate edges .""" | if vertices . shape [ 0 ] == 0 :
return PrecomputedSkeleton ( )
skel = PrecomputedSkeleton ( vertices )
edges = np . zeros ( shape = ( skel . vertices . shape [ 0 ] - 1 , 2 ) , dtype = np . uint32 )
edges [ : , 0 ] = np . arange ( skel . vertices . shape [ 0 ] - 1 )
edges [ : , 1 ] = np . arange ( 1 , skel . vertic... |
def get_suitable_slot_for_reference ( self , reference ) :
"""Returns the suitable position for reference analyses , taking into
account if there is a WorksheetTemplate assigned to this worksheet .
By default , returns a new slot at the end of the worksheet unless there
is a slot defined for a reference of th... | if not IReferenceSample . providedBy ( reference ) :
return - 1
occupied = self . get_slot_positions ( type = 'all' ) or [ 0 ]
wst = self . getWorksheetTemplate ( )
if not wst : # No worksheet template assigned , add a new slot at the end of the
# worksheet with the reference analyses there
slot_to = max ( occu... |
def learning_schedule ( ) -> Callable :
"""Returns a method that can be used in argument parsing to check that the argument is a valid learning rate schedule
string .
: return : A method that can be used as a type in argparse .""" | def parse ( schedule_str ) :
try :
schedule = LearningRateSchedulerFixedStep . parse_schedule_str ( schedule_str )
except ValueError :
raise argparse . ArgumentTypeError ( "Learning rate schedule string should have form rate1:num_updates1[,rate2:num_updates2,...]" )
return schedule
return pa... |
def clone ( self ) :
"""Returns a deep copy of self
Function clones :
* routes
* allocation
* nodes
Returns
SavingsSolution
A clone ( deepcopy ) of the instance itself""" | new_solution = self . __class__ ( self . _problem )
# Clone routes
for index , r in enumerate ( self . _routes ) :
new_route = new_solution . _routes [ index ] = models . Route ( self . _problem )
for node in r . nodes ( ) : # Insert new node on new route
new_node = new_solution . _nodes [ node . name (... |
def Connect ( host = 'localhost' , port = 443 , user = 'root' , pwd = '' , service = "hostd" , adapter = "SOAP" , namespace = None , path = "/sdk" , connectionPoolTimeout = CONNECTION_POOL_IDLE_TIMEOUT_SEC , version = None , keyFile = None , certFile = None , thumbprint = None , sslContext = None , b64token = None , me... | try :
info = re . match ( _rx , host )
if info is not None :
host = info . group ( 1 )
if host [ 0 ] == '[' :
host = info . group ( 1 ) [ 1 : - 1 ]
if info . group ( 2 ) is not None :
port = int ( info . group ( 2 ) [ 1 : ] )
except ValueError as ve :
pass
ssl... |
def set_domain ( self , values ) :
"""Set domain of the colors based on min and max of a list of values .""" | _flattenedList = sorted ( flatten ( values ) )
self . domain = tuple ( _flattenedList [ 0 ] if d == 'min' else d for d in self . domain )
self . domain = tuple ( _flattenedList [ - 1 ] if d == 'max' else d for d in self . domain ) |
def ccall ( self , ret_type , func_obj , args ) :
"""Creates a CCall operation .
A CCall is a procedure that calculates a value at * runtime * , not at lift - time .
You can use these for flags , unresolvable jump targets , etc .
We caution you to avoid using them when at all possible though .
For an exampl... | # HACK : FIXME : If you ' re reading this , I ' m sorry . It ' s truly a crime against Python . . .
from angr . engines . vex import ccall
# Check the args to make sure they ' re the right type
list_args = list ( args )
new_args = [ ]
for arg in list_args :
if isinstance ( arg , VexValue ) :
arg = arg . rdt... |
def formatWarnings ( self , warnings ) :
"""Format warnings to a list of results .
@ param warnings : a dict of warnings produced by parseWarnings
@ return : a list of warnings in string""" | lines = [ ]
for modulename in sorted ( warnings ) :
lines . append ( self . prefixModuleName + modulename )
lines . extend ( sorted ( warnings [ modulename ] , key = lambda x : x . split ( ":" ) [ 1 ] ) )
return "\n" . join ( lines ) |
def patch_apply ( self , patches , text ) :
"""Merge a set of patches onto the text . Return a patched text , as well
as a list of true / false values indicating which patches were applied .
Args :
patches : Array of Patch objects .
text : Old text .
Returns :
Two element Array , containing the new text... | if not patches :
return ( text , [ ] )
# Deep copy the patches so that no changes are made to originals .
patches = self . patch_deepCopy ( patches )
nullPadding = self . patch_addPadding ( patches )
text = nullPadding + text + nullPadding
self . patch_splitMax ( patches )
# delta keeps track of the offset between ... |
def memoize ( function ) :
"""A very simple memoize decorator to optimize pure - ish functions
Don ' t use this unless you ' ve examined the code and see the
potential risks .""" | cache = { }
@ functools . wraps ( function )
def _memoize ( * args ) :
if args in cache :
return cache [ args ]
result = function ( * args )
cache [ args ] = result
return result
return function |
def replace_namespaced_daemon_set ( self , name , namespace , body , ** kwargs ) :
"""replace the specified DaemonSet
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . replace _ namespaced _ daemon _ set ( name ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_namespaced_daemon_set_with_http_info ( name , namespace , body , ** kwargs )
else :
( data ) = self . replace_namespaced_daemon_set_with_http_info ( name , namespace , body , ** kwargs )
return data |
def validate ( self ) :
"""Validate keys and values .
Check to make sure every key used is a valid Vorbis key , and
that every value used is a valid Unicode or UTF - 8 string . If
any invalid keys or values are found , a ValueError is raised .
In Python 3 all keys and values have to be a string .""" | if not isinstance ( self . vendor , text_type ) :
if PY3 :
raise ValueError ( "vendor needs to be str" )
try :
self . vendor . decode ( 'utf-8' )
except UnicodeDecodeError :
raise ValueError
for key , value in self :
try :
if not is_valid_key ( key ) :
raise V... |
def get_distinct_value_props ( cls , sparql_endpoint_url = 'https://query.wikidata.org/sparql' ) :
"""On wikidata , the default core IDs will be the properties with a distinct values constraint
select ? p where { ? p wdt : P2302 wd : Q21502410}
See : https : / / www . wikidata . org / wiki / Help : Property _ c... | pcpid = config [ 'PROPERTY_CONSTRAINT_PID' ]
dvcqid = config [ 'DISTINCT_VALUES_CONSTRAINT_QID' ]
try :
h = WikibaseHelper ( sparql_endpoint_url )
pcpid = h . get_pid ( pcpid )
dvcqid = h . get_qid ( dvcqid )
except Exception :
warnings . warn ( "Unable to determine PIDs or QIDs for retrieving distinct ... |
def compute_err ( self , solution_y , coefficients ) :
"""Return an error value by finding the absolute difference for each
element in a list of solution - generated y - values versus expected values .
Compounds error by 50 % for each negative coefficient in the solution .
solution _ y : list of y - values pr... | error = 0
for modeled , expected in zip ( solution_y , self . expected_values ) :
error += abs ( modeled - expected )
if any ( [ c < 0 for c in coefficients ] ) :
error *= 1.5
return error |
def fetch ( self , zookeeper_path , settings = None ) :
"""Download a partition from another server .
: param zookeeper _ path : Path in zookeeper to fetch from
: param settings : Settings for executing request to ClickHouse over db . raw ( ) method
: return : SQL Query""" | return self . _partition_operation_sql ( 'FETCH' , settings = settings , from_part = zookeeper_path ) |
def create ( self , language , value , synonym_of = values . unset ) :
"""Create a new FieldValueInstance
: param unicode language : The ISO language - country tag that identifies the language of the value
: param unicode value : The Field Value data
: param unicode synonym _ of : The string value that indica... | data = values . of ( { 'Language' : language , 'Value' : value , 'SynonymOf' : synonym_of , } )
payload = self . _version . create ( 'POST' , self . _uri , data = data , )
return FieldValueInstance ( self . _version , payload , assistant_sid = self . _solution [ 'assistant_sid' ] , field_type_sid = self . _solution [ '... |
def get_arguments ( ) :
"""Get parsed arguments .""" | parser = argparse . ArgumentParser ( "AbodePy: Command Line Utility" )
parser . add_argument ( '-u' , '--username' , help = 'Username' , required = False )
parser . add_argument ( '-p' , '--password' , help = 'Password' , required = False )
parser . add_argument ( '--cache' , metavar = 'pickle_file' , help = 'Create/up... |
def layer_depth ( lat , lon , layerID = "LID-BOTTOM" ) :
"""Returns layer depth at lat / lon ( degrees )
where lat / lon may be arrays ( of equal size ) .
Depths are returned in metres .""" | # # Must wrap longitude from 0 to 360 . . .
lon1 = np . array ( lon ) % 360.0
lat1 = np . array ( lat )
# # # Must wrap longitude from - 180 to 180 . . .
# lon1 [ np . where ( lon1 > 180.0 ) ] = 360.0 - lon1 [ np . where ( lon1 > 180.0 ) ]
data , err = _interpolator . interpolate ( np . radians ( lon1 ) , np . radians ... |
def nontruncating_zip ( * seqs ) :
"""Return a list of tuples , where each tuple contains the i - th
element from each of the argument sequences .
The returned list is as long as the longest argument sequence .
Shorter argument sequences will be represented in the output as
None padding elements :
nontrun... | n_seqs = len ( seqs )
tups = [ ]
idx = 0
while True :
empties = 0
tup = [ ]
for seq in seqs :
try :
tup . append ( seq [ idx ] )
except IndexError :
empties += 1
tup . append ( None )
if empties == n_seqs :
break
tup = tuple ( tup )
tup... |
def peak_to_peak_period ( t , f , amplitude_threshold = 1E-2 ) :
"""Estimate the period of the input time series by measuring the average
peak - to - peak time .
Parameters
t : array _ like
Time grid aligned with the input time series .
f : array _ like
A periodic time series .
amplitude _ threshold :... | if hasattr ( t , 'unit' ) :
t_unit = t . unit
t = t . value
else :
t_unit = u . dimensionless_unscaled
# find peaks
max_ix = argrelmax ( f , mode = 'wrap' ) [ 0 ]
max_ix = max_ix [ ( max_ix != 0 ) & ( max_ix != ( len ( f ) - 1 ) ) ]
# find troughs
min_ix = argrelmin ( f , mode = 'wrap' ) [ 0 ]
min_ix = min_... |
def SensorsGet ( self , parameters = None , sensor_id = - 1 ) :
"""Retrieve sensors from CommonSense , according to parameters , or by sensor id .
If successful , result can be obtained by a call to getResponse ( ) , and should be a json string .
@ param parameters ( dictionary ) ( optional ) - Dictionary conta... | url = ''
if parameters is None and sensor_id <> - 1 :
url = '/sensors/{0}.json' . format ( sensor_id )
else :
url = '/sensors.json'
if self . __SenseApiCall__ ( url , 'GET' , parameters = parameters ) :
return True
else :
self . __error__ = "api call unsuccessful"
return False |
async def get_current_position ( self , refresh = True ) -> dict :
"""Return the current shade position .
: param refresh : If True it queries the hub for the latest info .
: return : Dictionary with position data .""" | if refresh :
await self . refresh ( )
position = self . _raw_data . get ( ATTR_POSITION_DATA )
return position |
def add_lines ( self , * lines , ** kwargs ) :
"""Add lines to the beginning or end of the build .
: param lines : one or more lines to add to the content , by default at the end .
: param all _ stages : bool for whether to add in all stages for a multistage build
or ( by default ) only the last .
: param a... | assert len ( lines ) > 0
lines = [ _endline ( line ) for line in lines ]
all_stages = kwargs . pop ( 'all_stages' , False )
at_start = kwargs . pop ( 'at_start' , False )
skip_scratch = kwargs . pop ( 'skip_scratch' , False )
assert not kwargs , "Unknown keyword argument(s): {0}" . format ( kwargs . keys ( ) )
froms = ... |
def setPhaseDuration ( self , tlsID , phaseDuration ) :
"""setPhaseDuration ( string , integer or float ) - > None
Set the phase duration of the current phase in seconds .""" | self . _connection . _sendIntCmd ( tc . CMD_SET_TL_VARIABLE , tc . TL_PHASE_DURATION , tlsID , int ( 1000 * phaseDuration ) ) |
def generic_var ( self , key , value = None ) :
"""Stores generic variables in the session prepending it with _ GENERIC _ VAR _ KEY _ PREFIX .""" | return self . _get_or_set ( '{0}{1}' . format ( self . _GENERIC_VAR_KEY_PREFIX , key ) , value ) |
def _get_area_rates ( self , source , mmin , mmax = np . inf ) :
"""Adds the rates from the area source by discretising the source
to a set of point sources
: param source :
Area source as instance of : class :
openquake . hazardlib . source . area . AreaSource""" | points = list ( source )
for point in points :
self . _get_point_rates ( point , mmin , mmax ) |
def get_bgp_config ( self , group = "" , neighbor = "" ) :
"""Implementation of NAPALM method get _ bgp _ config .""" | _GROUP_FIELD_MAP_ = { "type" : "type" , "multipath" : "multipath" , "apply-groups" : "apply_groups" , "remove-private-as" : "remove_private_as" , "ebgp-multihop" : "multihop_ttl" , "remote-as" : "remote_as" , "local-v4-addr" : "local_address" , "local-v6-addr" : "local_address" , "local-as" : "local_as" , "description"... |
def migrations_to_run ( self ) :
"""Get a list of migrations to run still , if any .
Note that this will fail if there ' s no migration record for
this class !""" | assert self . database_current_migration is not None
db_current_migration = self . database_current_migration
return [ ( migration_number , migration_func ) for migration_number , migration_func in self . sorted_migrations if migration_number > db_current_migration ] |
def datetime_to_djd ( time ) :
"""Converts a datetime to the Dublin Julian Day
Parameters
time : datetime . datetime
time to convert
Returns
float
fractional days since 12/31/1899 + 0000""" | if time . tzinfo is None :
time_utc = pytz . utc . localize ( time )
else :
time_utc = time . astimezone ( pytz . utc )
djd_start = pytz . utc . localize ( dt . datetime ( 1899 , 12 , 31 , 12 ) )
djd = ( time_utc - djd_start ) . total_seconds ( ) * 1.0 / ( 60 * 60 * 24 )
return djd |
def _build_generator_list ( network ) :
"""Builds DataFrames with all generators in MV and LV grids
Returns
: pandas : ` pandas . DataFrame < dataframe > `
A DataFrame with id of and reference to MV generators
: pandas : ` pandas . DataFrame < dataframe > `
A DataFrame with id of and reference to LV gener... | genos_mv = pd . DataFrame ( columns = ( 'id' , 'obj' ) )
genos_lv = pd . DataFrame ( columns = ( 'id' , 'obj' ) )
genos_lv_agg = pd . DataFrame ( columns = ( 'la_id' , 'id' , 'obj' ) )
# MV genos
for geno in network . mv_grid . graph . nodes_by_attribute ( 'generator' ) :
genos_mv . loc [ len ( genos_mv ) ] = [ int... |
def _computeArray ( self , funcTilde , R , z , phi ) :
"""NAME :
_ computeArray
PURPOSE :
evaluate the density or potential for a given array of coordinates
INPUT :
funcTidle - must be _ rhoTilde or _ phiTilde
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
OUTPUT :
densi... | R = nu . array ( R , dtype = float ) ;
z = nu . array ( z , dtype = float ) ;
phi = nu . array ( phi , dtype = float ) ;
shape = ( R * z * phi ) . shape
if shape == ( ) :
return nu . sum ( self . _compute ( funcTilde , R , z , phi ) )
R = R * nu . ones ( shape ) ;
z = z * nu . ones ( shape ) ;
phi = phi * nu . ones... |
def _create_bundle ( self , version ) :
"""Initialise NIDM - Results bundle .""" | # * * * Bundle entity
if not hasattr ( self , 'bundle_ent' ) :
self . bundle_ent = NIDMResultsBundle ( nidm_version = version [ 'num' ] )
self . bundle = ProvBundle ( identifier = self . bundle_ent . id )
self . bundle_ent . export ( self . version , self . export_dir )
# # provn export
# self . bundle = ProvBundle... |
def v6_nd_suppress_ra ( self , ** kwargs ) :
"""Disable IPv6 Router Advertisements
Args :
int _ type ( str ) : Type of interface . ( gigabitethernet ,
tengigabitethernet , etc )
name ( str ) : Name of interface . ( 1/0/5 , 1/0/10 , etc )
rbridge _ id ( str ) : rbridge - id for device . Only required when ... | int_type = str ( kwargs . pop ( 'int_type' ) . lower ( ) )
name = str ( kwargs . pop ( 'name' ) )
callback = kwargs . pop ( 'callback' , self . _callback )
int_types = [ 'gigabitethernet' , 'tengigabitethernet' , 'fortygigabitethernet' , 'hundredgigabitethernet' , 've' ]
if int_type not in int_types :
raise ValueEr... |
def symbol_top ( body_output , targets , model_hparams , vocab_size ) :
"""Generate logits .
Args :
body _ output : A Tensor with shape
[ batch , p0 , p1 , model _ hparams . hidden _ size ] .
targets : Unused .
model _ hparams : HParams , model hyperparmeters .
vocab _ size : int , vocabulary size .
R... | del targets
# unused arg
if model_hparams . shared_embedding_and_softmax_weights :
scope_name = "shared"
reuse = tf . AUTO_REUSE
else :
scope_name = "softmax"
reuse = False
with tf . variable_scope ( scope_name , reuse = reuse ) :
body_output_shape = common_layers . shape_list ( body_output )
va... |
def logpdf ( x , mean = None , cov = 1 , allow_singular = True ) :
"""Computes the log of the probability density function of the normal
N ( mean , cov ) for the data x . The normal may be univariate or multivariate .
Wrapper for older versions of scipy . multivariate _ normal . logpdf which
don ' t support s... | if mean is not None :
flat_mean = np . asarray ( mean ) . flatten ( )
else :
flat_mean = None
flat_x = np . asarray ( x ) . flatten ( )
if _support_singular :
return multivariate_normal . logpdf ( flat_x , flat_mean , cov , allow_singular )
return multivariate_normal . logpdf ( flat_x , flat_mean , cov ) |
def parse_client_cert_pair ( config_value ) :
"""Parses the client cert pair from config item .
: param config _ value : the string value of config item .
: returns : tuple or none .""" | if not config_value :
return
client_cert = config_value . split ( ':' )
if len ( client_cert ) != 2 :
tips = ( 'client_cert should be formatted like ' '"/path/to/cert.pem:/path/to/key.pem"' )
raise ValueError ( '{0!r} is invalid.\n{1}' . format ( config_value , tips ) )
return tuple ( client_cert ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.