signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def train ( sess , loss , x_train , y_train , init_all = False , evaluate = None , feed = None , args = None , rng = None , var_list = None , fprop_args = None , optimizer = None , devices = None , x_batch_preprocessor = None , use_ema = False , ema_decay = .998 , run_canary = None , loss_threshold = 1e5 , dataset_trai... | # Check whether the hardware is working correctly
canary . run_canary ( )
if run_canary is not None :
warnings . warn ( "The `run_canary` argument is deprecated. The canary " "is now much cheaper and thus runs all the time. The " "canary now uses its own loss function so it is not " "necessary to turn off the canar... |
def draw ( self , true_classes ) :
"""Draw samples from log uniform distribution and returns sampled candidates ,
expected count for true classes and sampled classes .""" | range_max = self . range_max
num_sampled = self . num_sampled
ctx = true_classes . context
log_range = math . log ( range_max + 1 )
num_tries = 0
true_classes = true_classes . reshape ( ( - 1 , ) )
sampled_classes , num_tries = self . sampler . sample_unique ( num_sampled )
true_cls = true_classes . as_in_context ( ctx... |
def _deserialize ( self ) :
"""Try and deserialize a response body based upon the specified
content type .
: rtype : mixed""" | if not self . _responses or not self . _responses [ - 1 ] . body :
return None
if 'Content-Type' not in self . _responses [ - 1 ] . headers :
return self . _responses [ - 1 ] . body
try :
content_type = algorithms . select_content_type ( [ headers . parse_content_type ( self . _responses [ - 1 ] . headers [... |
def cmpr ( self , val1 , name , val2 ) :
'''Compare the two values using the given type specific comparator .''' | ctor = self . getCmprCtor ( name )
if ctor is None :
raise s_exc . NoSuchCmpr ( cmpr = name , name = self . name )
norm1 = self . norm ( val1 ) [ 0 ]
norm2 = self . norm ( val2 ) [ 0 ]
return ctor ( norm2 ) ( norm1 ) |
def calculate_shannon_entropy ( self , data ) :
"""In our investigations , we have found that when the input is all digits ,
the number of false positives we get greatly exceeds realistic true
positive scenarios .
Therefore , this tries to capture this heuristic mathemetically .
We do this by noting that th... | entropy = super ( HexHighEntropyString , self ) . calculate_shannon_entropy ( data )
if len ( data ) == 1 :
return entropy
try :
int ( data )
# This multiplier was determined through trial and error , with the
# intent of keeping it simple , yet achieving our goals .
entropy -= 1.2 / math . log ( le... |
def references ( self , env , object_name , model , assoc_class , result_class_name , role , result_role , keys_only ) :
"""Instrument Associations .
All four association - related operations ( Associators , AssociatorNames ,
References , ReferenceNames ) are mapped to this method .
This method is a python ge... | pass |
def call ( self , transaction = None , block_identifier = 'latest' ) :
"""Execute a contract function call using the ` eth _ call ` interface .
This method prepares a ` ` Caller ` ` object that exposes the contract
functions and public variables as callable Python functions .
Reading a public ` ` owner ` ` ad... | if transaction is None :
call_transaction = { }
else :
call_transaction = dict ( ** transaction )
if 'data' in call_transaction :
raise ValueError ( "Cannot set data in call transaction" )
if self . address :
call_transaction . setdefault ( 'to' , self . address )
if self . web3 . eth . defaultAccount i... |
def updateParamsets ( self ) :
"""Devices should update their own paramsets . They rely on the state of the server . Hence we pull all paramsets .""" | try :
for ps in self . _PARAMSETS :
self . updateParamset ( ps )
return True
except Exception as err :
LOG . error ( "HMGeneric.updateParamsets: Exception: " + str ( err ) )
return False |
def get_nailing ( expnum , ccd ) :
"""Get the ' nailing ' images associated with expnum""" | sql = """
SELECT e.expnum, (e.mjdate - f.mjdate) dt
FROM bucket.exposure e
JOIN bucket.exposure f
JOIN bucket.association b ON b.expnum=f.expnum
JOIN bucket.association a ON a.pointing=b.pointing AND a.expnum=e.expnum
WHERE f.expnum=%d
AND abs(e.mjdate - f.mjdate) > 0.5
AND abs(e.mjdate ... |
def copy ( self ) :
"""Make a copy of this SimLibrary , allowing it to be mutated without affecting the global version .
: return : A new SimLibrary object with the same library references but different dict / list references""" | o = SimLibrary ( )
o . procedures = dict ( self . procedures )
o . non_returning = set ( self . non_returning )
o . prototypes = dict ( self . prototypes )
o . default_ccs = dict ( self . default_ccs )
o . names = list ( self . names )
return o |
def get ( self , uri ) :
'''Get the content for the bodypart identified by the uri .''' | if uri . startswith ( 'cid:' ) : # Content - ID , so raise exception if not found .
head , part = self . id_dict [ uri [ 4 : ] ]
return StringIO . StringIO ( part . getvalue ( ) )
if self . loc_dict . has_key ( uri ) :
head , part = self . loc_dict [ uri ]
return StringIO . StringIO ( part . getvalue ( ... |
def __clean ( self , misp_response ) :
""": param misp _ response :
: return :""" | response = [ ]
for event in misp_response . get ( 'response' , [ ] ) :
response . append ( self . __clean_event ( event [ 'Event' ] ) )
return response |
def getSizedInteger ( self , data , byteSize , as_number = False ) :
"""Numbers of 8 bytes are signed integers when they refer to numbers , but unsigned otherwise .""" | result = 0
if byteSize == 0 :
raise InvalidPlistException ( "Encountered integer with byte size of 0." )
# 1 , 2 , and 4 byte integers are unsigned
elif byteSize == 1 :
result = unpack ( '>B' , data ) [ 0 ]
elif byteSize == 2 :
result = unpack ( '>H' , data ) [ 0 ]
elif byteSize == 4 :
result = unpack (... |
def delete_dataset ( self , dataset_id , delete_contents = False , project_id = None ) :
"""Delete a BigQuery dataset .
Parameters
dataset _ id : str
Unique ` ` str ` ` identifying the dataset with the project ( the
referenceId of the dataset )
Unique ` ` str ` ` identifying the BigQuery project contains ... | project_id = self . _get_project_id ( project_id )
try :
datasets = self . bigquery . datasets ( )
request = datasets . delete ( projectId = project_id , datasetId = dataset_id , deleteContents = delete_contents )
response = request . execute ( num_retries = self . num_retries )
if self . swallow_result... |
def get_child_values ( parent , names ) :
"""return a list of values for the specified child fields . If field not in Element then replace with nan .""" | vals = [ ]
for name in names :
if parent . HasElement ( name ) :
vals . append ( XmlHelper . as_value ( parent . GetElement ( name ) ) )
else :
vals . append ( np . nan )
return vals |
def read_model ( self ) :
"""Read the model and the couplings from the model file .""" | if self . verbosity > 0 :
settings . m ( 0 , 'reading model' , self . model )
# read model
boolRules = [ ]
for line in open ( self . model ) :
if line . startswith ( '#' ) and 'modelType =' in line :
keyval = line
if '|' in line :
keyval , type = line . split ( '|' ) [ : 2 ]
... |
def and_yields ( self , * values ) :
"""Expects the return value of the expectation to be a generator of the
given values""" | def generator ( ) :
for value in values :
yield value
self . __expect ( Expectation , Invoke ( generator ) ) |
def serveUpcoming ( self , request ) :
"""Upcoming events list view .""" | myurl = self . get_url ( request )
today = timezone . localdate ( )
monthlyUrl = myurl + self . reverse_subpage ( 'serveMonth' , args = [ today . year , today . month ] )
weekNum = gregorian_to_week_date ( today ) [ 1 ]
weeklyUrl = myurl + self . reverse_subpage ( 'serveWeek' , args = [ today . year , weekNum ] )
listU... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : ModelBuildContext for this ModelBuildInstance
: rtype : twilio . rest . autopilot . v1 . assistant . model _ build . Model... | if self . _context is None :
self . _context = ModelBuildContext ( self . _version , assistant_sid = self . _solution [ 'assistant_sid' ] , sid = self . _solution [ 'sid' ] , )
return self . _context |
def _to_str_columns ( self ) :
"""Render a DataFrame to a list of columns ( as lists of strings ) .""" | frame = self . tr_frame
# may include levels names also
str_index = self . _get_formatted_index ( frame )
str_columns = self . _get_formatted_column_labels ( frame )
if self . header :
stringified = [ ]
for i , c in enumerate ( frame . columns ) :
cheader = str_columns [ i ]
max_colwidth = max (... |
def send_vdp_msg ( self , mode , mgrid , typeid , typeid_ver , vsiid_frmt , vsiid , filter_frmt , gid , mac , vlan , oui_id , oui_data , sw_resp ) :
"""Constructs and Sends the VDP Message .
Please refer http : / / www . ieee802 . org / 1 / pages / 802.1bg . html VDP
Section for more detailed information
: pa... | if not self . is_ncb :
LOG . error ( "EVB cannot be set on NB" )
return
vdp_key_str = self . construct_vdp_dict ( mode , mgrid , typeid , typeid_ver , vsiid_frmt , vsiid , filter_frmt , gid , mac , vlan , oui_id , oui_data )
if len ( vdp_key_str ) == 0 :
LOG . error ( "NULL List" )
return
oui_cmd_str = ... |
def set_score ( submission_uuid , points_earned , points_possible , annotation_creator = None , annotation_type = None , annotation_reason = None ) :
"""Set a score for a particular submission .
Sets the score for a particular submission . This score is calculated
externally to the API .
Args :
submission _... | try :
submission_model = _get_submission_model ( submission_uuid )
except Submission . DoesNotExist :
raise SubmissionNotFoundError ( u"No submission matching uuid {}" . format ( submission_uuid ) )
except DatabaseError :
error_msg = u"Could not retrieve submission {}." . format ( submission_uuid )
logg... |
def assess_car_t_validity ( job , gene_expression , univ_options , reports_options ) :
"""This function creates a report on the available clinical trials and scientific literature
available for the overexpressed genes in the specified tumor type .
It also gives a list of clinical trials available for other type... | work_dir = os . getcwd ( )
tumor_type = univ_options [ 'tumor_type' ]
input_files = { 'rsem_quant.tsv' : gene_expression , 'car_t_targets.tsv.tar.gz' : reports_options [ 'car_t_targets_file' ] }
input_files = get_files_from_filestore ( job , input_files , work_dir , docker = False )
input_files [ 'car_t_targets.tsv' ] ... |
def fetch ( ) :
"""Downloads the Planck Collaboration ( 2013 ) dust map , placing it in the
default ` ` dustmaps ` ` data directory .""" | url = 'http://pla.esac.esa.int/pla/aio/product-action?MAP.MAP_ID=HFI_CompMap_ThermalDustModel_2048_R1.20.fits'
md5 = '8d804f4e64e709f476a63f0dfed1fd11'
fname = os . path . join ( data_dir ( ) , 'planck' , 'HFI_CompMap_ThermalDustModel_2048_R1.20.fits' )
fetch_utils . download_and_verify ( url , md5 , fname = fname ) |
def find_all_output_in_range ( self , ifo , currSeg , useSplitLists = False ) :
"""Return all files that overlap the specified segment .""" | if not useSplitLists : # Slower , but simpler method
outFiles = [ i for i in self if ifo in i . ifo_list ]
outFiles = [ i for i in outFiles if i . segment_list . intersects_segment ( currSeg ) ]
else : # Faster , but more complicated
# Basically only check if a subset of files intersects _ segment by
# using a ... |
def cache_control ( max_age = None , private = False , public = False , s_maxage = None , must_revalidate = False , proxy_revalidate = False , no_cache = False , no_store = False ) :
"""Generate the value for a Cache - Control header .
Example :
> > > from rhino . http import cache _ control as cc
> > > from ... | if all ( [ private , public ] ) :
raise ValueError ( "'private' and 'public' are mutually exclusive" )
if isinstance ( max_age , timedelta ) :
max_age = int ( total_seconds ( max_age ) )
if isinstance ( s_maxage , timedelta ) :
s_maxage = int ( total_seconds ( s_maxage ) )
directives = [ ]
if public :
d... |
def list_media_services ( access_token , subscription_id ) :
'''List the media services in a subscription .
Args :
access _ token ( str ) : A valid Azure authentication token .
subscription _ id ( str ) : Azure subscription id .
Returns :
HTTP response . JSON body .''' | endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/providers/microsoft.media/mediaservices?api-version=' , MEDIA_API ] )
return do_get ( endpoint , access_token ) |
def get_jobs ( when = None , only_scheduled = False ) :
"""Return a dictionary mapping of job names together with their respective
application class .""" | # FIXME : HACK : make sure the project dir is on the path when executed as . / manage . py
try :
cpath = os . path . dirname ( os . path . realpath ( sys . argv [ 0 ] ) )
ppath = os . path . dirname ( cpath )
if ppath not in sys . path :
sys . path . append ( ppath )
except Exception :
pass
_job... |
def get_prefix ( self , key_prefix , ** kwargs ) :
"""Get a range of keys with a prefix .
: param key _ prefix : first key in range
: param keys _ only : if True , retrieve only the keys , not the values
: returns : sequence of ( value , metadata ) tuples""" | range_response = self . get_prefix_response ( key_prefix , ** kwargs )
for kv in range_response . kvs :
yield ( kv . value , KVMetadata ( kv , range_response . header ) ) |
def refresh_session ( self , session = None ) :
"""Return updated session if token has expired , attempts to
refresh using newly acquired token .
If a session object is provided , configure it directly . Otherwise ,
create a new session and return it .
: param session : The session to configure for authenti... | if 'refresh_token' in self . token :
try :
token = self . _context . acquire_token_with_refresh_token ( self . token [ 'refresh_token' ] , self . id , self . resource , self . secret # This is needed when using Confidential Client
)
self . token = self . _convert_token ( token )
except a... |
def user_info ( name , ** client_args ) :
'''Get information about given user .
name
Name of the user for which to get information .
CLI Example :
. . code - block : : bash
salt ' * ' influxdb . user _ info < name >''' | matching_users = ( user for user in list_users ( ** client_args ) if user . get ( 'user' ) == name )
try :
return next ( matching_users )
except StopIteration :
pass |
def year_origin_filter ( year_predicate = None , origin_predicate = None ) :
"""Returns a predicate for cable identifiers where ` year _ predicate ` and
` origin _ predicate ` must hold true .
If ` year _ predicate ` and ` origin _ predicate ` is ` ` None ` ` the returned
predicate holds always true .
` yea... | def accept ( cable_id , predicate ) :
year , origin = _YEAR_ORIGIN_PATTERN . match ( canonicalize_id ( cable_id ) ) . groups ( )
return predicate ( year , origin )
if year_predicate and origin_predicate :
return partial ( accept , predicate = lambda y , o : year_predicate ( y ) and origin_predicate ( o ) )
... |
def generic_visit ( self , pattern ) :
"""Check if the pattern match with the checked node .
a node match if :
- type match
- all field match""" | return ( isinstance ( pattern , type ( self . node ) ) and all ( self . field_match ( value , getattr ( pattern , field ) ) for field , value in iter_fields ( self . node ) ) ) |
def flush ( self ) :
"""Sends the current . batch to Cloud Bigtable .
For example :
. . literalinclude : : snippets . py
: start - after : [ START bigtable _ batcher _ flush ]
: end - before : [ END bigtable _ batcher _ flush ]""" | if len ( self . rows ) != 0 :
self . table . mutate_rows ( self . rows )
self . total_mutation_count = 0
self . total_size = 0
self . rows = [ ] |
def _autorestart_store_components ( self , bundle ) : # type : ( Bundle ) - > None
"""Stores the components of the given bundle with the auto - restart
property
: param bundle : A Bundle object""" | with self . __instances_lock : # Prepare the list of components
store = self . __auto_restart . setdefault ( bundle , [ ] )
for stored_instance in self . __instances . values ( ) : # Get the factory name
factory = stored_instance . factory_name
if self . get_factory_bundle ( factory ) is bundle ... |
def output_files ( self ) :
"""Returns the list of output files from this rule .
Paths are generated from the outputs of this rule ' s dependencies , with
their paths translated based on prefix and strip _ prefix .
Returned paths are relative to buildroot .""" | for dep in self . subgraph . successors ( self . address ) :
dep_rule = self . subgraph . node [ dep ] [ 'target_obj' ]
for dep_file in dep_rule . output_files :
yield self . translate_path ( dep_file , dep_rule ) . lstrip ( '/' ) |
def set_logxticks ( self , row , column , logticks ) :
"""Manually specify the x - axis log tick values .
: param row , column : specify the subplot .
: param logticks : logarithm of the locations for the ticks along the
axis .
For example , if you specify [ 1 , 2 , 3 ] , ticks will be placed at 10,
100 a... | subplot = self . get_subplot_at ( row , column )
subplot . set_logxticks ( logticks ) |
def make_outpoint ( tx_id_le , index , tree = None ) :
'''byte - like , int , int - > Outpoint''' | if 'decred' in riemann . get_current_network_name ( ) :
return tx . DecredOutpoint ( tx_id = tx_id_le , index = utils . i2le_padded ( index , 4 ) , tree = utils . i2le_padded ( tree , 1 ) )
return tx . Outpoint ( tx_id = tx_id_le , index = utils . i2le_padded ( index , 4 ) ) |
def __create ( self , type , ** kwargs ) :
"""Call documentation : ` / user / mfa / create
< https : / / www . wepay . com / developer / reference / user - mfa # create > ` _ , plus
extra keyword parameter :
: keyword bool batch _ mode : turn on / off the batch _ mode , see
: class : ` wepay . api . WePay `... | params = { 'type' : type }
return self . make_call ( self . __create , params , kwargs ) |
def tolocal ( self ) :
"""Convert to local mode .""" | from thunder . series . readers import fromarray
if self . mode == 'local' :
logging . getLogger ( 'thunder' ) . warn ( 'images already in local mode' )
pass
return fromarray ( self . toarray ( ) , index = self . index , labels = self . labels ) |
def duplicate ( self , fullname , shortname , categoryid , visible = True , ** kwargs ) :
"""Duplicates an existing course with options .
Note : Can be very slow running .
: param string fullname : The new course ' s full name
: param string shortname : The new course ' s short name
: param string categoryi... | # TODO
# Ideally categoryid should be optional here and
# should default to catid of course being duplicated .
allowed_options = [ 'activities' , 'blocks' , 'filters' , 'users' , 'role_assignments' , 'comments' , 'usercompletion' , 'logs' , 'grade_histories' ]
if valid_options ( kwargs , allowed_options ) :
option_... |
def write ( self ) :
"""Restore GFF3 entry to original format
Returns :
str : properly formatted string containing the GFF3 entry""" | none_type = type ( None )
# Format attributes for writing
attrs = self . attribute_string ( )
# Place holder if field value is NoneType
for attr in self . __dict__ . keys ( ) :
if type ( attr ) == none_type :
setattr ( self , attr , '.' )
# Format entry for writing
fstr = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\... |
def wr_hdrs ( self , worksheet , row_idx ) :
"""Print row of column headers""" | for col_idx , hdr in enumerate ( self . hdrs ) : # print ( " ROW ( { R } ) COL ( { C } ) HDR ( { H } ) FMT ( { F } ) \ n " . format (
# R = row _ idx , C = col _ idx , H = hdr , F = self . fmt _ hdr ) )
worksheet . write ( row_idx , col_idx , hdr , self . fmt_hdr )
row_idx += 1
return row_idx |
def wall ( self ) :
"""refresh the token from the API
then call a Wallabag instance
then store the token
: return : wall instance""" | us = UserService . objects . get ( user = self . user , name = 'ServiceWallabag' )
params = { 'client_id' : us . client_id , 'client_secret' : us . client_secret , 'username' : us . username , 'password' : us . password , }
try :
token = Wall . get_token ( host = us . host , ** params )
except Exception as e :
... |
def create_agent ( self , configuration , agent_id = "" ) :
"""Create an agent .
: param dict configuration : Form given by the craftai documentation .
: param str agent _ id : Optional . The id of the agent to create . It
must be an str containing only characters in " a - zA - Z0-9 _ - " and
must be betwee... | # Extra header in addition to the main session ' s
ct_header = { "Content-Type" : "application/json; charset=utf-8" }
# Building payload and checking that it is valid for a JSON
# serialization
payload = { "configuration" : configuration }
if agent_id != "" : # Raises an error when agent _ id is invalid
self . _che... |
def todict ( self ) :
"""Convert namedtuple to dict .""" | return OrderedDict ( ( name , self [ i ] ) for i , name in enumerate ( self . _fields ) ) |
def _infinite_iterator ( self ) :
"""this iterator wraps the " _ basic _ iterator " when the configuration
specifies that the " number _ of _ submissions " is set to " forever " .
Whenever the " _ basic _ iterator " is exhausted , it is called again to
restart the iteration . It is up to the implementation of... | while True :
for crash_id in self . _basic_iterator ( ) :
if self . _filter_disallowed_values ( crash_id ) :
continue
yield crash_id |
def from_bytes ( cls , bitstream ) :
r'''Parse the given packet and update properties accordingly
> > > data _ hex = ( ' 13000001ae92b5574f849cd00001ac10'
. . . ' 1f0300015cfe1cbd00200001ac101f01 ' )
> > > data = data _ hex . decode ( ' hex ' )
> > > message = ControlMessage . from _ bytes ( data )
> > > ... | packet = cls ( )
# Convert to ConstBitStream ( if not already provided )
if not isinstance ( bitstream , ConstBitStream ) :
if isinstance ( bitstream , Bits ) :
bitstream = ConstBitStream ( auto = bitstream )
else :
bitstream = ConstBitStream ( bytes = bitstream )
# Read the message type
type_nr... |
async def auth ( self ) :
"""Perform AirPlay device authentication .""" | credentials = await self . atv . airplay . generate_credentials ( )
await self . atv . airplay . load_credentials ( credentials )
try :
await self . atv . airplay . start_authentication ( )
pin = await _read_input ( self . loop , 'Enter PIN on screen: ' )
await self . atv . airplay . finish_authentication (... |
def get_params_parser ( ) :
"""Parse command line arguments""" | parser = argparse . ArgumentParser ( )
parser . add_argument ( "-e" , "--elastic_url" , default = "http://127.0.0.1:9200" , help = "Host with elastic search (default: http://127.0.0.1:9200)" )
parser . add_argument ( '-g' , '--debug' , dest = 'debug' , action = 'store_true' )
parser . add_argument ( '-t' , '--token' , ... |
def unset_iscsi_info ( self ) :
"""Disable iSCSI boot option in UEFI boot mode .
: raises : IloError , on an error from iLO .
: raises : IloCommandNotSupportedInBiosError , if the system is
in the BIOS boot mode .""" | if ( self . _is_boot_mode_uefi ( ) is True ) :
iscsi_info = { 'iSCSIBootEnable' : 'Disabled' }
self . _change_iscsi_settings ( iscsi_info )
else :
msg = 'iSCSI boot is not supported in the BIOS boot mode'
raise exception . IloCommandNotSupportedInBiosError ( msg ) |
def scale ( cls , * scaling ) :
"""Create a scaling transform from a scalar or vector .
: param scaling : The scaling factor . A scalar value will
scale in both dimensions equally . A vector scaling
value scales the dimensions independently .
: type scaling : float or sequence
: rtype : Affine""" | if len ( scaling ) == 1 :
sx = sy = float ( scaling [ 0 ] )
else :
sx , sy = scaling
return tuple . __new__ ( cls , ( sx , 0.0 , 0.0 , 0.0 , sy , 0.0 , 0.0 , 0.0 , 1.0 ) ) |
def write_pdb ( self , custom_name = '' , out_suffix = '' , out_dir = None , custom_selection = None , force_rerun = False ) :
"""Write a new PDB file for the Structure ' s FIRST MODEL .
Set custom _ selection to a PDB . Select class for custom SMCRA selections .
Args :
custom _ name : Filename of the new fil... | if not custom_selection :
custom_selection = ModelSelection ( [ 0 ] )
# If no output directory , custom name , or suffix is specified , add a suffix " _ new "
if not out_dir or not custom_name :
if not out_suffix :
out_suffix = '_new'
# Prepare the output file path
outfile = ssbio . utils . outfile_make... |
def split ( examples , ratio = 0.8 ) :
"""Utility function that can be used within the parse ( ) implementation of
sub classes to split a list of example into two lists for training and
testing .""" | split = int ( ratio * len ( examples ) )
return examples [ : split ] , examples [ split : ] |
def _make_chunk_size ( self , req_size ) :
"""Takes an allocation size as requested by the user and modifies it to be a suitable chunk size .""" | size = req_size
size += 2 * self . _chunk_size_t_size
# Two size fields
size = self . _chunk_min_size if size < self . _chunk_min_size else size
if size & self . _chunk_align_mask : # If the chunk would not be aligned
size = ( size & ~ self . _chunk_align_mask ) + self . _chunk_align_mask + 1
# Fix it
return si... |
def cermine_dois ( pdf_file , force_api = False , override_local = None ) :
"""Run ` CERMINE < https : / / github . com / CeON / CERMINE > ` _ to extract DOIs of cited papers from a PDF file .
. . note : :
Try to use a local CERMINE JAR file , and falls back to using the API . JAR file is expected to be found i... | # TODO :
# * Do not convert to plain text , but use the extra metadata from
# CERMINE
# Call CERMINE on the PDF file
cermine_output = cermine ( pdf_file , force_api , override_local )
# Parse the resulting XML
root = ET . fromstring ( cermine_output )
plaintext_references = [ # Remove extra whitespaces
tools . clean_wh... |
def steem_to_sbd ( self , steemamt = 0 , price = 0 , account = None ) :
'''Uses the ticker to get the highest bid
and moves the steem at that price .''' | if not account :
account = self . mainaccount
if self . check_balances ( account ) :
if steemamt == 0 :
steemamt = self . steembal
elif steemamt > self . steembal :
self . msg . error_message ( "INSUFFICIENT FUNDS. CURRENT STEEM BAL: " + str ( self . steembal ) )
return False
if ... |
def _set_properties ( self , resource ) :
"""Update properties from resource in body of ` ` api _ response ` `
: type resource : dict
: param resource : variable representation returned from the API .""" | self . _properties . clear ( )
cleaned = resource . copy ( )
if "name" in cleaned :
self . name = variable_name_from_full_name ( cleaned . pop ( "name" ) )
self . _properties . update ( cleaned ) |
def plot_power_factor_mu ( self , temp = 600 , output = 'eig' , relaxation_time = 1e-14 , xlim = None ) :
"""Plot the power factor in function of Fermi level . Semi - log plot
Args :
temp : the temperature
xlim : a list of min and max fermi energy by default ( 0 , and band
gap )
tau : A relaxation time in... | import matplotlib . pyplot as plt
plt . figure ( figsize = ( 9 , 7 ) )
pf = self . _bz . get_power_factor ( relaxation_time = relaxation_time , output = output , doping_levels = False ) [ temp ]
plt . semilogy ( self . _bz . mu_steps , pf , linewidth = 3.0 )
self . _plot_bg_limits ( )
self . _plot_doping ( temp )
if ou... |
def filter ( args ) :
"""% prog filter test . blast
Produce a new blast file and filter based on :
- score : > = cutoff
- pctid : > = cutoff
- hitlen : > = cutoff
- evalue : < = cutoff
- ids : valid ids
Use - - inverse to obtain the complementary records for the criteria above .
- noself : remove se... | p = OptionParser ( filter . __doc__ )
p . add_option ( "--score" , dest = "score" , default = 0 , type = "int" , help = "Score cutoff" )
p . set_align ( pctid = 95 , hitlen = 100 , evalue = .01 )
p . add_option ( "--noself" , default = False , action = "store_true" , help = "Remove self-self hits" )
p . add_option ( "-... |
def _close ( self ) :
"""Close connection to remote host .""" | if self . _process is None :
return
self . quit ( )
self . _process . stdin . close ( )
logger . debug ( "Waiting for ssh process to finish..." )
self . _process . wait ( )
# Wait for ssh session to finish .
# self . _ process . terminate ( )
# self . _ process . kill ( )
self . _process = None |
def predicatesOut ( G : Graph , n : Node ) -> Set [ TriplePredicate ] :
"""predicatesOut ( G , n ) is the set of predicates in arcsOut ( G , n ) .""" | return { p for p , _ in G . predicate_objects ( n ) } |
def increment ( self , member , amount = 1 ) :
"""Increment the score of ` ` member ` ` by ` ` amount ` ` .""" | self . _dict [ member ] += amount
return self . _dict [ member ] |
def __run_embedded ( db_name , argv ) :
"""Runs the Database device server embeded in another TANGO Database
( just like any other TANGO device server )""" | __monkey_patch_database_class ( )
run ( ( DataBase , ) , args = argv , util = util , green_mode = GreenMode . Gevent ) |
def calmarnorm ( sharpe , T , tau = 1.0 ) :
'''Multiplicator for normalizing calmar ratio to period tau''' | return calmar ( sharpe , tau ) / calmar ( sharpe , T ) |
def get_instance ( self , payload ) :
"""Build an instance of TollFreeInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . api . v2010 . account . available _ phone _ number . toll _ free . TollFreeInstance
: rtype : twilio . rest . api . v2010 . account . available _ phon... | return TollFreeInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , country_code = self . _solution [ 'country_code' ] , ) |
def vswitch_delete ( self , vswitch_name , persist = True ) :
"""Delete vswitch .
: param str name : the vswitch name
: param bool persist : whether delete the vswitch from the permanent
configuration for the system""" | self . _networkops . delete_vswitch ( vswitch_name , persist ) |
def aes_b64_decrypt ( value , secret , block_size = AES . block_size ) :
"""AES decrypt @ value with @ secret using the | CFB | mode of AES
with a cryptographically secure initialization vector .
- > ( # str ) AES decrypted @ value
from vital . security import aes _ encrypt , aes _ decrypt
aes _ encrypt ( "... | if value is not None :
iv = value [ : block_size ]
cipher = AES . new ( secret [ : 32 ] , AES . MODE_CFB , iv )
return cipher . decrypt ( b64decode ( uniorbytes ( value [ block_size * 2 : ] , bytes ) ) ) . decode ( 'utf-8' ) |
def _CheckIsSocket ( self , file_entry ) :
"""Checks the is _ socket find specification .
Args :
file _ entry ( FileEntry ) : file entry .
Returns :
bool : True if the file entry matches the find specification , False if not .""" | if definitions . FILE_ENTRY_TYPE_SOCKET not in self . _file_entry_types :
return False
return file_entry . IsSocket ( ) |
def saveSettings ( self , groupName = None ) :
"""Writes the registry items into the persistent settings store .""" | groupName = groupName if groupName else self . settingsGroupName
settings = QtCore . QSettings ( )
logger . info ( "Saving {} to: {}" . format ( groupName , settings . fileName ( ) ) )
settings . remove ( groupName )
# start with a clean slate
settings . beginGroup ( groupName )
try :
for itemNr , item in enumerate... |
def DeserializeFromBufer ( buffer , offset = 0 ) :
"""Deserialize object instance from the specified buffer .
Args :
buffer ( bytes , bytearray , BytesIO ) : ( Optional ) data to create the stream from .
offset : UNUSED
Returns :
Transaction :""" | mstream = StreamManager . GetStream ( buffer )
reader = BinaryReader ( mstream )
tx = Transaction . DeserializeFrom ( reader )
StreamManager . ReleaseStream ( mstream )
return tx |
def prox_l0 ( v , alpha ) :
r"""Compute the proximal operator of the : math : ` \ ell _ 0 ` " norm " ( hard
thresholding )
. . math : :
\ mathrm { prox } _ { \ alpha f } ( v ) = \ mathcal { S } _ { 0 , \ alpha } ( \ mathbf { v } )
= \ left \ { \ begin { array } { ccc } 0 & \ text { if } &
| v | < \ sqrt {... | return ( np . abs ( v ) >= np . sqrt ( 2.0 * alpha ) ) * v |
def deploy_directory ( directory , auth = None ) :
"""Deploy all files in a given directory .
: param str directory : the path to a directory
: param tuple [ str ] auth : A pair of ( str username , str password ) to give to the auth keyword of the constructor of
: class : ` artifactory . ArtifactoryPath ` . D... | for file in os . listdir ( directory ) :
full_path = os . path . join ( directory , file )
if file . endswith ( BELANNO_EXTENSION ) :
name = file [ : - len ( BELANNO_EXTENSION ) ]
log . info ( 'deploying annotation %s' , full_path )
deploy_annotation ( full_path , name , auth = auth )
... |
def fw_rule_create ( self , data , fw_name = None , cache = False ) :
"""Top level rule creation routine .""" | LOG . debug ( "FW Rule create %s" , data )
self . _fw_rule_create ( fw_name , data , cache ) |
def _set_environment_variables ( self ) :
"""Initializes the correct environment variables for spark""" | cmd = [ ]
# special case for driver JVM properties .
self . _set_launcher_property ( "driver-memory" , "spark.driver.memory" )
self . _set_launcher_property ( "driver-library-path" , "spark.driver.extraLibraryPath" )
self . _set_launcher_property ( "driver-class-path" , "spark.driver.extraClassPath" )
self . _set_launc... |
def handle ( self , * args , ** options ) :
"""Command handle .""" | models . Observer . objects . all ( ) . delete ( )
models . Subscriber . objects . all ( ) . delete ( )
for cache_key in cache . keys ( search = '{}*' . format ( THROTTLE_CACHE_PREFIX ) ) :
cache . delete ( cache_key ) |
def set_attributes ( self , doc , fields , parent_type = None ) :
"""Fields are specified as a list so that order is preserved for display
purposes only . ( Might be used for certain serialization formats . . . )
: param str doc : Description of type .
: param list ( Field ) fields : Ordered list of fields fo... | self . raw_doc = doc
self . doc = doc_unwrap ( doc )
self . fields = fields
self . parent_type = parent_type
self . _raw_examples = OrderedDict ( )
self . _examples = OrderedDict ( )
self . _fields_by_name = { }
# Dict [ str , Field ]
# Check that no two fields share the same name .
for field in self . fields :
if ... |
def load_act_node ( self ) -> ActNode :
"""Raises :
ValidationError : AAA01 when no act block is found and AAA02 when
multiple act blocks are found .""" | act_nodes = ActNode . build_body ( self . node . body )
if not act_nodes :
raise ValidationError ( self . first_line_no , self . node . col_offset , 'AAA01 no Act block found in test' )
# Allow ` pytest . raises ` and ` self . assertRaises ( ) ` in assert nodes - if
# any of the additional nodes are ` pytest . rais... |
def benchmark_forward ( self ) :
"""Benchmark forward execution .""" | self . _setup ( )
def f ( ) :
self . _forward ( )
self . mod_ext . synchronize ( ** self . ext_kwargs )
f ( )
# Ignore first
self . forward_stat = self . _calc_benchmark_stat ( f ) |
def flatten_reducer ( flattened_list : list , entry : typing . Union [ list , tuple , COMPONENT ] ) -> list :
"""Flattens a list of COMPONENT instances to remove any lists or tuples
of COMPONENTS contained within the list
: param flattened _ list :
The existing flattened list that has been populated from prev... | if hasattr ( entry , 'includes' ) and hasattr ( entry , 'files' ) :
flattened_list . append ( entry )
elif entry :
flattened_list . extend ( entry )
return flattened_list |
def _substitute ( self , var_map , safe = False ) :
"""Implementation of : meth : ` substitute ` .
For internal use , the ` safe ` keyword argument allows to perform a
substitution on the ` args ` and ` kwargs ` of the expression only ,
guaranteeing that the type of the expression does not change , at the
c... | if self in var_map :
if not safe or ( type ( var_map [ self ] ) == type ( self ) ) :
return var_map [ self ]
if isinstance ( self . __class__ , Singleton ) :
return self
new_args = [ substitute ( arg , var_map ) for arg in self . args ]
new_kwargs = { key : substitute ( val , var_map ) for ( key , val )... |
def plot_ebands_with_edos ( self , dos_pos = 0 , method = "gaussian" , step = 0.01 , width = 0.1 , ** kwargs ) :
"""Plot the band structure and the DOS .
Args :
dos _ pos : Index of the task from which the DOS should be obtained ( note : 0 refers to the first DOS task ) .
method : String defining the method f... | with self . nscf_task . open_gsr ( ) as gsr :
gs_ebands = gsr . ebands
with self . dos_tasks [ dos_pos ] . open_gsr ( ) as gsr :
dos_ebands = gsr . ebands
edos = dos_ebands . get_edos ( method = method , step = step , width = width )
return gs_ebands . plot_with_edos ( edos , ** kwargs ) |
def MODE ( self , setmode ) :
"""Set mode .""" | set_data = True
mode = None
if setmode == self . AUTO_MODE :
mode = 'AUTO_MODE'
elif setmode == self . MANU_MODE :
mode = 'MANU_MODE'
set_data = self . get_set_temperature ( )
elif setmode == self . BOOST_MODE :
mode = 'BOOST_MODE'
elif setmode == self . COMFORT_MODE :
mode = 'COMFORT_MODE'
elif set... |
def _wait_for_status ( linode_id , status = None , timeout = 300 , quiet = True ) :
'''Wait for a certain status from Linode .
linode _ id
The ID of the Linode to wait on . Required .
status
The status to look for to update .
timeout
The amount of time to wait for a status to update .
quiet
Log stat... | if status is None :
status = _get_status_id_by_name ( 'brand_new' )
status_desc_waiting = _get_status_descr_by_id ( status )
interval = 5
iterations = int ( timeout / interval )
for i in range ( 0 , iterations ) :
result = get_linode ( kwargs = { 'linode_id' : linode_id } )
if result [ 'STATUS' ] == status ... |
def id_field_name ( cls ) :
"""If only one primary _ key , then return it . Otherwise , raise ValueError .""" | if cls . _cache_id_field_name is None :
pk_names = cls . pk_names ( )
if len ( pk_names ) == 1 :
cls . _cache_id_field_name = pk_names [ 0 ]
else : # pragma : no cover
raise ValueError ( "{classname} has more than 1 primary key!" . format ( classname = cls . __name__ ) )
return cls . _cache_... |
def ExportToDjangoView ( request ) :
"""Exports / metrics as a Django view .
You can use django _ prometheus . urls to map / metrics to this view .""" | if 'prometheus_multiproc_dir' in os . environ :
registry = prometheus_client . CollectorRegistry ( )
multiprocess . MultiProcessCollector ( registry )
else :
registry = prometheus_client . REGISTRY
metrics_page = prometheus_client . generate_latest ( registry )
return HttpResponse ( metrics_page , content_t... |
def neighbors ( self , key ) :
"""Return dict of neighbor atom index and connecting bond .""" | return { n : attr [ "bond" ] for n , attr in self . graph [ key ] . items ( ) } |
def render_context_with_title ( self , context ) :
"""Render a page title and insert it into the context .
This function takes in a context dict and uses it to render the
page _ title variable . It then appends this title to the context using
the ' page _ title ' key . If there is already a page _ title key d... | if "page_title" not in context :
con = template . Context ( context )
# NOTE ( sambetts ) : Use force _ text to ensure lazy translations
# are handled correctly .
temp = template . Template ( encoding . force_text ( self . page_title ) )
context [ "page_title" ] = temp . render ( con )
return contex... |
def fire ( self , * args , ** kwargs ) :
"""Emit the signal , calling all coroutines in - line with the given
arguments and in the order they were registered .
This is obviously a coroutine .
Instead of calling : meth : ` fire ` explicitly , the ad - hoc signal object
itself can be called , too .""" | for token , coro in list ( self . _connections . items ( ) ) :
keep = yield from coro ( * args , ** kwargs )
if not keep :
del self . _connections [ token ] |
def _login ( session ) :
"""Login .
Use Selenium webdriver to login . USPS authenticates users
in part by a key generated by complex , obfuscated client - side
Javascript , which can ' t ( easily ) be replicated in Python .
Invokes the webdriver once to perform login , then uses the
resulting session cook... | _LOGGER . debug ( "attempting login" )
session . cookies . clear ( )
try :
session . remove_expired_responses ( )
except AttributeError :
pass
try :
driver = _get_driver ( session . auth . driver )
except WebDriverException as exception :
raise USPSError ( str ( exception ) )
driver . get ( LOGIN_URL )
... |
def sources ( self ) :
"""Returns a dictionary of source methods found on this object ,
keyed on method name . Source methods are identified by
( self , context ) arguments on this object . For example :
. . code - block : : python
def f ( self , context ) :
is a source method , but
. . code - block : :... | try :
return self . _sources
except AttributeError :
self . _sources = find_sources ( self )
return self . _sources |
def record_command ( self , cmd , prg = '' ) :
"""record the command passed - this is usually the name of the program
being run or task being run""" | self . _log ( self . logFileCommand , force_to_string ( cmd ) , prg ) |
def set_courses ( self , course_ids ) :
"""Sets the courses .
arg : course _ ids ( osid . id . Id [ ] ) : the course ` ` Ids ` `
raise : InvalidArgument - ` ` course _ ids ` ` is invalid
raise : NullArgument - ` ` course _ ids ` ` is ` ` null ` `
raise : NoAccess - ` ` Metadata . isReadOnly ( ) ` ` is ` ` t... | # Implemented from template for osid . learning . ActivityForm . set _ assets _ template
if not isinstance ( course_ids , list ) :
raise errors . InvalidArgument ( )
if self . get_courses_metadata ( ) . is_read_only ( ) :
raise errors . NoAccess ( )
idstr_list = [ ]
for object_id in course_ids :
if not self... |
def cmd_export_all ( * args ) :
"""Arguments :
< output folder > [ - - [ - - quality < 0-100 > ] [ - - page _ format < page _ format > ] ]
Export all documents as PDF files .
Default quality is 50.
Default page format is A4.
Possible JSON replies :
" status " : " error " , " exception " : " yyy " ,
" ... | ( output_dir , quality , page_format ) = _get_export_params ( args )
dsearch = get_docsearch ( )
try :
os . mkdir ( output_dir )
except FileExistsError : # NOQA ( Python 3 . x only )
pass
out = [ ]
docs = [ d for d in dsearch . docs ]
docs . sort ( key = lambda doc : doc . docid )
output_dir = FS . safe ( outpu... |
def render ( template , ** context ) :
'''Render a template with uData frontend specifics
* Theme''' | theme = current_app . config [ 'THEME' ]
return render_theme_template ( get_theme ( theme ) , template , ** context ) |
def doOutages ( self ) :
"""Applies branch outtages .""" | assert len ( self . branchOutages ) == len ( self . market . case . branches )
weights = [ [ ( False , r ) , ( True , 1 - ( r ) ) ] for r in self . branchOutages ]
for i , ln in enumerate ( self . market . case . branches ) :
ln . online = weighted_choice ( weights [ i ] )
if ln . online == False :
prin... |
def set_input_shape_ngpu ( self , new_input_shape ) :
"""Create and initialize layer parameters on the device previously set
in self . device _ name .
: param new _ input _ shape : a list or tuple for the shape of the input .""" | assert self . device_name , "Device name has not been set."
device_name = self . device_name
if self . input_shape is None : # First time setting the input shape
self . input_shape = [ None ] + [ int ( d ) for d in list ( new_input_shape ) ]
if device_name in self . params_device : # There is a copy of weights on t... |
def _got_message ( self , uid , text ) :
"""The controller has send us a message .
: param uid : Unique id of the controller
: param text : Text to display
: type uid : str
: type text : str""" | # TODO : use try
e = Event ( uid , E_MESSAGE , text )
self . queue . put_nowait ( e )
self . controllers [ uid ] [ 2 ] = time . time ( ) |
def _reference_rmvs ( self , removes ) :
"""Prints all removed packages""" | print ( "" )
self . msg . template ( 78 )
msg_pkg = "package"
if len ( removes ) > 1 :
msg_pkg = "packages"
print ( "| Total {0} {1} removed" . format ( len ( removes ) , msg_pkg ) )
self . msg . template ( 78 )
for pkg in removes :
if not GetFromInstalled ( pkg ) . name ( ) :
print ( "| Package {0} rem... |
def element ( self , inp = None ) :
"""Return an element from ` ` inp ` ` or from scratch .""" | if inp is not None :
s = str ( inp ) [ : self . length ]
s += ' ' * ( self . length - len ( s ) )
return s
else :
return ' ' * self . length |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.