signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def cors_setup ( self , request ) :
"""Sets up the CORS headers response based on the settings used for the API .
: param request : < pyramid . request . Request >""" | def cors_headers ( request , response ) :
if request . method . lower ( ) == 'options' :
response . headers . update ( { '-' . join ( [ p . capitalize ( ) for p in k . split ( '_' ) ] ) : v for k , v in self . cors_options . items ( ) } )
else :
origin = self . cors_options . get ( 'access_contr... |
def _ ( s : Influence , cutoff : float = 0.7 ) -> bool :
"""Returns true if both subj and obj are grounded to the UN ontology .""" | return all ( map ( lambda c : is_well_grounded ( c , cutoff ) , s . agent_list ( ) ) ) |
def init_workers ( ) :
"""Waiting function , used to wake up the process pool""" | setproctitle ( 'oq-worker' )
# unregister raiseMasterKilled in oq - workers to avoid deadlock
# since processes are terminated via pool . terminate ( )
signal . signal ( signal . SIGTERM , signal . SIG_DFL )
# prctl is still useful ( on Linux ) to terminate all spawned processes
# when master is killed via SIGKILL
try ... |
def mousePressEvent ( self , event ) :
"""override Qt method""" | # Raise the main application window on click
self . parent . raise_ ( )
self . raise_ ( )
if event . button ( ) == Qt . RightButton :
pass |
def frequency_of_peaks ( self , x , start_offset = 100 , end_offset = 100 ) :
"""This method assess the frequency of the peaks on any given 1 - dimensional time series .
: param x : The time series to assess freeze of gait on . This could be x , y , z or mag _ sum _ acc .
: type x : pandas . Series
: param st... | peaks_data = x [ start_offset : - end_offset ] . values
maxtab , mintab = peakdet ( peaks_data , self . delta )
x = np . mean ( peaks_data [ maxtab [ 1 : , 0 ] . astype ( int ) ] - peaks_data [ maxtab [ : - 1 , 0 ] . astype ( int ) ] )
frequency_of_peaks = abs ( 1 / x )
return frequency_of_peaks |
def regions_to_network ( im , dt = None , voxel_size = 1 ) :
r"""Analyzes an image that has been partitioned into pore regions and extracts
the pore and throat geometry as well as network connectivity .
Parameters
im : ND - array
An image of the pore space partitioned into individual pore regions .
Note t... | print ( '_' * 60 )
print ( 'Extracting pore and throat information from image' )
from skimage . morphology import disk , ball
struc_elem = disk if im . ndim == 2 else ball
# if ~ sp . any ( im = = 0 ) :
# raise Exception ( ' The received image has no solid phase ( 0 \ ' s ) ' )
if dt is None :
dt = spim . distance_... |
def InternalSendApdu ( self , apdu_to_send ) :
"""Send an APDU to the device .
Sends an APDU to the device , possibly falling back to the legacy
encoding format that is not ISO7816-4 compatible .
Args :
apdu _ to _ send : The CommandApdu object to send
Returns :
The ResponseApdu object constructed out o... | response = None
if not self . use_legacy_format :
response = apdu . ResponseApdu ( self . transport . SendMsgBytes ( apdu_to_send . ToByteArray ( ) ) )
if response . sw1 == 0x67 and response . sw2 == 0x00 : # If we failed using the standard format , retry with the
# legacy format .
self . use_legacy... |
def unregister_callback ( callback_id ) :
"""unregister a callback registration""" | global _callbacks
obj = _callbacks . pop ( callback_id , None )
threads = [ ]
if obj is not None :
t , quit = obj
quit . set ( )
threads . append ( t )
for t in threads :
t . join ( ) |
def problem ( self ) :
"""| Comment : For tickets of type " incident " , the ID of the problem the incident is linked to""" | if self . api and self . problem_id :
return self . api . _get_problem ( self . problem_id ) |
def make_socket ( ) :
'''Creates a socket suitable for SSDP searches .
The socket will have a default timeout of 0.2 seconds ( this works well for
the : py : func : search function which interleaves sending requests and reading
responses .''' | mreq = struct . pack ( "4sl" , socket . inet_aton ( MCAST_IP ) , socket . INADDR_ANY )
sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM , socket . IPPROTO_UDP )
sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 )
sock . bind ( ( '' , MCAST_PORT ) )
sock . setsockopt ( socket . IPPROTO_I... |
def set_vm_status ( self , device = 'FLOPPY' , boot_option = 'BOOT_ONCE' , write_protect = 'YES' ) :
"""Sets the Virtual Media drive status
It sets the boot option for virtual media device .
Note : boot option can be set only for CD device .
: param device : virual media device
: param boot _ option : boot ... | # CONNECT is a RIBCL call . There is no such property to set in Redfish .
if boot_option == 'CONNECT' :
return
self . _validate_virtual_media ( device )
if boot_option not in BOOT_OPTION_MAP :
msg = ( self . _ ( "Virtual media boot option '%s' is invalid." ) % boot_option )
LOG . debug ( msg )
raise exc... |
def Plot_Impact_3DPoly ( T , Leg = "" , ax = None , Ang = _def . TorPAng , AngUnit = _def . TorPAngUnit , Pdict = _def . TorP3DFilld , dLeg = _def . TorLegd , draw = True , fs = None , wintit = _wintit , Test = True ) :
"""Plotting the toroidal projection of a Ves instance
D . VEZINET , Aug . 2014
Inputs :
T ... | if Test :
assert T . Id . Cls in [ 'Ves' , 'Struct' ] or ( isinstance ( T , tuple ) and len ( T ) == 3 ) , "Arg T must be Ves instance or tuple with (Theta,pP,pN) 3 ndarrays !"
assert isinstance ( ax , Axes3D ) or ax is None , "Arg ax must be a Axes instance !"
assert type ( Pdict ) is dict , "Arg Pdict mus... |
def get_next_page ( self , page_num , page_size ) :
"""Retrieve the next page of results .""" | url = self . _response_json . get ( self . next_page_attr , None )
if url is None :
raise StopIteration ( )
params , url = self . process_url ( page_num , page_size , url )
response = self . response_handler . api . _get ( url , raw_response = True , params = params )
return response . json ( ) |
def joins ( self , table ) :
"""Analog to " INNER JOIN " in SQL on the passed + table + . Use only once
per query .""" | def do_join ( table , model ) :
while model is not associations . model_from_name ( table ) : # ex ) Category - > Forum - > Thread - > Post
# Category : { " posts " : " forums " }
# Forum : { " posts " : " threads " }
# Thread : { " posts " : None }
# > > > Category . joins ( " posts " )
# { ' t... |
def export_pipeline ( url , pipeline_id , auth , verify_ssl ) :
"""Export the config and rules for a pipeline .
Args :
url ( str ) : the host url in the form ' http : / / host : port / ' .
pipeline _ id ( str ) : the ID of of the exported pipeline .
auth ( tuple ) : a tuple of username , and password .
ve... | export_result = requests . get ( url + '/' + pipeline_id + '/export' , headers = X_REQ_BY , auth = auth , verify = verify_ssl )
if export_result . status_code == 404 :
logging . error ( 'Pipeline not found: ' + pipeline_id )
export_result . raise_for_status ( )
return export_result . json ( ) |
def unsubscribe ( self ) :
"""Completly stop all pubnub operations .""" | _LOGGER . info ( "PubNub unsubscribing" )
self . _pubnub . unsubscribe_all ( )
self . _pubnub . stop ( )
self . _pubnub = None |
def format ( args ) :
"""% prog format infasta outfasta
Reformat FASTA file and also clean up names .""" | sequential_choices = ( "replace" , "prefix" , "suffix" )
p = OptionParser ( format . __doc__ )
p . add_option ( "--pairs" , default = False , action = "store_true" , help = "Add trailing /1 and /2 for interleaved pairs [default: %default]" )
p . add_option ( "--sequential" , default = None , choices = sequential_choice... |
def get_objective_hierarchy_design_session_for_objective_bank ( self , objective_bank_id = None , * args , ** kwargs ) :
"""Gets the OsidSession associated with the objective hierarchy
design service for the given objective bank .
arg : objectiveBankId ( osid . id . Id ) : the Id of the objective
bank
retur... | if not objective_bank_id :
raise NullArgument
if not self . supports_objective_hierarchy_design ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
try :
session = sessions . ObjectiveHierarchyDesignSession ( objective_bank_id , runtime = self . ... |
def _drop_cascade_relation ( self , dropped ) :
"""Drop the given relation and cascade it appropriately to all
dependent relations .
: param _ CachedRelation dropped : An existing _ CachedRelation to drop .""" | if dropped not in self . relations :
logger . debug ( 'dropped a nonexistent relationship: {!s}' . format ( dropped ) )
return
consequences = self . relations [ dropped ] . collect_consequences ( )
logger . debug ( 'drop {} is cascading to {}' . format ( dropped , consequences ) )
self . _remove_refs ( conseque... |
def setup_logging ( handler , exclude = ( "gunicorn" , "south" , "elasticapm.errors" ) ) :
"""Configures logging to pipe to Elastic APM .
- ` ` exclude ` ` is a list of loggers that shouldn ' t go to ElasticAPM .
For a typical Python install :
> > > from elasticapm . handlers . logging import LoggingHandler
... | logger = logging . getLogger ( )
if handler . __class__ in map ( type , logger . handlers ) :
return False
logger . addHandler ( handler )
return True |
def increment ( self , key , value = 1 ) :
"""Increment the value of an item in the cache .
: param key : The cache key
: type key : str
: param value : The increment value
: type value : int
: rtype : int or bool""" | raw = self . _get_payload ( key )
integer = int ( raw [ 'data' ] ) + value
self . put ( key , integer , int ( raw [ 'time' ] ) )
return integer |
def patch ( self , resource_endpoint , data = { } ) :
"""Don ' t use it .""" | url = self . _create_request_url ( resource_endpoint )
return req . patch ( url , headers = self . auth_header , json = data ) |
def js ( request ) :
"""Returns the javascript needed to run persona""" | userid = authenticated_userid ( request )
user = markupsafe . Markup ( "'%s'" ) % userid if userid else "null"
redirect_paramater = request . registry [ 'persona.redirect_url_parameter' ]
came_from = '%s%s' % ( request . host_url , request . GET . get ( redirect_paramater , request . path_qs ) )
data = { 'user' : user ... |
def pdfFromPOST ( self ) :
"""It returns the pdf for the sampling rounds printed""" | html = self . request . form . get ( 'html' )
style = self . request . form . get ( 'style' )
reporthtml = "<html><head>%s</head><body><div id='report'>%s</body></html>" % ( style , html )
return self . printFromHTML ( safe_unicode ( reporthtml ) . encode ( 'utf-8' ) ) |
def get_image_tags ( self ) :
"""Fetches image labels ( repository / tags ) from Docker .
: return : A dictionary , with image name and tags as the key and the image id as value .
: rtype : dict""" | current_images = self . images ( )
tags = { tag : i [ 'Id' ] for i in current_images for tag in i [ 'RepoTags' ] }
return tags |
def colorize_text ( self , text ) :
"""Colorize the text .""" | # As originally implemented , this method acts upon all the contents of
# the file as a single string using the MULTILINE option of the re
# package . I believe this was ostensibly for performance reasons , but
# it has a few side effects that are less than ideal . It ' s non - trivial
# to avoid some substitutions bas... |
def _removepkg ( self , package ) :
"""removepkg Slackware command""" | try :
subprocess . call ( "removepkg {0} {1}" . format ( self . flag , package ) , shell = True )
if os . path . isfile ( self . dep_path + package ) :
os . remove ( self . dep_path + package )
# remove log
except subprocess . CalledProcessError as er :
print ( er )
raise SystemExit ( ) |
def timeout_callback ( self ) :
"""过期回调函数 .
如果设置了timeout则会启动一个协程按当前时间和最近的响应时间只差递归的执行这个回调""" | # Check if elapsed time since last response exceeds our configured
# maximum keep alive timeout value
now = time ( )
time_elapsed = now - self . _last_response_time
if time_elapsed < self . timeout :
time_left = self . timeout - time_elapsed
self . _timeout_handler = ( self . _loop . call_later ( time_left , se... |
def tasks ( self ) :
""": class : ` ~ zhmcclient . TaskManager ` : Access to the : term : ` Tasks < Task > ` in
this Console .""" | # We do here some lazy loading .
if not self . _tasks :
self . _tasks = TaskManager ( self )
return self . _tasks |
def part ( self , channel , reason = '' ) :
"""Part a channel .
Required arguments :
* channel - Channel to part .
Optional arguments :
* reason = ' ' - Reason for parting .""" | with self . lock :
self . is_in_channel ( channel )
self . send ( 'PART %s :%s' % ( channel , reason ) )
msg = self . _recv ( expected_replies = ( 'PART' , ) )
if msg [ 0 ] == 'PART' :
del self . channels [ msg [ 1 ] ]
if not self . hide_called_events :
self . stepback ( ) |
def longest_run ( da , dim = 'time' ) :
"""Return the length of the longest consecutive run of True values .
Parameters
arr : N - dimensional array ( boolean )
Input array
dim : Xarray dimension ( default = ' time ' )
Dimension along which to calculate consecutive run
Returns
N - dimensional array ( i... | d = rle ( da , dim = dim )
rl_long = d . max ( dim = dim )
return rl_long |
def execute ( self , stmt , ** params ) :
"""Execute a SQL statement .
The statement may be a string SQL string ,
an : func : ` sqlalchemy . sql . expression . select ` construct , or a
: func : ` sqlalchemy . sql . expression . text `
construct .""" | return self . session . execute ( sql . text ( stmt , bind = self . bind ) , ** params ) |
def _try_open ( cls ) :
"""Try to open a USB handle .""" | handle = None
for usb_cls , subcls , protocol in [ ( adb_device . CLASS , adb_device . SUBCLASS , adb_device . PROTOCOL ) , ( fastboot_device . CLASS , fastboot_device . SUBCLASS , fastboot_device . PROTOCOL ) ] :
try :
handle = local_usb . LibUsbHandle . open ( serial_number = cls . serial_number , interfa... |
def resource_redirect ( id ) :
'''Redirect to the latest version of a resource given its identifier .''' | resource = get_resource ( id )
return redirect ( resource . url . strip ( ) ) if resource else abort ( 404 ) |
def handle_logout_response ( self , response , sign_alg = None , digest_alg = None ) :
"""handles a Logout response
: param response : A response . Response instance
: return : 4 - tuple of ( session _ id of the last sent logout request ,
response message , response headers and message )""" | logger . info ( "state: %s" , self . state )
status = self . state [ response . in_response_to ]
logger . info ( "status: %s" , status )
issuer = response . issuer ( )
logger . info ( "issuer: %s" , issuer )
del self . state [ response . in_response_to ]
if status [ "entity_ids" ] == [ issuer ] : # done
self . loca... |
def split_face ( self , face , number = None , ids = None ) :
"""Split a topological face into a number of small faces .
* ` ` face ` ` : The face to split . Must be in the topology .
* ` ` number ` ` : Number of new faces to create . Optional , can be inferred from ` ` ids ` ` . Default is 2 new faces .
* ` ... | assert face in self . faces
if ids :
ids = set ( ids )
else :
max_int = max ( x for x in self . faces if isinstance ( x , int ) )
ids = set ( range ( max_int + 1 , max_int + 1 + ( number or 2 ) ) )
for obj in self . topology . values ( ) :
if face in obj :
obj . discard ( face )
obj . up... |
def get_dependency_type ( _type ) :
"""Get the dependency type string for SlurmPrinter
: rtype : str""" | if _type == DependencyTypes . AFTER :
return 'after'
elif _type == DependencyTypes . AFTER_ANY :
return 'afterany'
elif _type == DependencyTypes . AFTER_CORR :
return 'aftercorr'
elif _type == DependencyTypes . AFTER_NOT_OK :
return 'afternotok'
elif _type == DependencyTypes . AFTER_OK :
return 'aft... |
def elevate_element ( node , adopt_name = None , adopt_attrs = None ) :
"""This method serves a specialized function . It comes up most often when
working with block level elements that may not be contained within
paragraph elements , which are presented in the source document as
inline elements ( inside a pa... | # These must be collected before modifying the xml
parent = node . getparent ( )
grandparent = parent . getparent ( )
child_index = parent . index ( node )
parent_index = grandparent . index ( parent )
# Get a list of the siblings
siblings = list ( parent ) [ child_index + 1 : ]
# Insert the node after the parent
grand... |
def contains_offset ( self , offset ) :
"""Check whether the section contains the file offset provided .""" | if self . PointerToRawData is None : # bss and other sections containing only uninitialized data must have 0
# and do not take space in the file
return False
return ( adjust_FileAlignment ( self . PointerToRawData , self . pe . OPTIONAL_HEADER . FileAlignment ) <= offset < adjust_FileAlignment ( self . PointerToRaw... |
def all_cities ( ) :
"""Get a list of all Backpage city names .
Returns :
list of city names as Strings""" | cities = [ ]
fname = pkg_resources . resource_filename ( __name__ , 'resources/CityPops.csv' )
with open ( fname , 'rU' ) as csvfile :
reader = csv . reader ( csvfile , delimiter = ',' )
for row in reader :
cities . append ( row [ 0 ] )
cities . sort ( )
return cities |
def filter_record ( self , record ) :
"""Filter record , truncating any over some maximum length""" | if len ( record ) >= self . max_length :
return record [ : self . max_length ]
else :
return record |
def do_OP_SUBSTR ( vm ) :
"""> > > s = [ b ' abcdef ' , b ' \3 ' , b ' \2 ' ]
> > > do _ OP _ SUBSTR ( s , require _ minimal = True )
> > > print ( s )
[ b ' de ' ]""" | pos = vm . pop_nonnegative ( )
length = vm . pop_nonnegative ( )
vm . append ( vm . pop ( ) [ length : length + pos ] ) |
def _set_jinja2_enviroment ( self ) :
"""Set up the jinja2 environment .""" | template_loader = FileSystemLoader ( searchpath = self . TEMPLATE_DIR )
env = Environment ( loader = template_loader , trim_blocks = True , lstrip_blocks = True )
env . globals . update ( chunker = chunker , enumerate = enumerate , str = str )
# Add filters to the environment
round2digits = functools . partial ( round_... |
def _rebuild_table ( self , new_name , old_name , new_columns , old_columns ) :
'''a helper method for rebuilding table ( by renaming & migrating )''' | # verbosity
print ( 'Rebuilding %s table in %s database' % ( self . table_name , self . database_name ) , end = '' , flush = True )
from sqlalchemy import Table , MetaData
metadata_object = MetaData ( )
# construct old table
old_table_args = [ old_name , metadata_object ]
old_column_args = self . _construct_columns ( o... |
def _ParseArgs ( self , args , known_only ) :
"""Helper function to do the main argument parsing .
This function goes through args and does the bulk of the flag parsing .
It will find the corresponding flag in our flag dictionary , and call its
. parse ( ) method on the flag value .
Args :
args : List of ... | unknown_flags , unparsed_args , undefok = [ ] , [ ] , set ( )
flag_dict = self . FlagDict ( )
args = iter ( args )
for arg in args :
value = None
def GetValue ( ) : # pylint : disable = cell - var - from - loop
try :
return next ( args ) if value is None else value
except StopIterati... |
def predict_to_dataframe ( self , peptides , alleles = None , allele = None , throw = True , include_individual_model_predictions = False , include_percentile_ranks = True , include_confidence_intervals = True , centrality_measure = DEFAULT_CENTRALITY_MEASURE ) :
"""Predict nM binding affinities . Gives more detail... | if isinstance ( peptides , string_types ) :
raise TypeError ( "peptides must be a list or array, not a string" )
if isinstance ( alleles , string_types ) :
raise TypeError ( "alleles must be a list or array, not a string" )
if allele is None and alleles is None :
raise ValueError ( "Must specify 'allele' or... |
def poll ( self , lease_seconds = LEASE_SECONDS , tag = None , verbose = False , execute_args = [ ] , execute_kwargs = { } , stop_fn = None , backoff_exceptions = [ ] , min_backoff_window = 30 , max_backoff_window = 120 , log_fn = None ) :
"""Poll a queue until a stop condition is reached ( default forever ) . Note... | global LOOP
if not callable ( stop_fn ) and stop_fn is not None :
raise ValueError ( "stop_fn must be a callable. " + str ( stop_fn ) )
elif not callable ( stop_fn ) :
stop_fn = lambda : False
def random_exponential_window_backoff ( n ) :
n = min ( n , min_backoff_window )
# 120 sec max b / c on avg a r... |
def handle ( self , namespace ) :
"""Handles given ` ` namespace ` ` by calling ` ` handle _ label ` ` method
for each given * label * .""" | for label in namespace . labels :
self . handle_label ( label , namespace )
else :
self . handle_no_labels ( namespace ) |
def get_keys ( keynames = None , filters = None , region = None , key = None , keyid = None , profile = None ) :
'''Gets all keys or filters them by name and returns a list .
keynames ( list ) : : A list of the names of keypairs to retrieve .
If not provided , all key pairs will be returned .
filters ( dict )... | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
try :
keys = conn . get_all_key_pairs ( keynames , filters )
log . debug ( "the key to return is : %s" , keys )
key_values = [ ]
if keys :
for key in keys :
key_values . append ( key . name )
ret... |
def symmetrize ( C ) :
"""Symmetrize the Wilson coefficient arrays .
Note that this function does not take into account the symmetry factors
that occur when transitioning from a basis with only non - redundant operators
( like in WCxf ) to a basis where the Wilson coefficients are symmetrized
like the opera... | C_symm = { }
for i , v in C . items ( ) :
if i in C_symm_keys [ 0 ] :
C_symm [ i ] = v . real
elif i in C_symm_keys [ 1 ] + C_symm_keys [ 3 ] :
C_symm [ i ] = v
# nothing to do
elif i in C_symm_keys [ 2 ] :
C_symm [ i ] = symmetrize_2 ( C [ i ] )
elif i in C_symm_keys [ 4... |
def make_reading_comprehension_instance_quac ( question_list_tokens : List [ List [ Token ] ] , passage_tokens : List [ Token ] , token_indexers : Dict [ str , TokenIndexer ] , passage_text : str , token_span_lists : List [ List [ Tuple [ int , int ] ] ] = None , yesno_list : List [ int ] = None , followup_list : List ... | additional_metadata = additional_metadata or { }
fields : Dict [ str , Field ] = { }
passage_offsets = [ ( token . idx , token . idx + len ( token . text ) ) for token in passage_tokens ]
# This is separate so we can reference it later with a known type .
passage_field = TextField ( passage_tokens , token_indexers )
fi... |
def _thumbnail_local ( self , original_filename , thumb_filename , thumb_size , thumb_url , crop = None , bg = None , quality = 85 ) :
"""Finds or creates a thumbnail for the specified image on the local filesystem .""" | # create folders
self . _get_path ( thumb_filename )
thumb_url_full = url_for ( 'static' , filename = thumb_url )
# Return the thumbnail URL now if it already exists locally
if os . path . exists ( thumb_filename ) :
return thumb_url_full
try :
image = Image . open ( original_filename )
except IOError :
ret... |
def _is_valid_close_code ( self , code ) :
""": returns : Whether the returned close code is a valid hybi return code .""" | if code < 1000 :
return False
if 1004 <= code <= 1006 :
return False
if 1012 <= code <= 1016 :
return False
if code == 1100 : # not sure about this one but the autobahn fuzzer requires it .
return False
if 2000 <= code <= 2999 :
return False
return True |
def get_user_best ( self , username , * , mode = OsuMode . osu , limit = 50 ) :
"""Get a user ' s best scores .
Parameters
username : str or int
A ` str ` representing the user ' s username , or an ` int ` representing the user ' s id .
mode : : class : ` osuapi . enums . OsuMode `
The osu ! game mode for... | return self . _make_req ( endpoints . USER_BEST , dict ( k = self . key , u = username , type = _username_type ( username ) , m = mode . value , limit = limit ) , JsonList ( SoloScore ) ) |
def Filter ( self , filename_spec ) :
"""Use pkg _ resources to find the path to the required resource .""" | if "@" in filename_spec :
file_path , package_name = filename_spec . split ( "@" )
else :
file_path , package_name = filename_spec , Resource . default_package
resource_path = package . ResourcePath ( package_name , file_path )
if resource_path is not None :
return resource_path
# pylint : disable = unreach... |
def __parse_organizations ( self , json ) :
"""Parse Stackalytics organizations .
The Stackalytics organizations format is a JSON document stored under the
" companies " key . The next JSON shows the structure of the
document :
" companies " : [
" domains " : [ " alcatel - lucent . com " ] ,
" company _... | try :
for company in json [ 'companies' ] :
name = self . __encode ( company [ 'company_name' ] )
org = self . _organizations . get ( name , None )
if not org :
org = Organization ( name = name )
self . _organizations [ name ] = org
for domain in company [ 'do... |
def _getTrailerString ( self , compressed = 1 ) :
"""_ getTrailerString ( self , compressed = 1 ) - > PyObject *""" | if self . isClosed :
raise ValueError ( "operation illegal for closed doc" )
return _fitz . Document__getTrailerString ( self , compressed ) |
def clear ( self ) :
"""Initializes the device memory with an empty ( blank ) image .""" | self . display ( Image . new ( self . mode , self . size ) ) |
def Deserialize ( self , reader ) :
"""Deserialize full object .
Args :
reader ( neocore . IO . BinaryReader ) :""" | super ( AccountState , self ) . Deserialize ( reader )
self . ScriptHash = reader . ReadUInt160 ( )
self . IsFrozen = reader . ReadBool ( )
num_votes = reader . ReadVarInt ( )
for i in range ( 0 , num_votes ) :
self . Votes . append ( reader . ReadBytes ( 33 ) )
num_balances = reader . ReadVarInt ( )
self . Balance... |
def as_part ( func ) :
"""Converts a function to a : class : ` Part < cqparts . Part > ` instance .
So the conventionally defined * part * : :
import cadquery
from cqparts import Part
from cqparts . params import Float
class Box ( Part ) :
x = Float ( 1)
y = Float ( 2)
z = Float ( 4)
def make ( se... | from . . import Part
def inner ( * args , ** kwargs ) :
part_class = type ( func . __name__ , ( Part , ) , { 'make' : lambda self : func ( * args , ** kwargs ) , } )
return part_class ( )
inner . __doc__ = func . __doc__
return inner |
def get_dimension ( self , dataset , dimension ) :
"""The method is getting information about dimension with items""" | path = '/api/1.0/meta/dataset/{}/dimension/{}'
return self . _api_get ( definition . Dimension , path . format ( dataset , dimension ) ) |
def eval_expr ( expr , context ) :
"""Recursively evaluates a compiled expression using the specified context .
Dict instances can contain a " _ _ kwargs " key which will be used to update the
dict with its content""" | if isinstance ( expr , list ) :
rv = [ ]
for item in expr :
rv . append ( eval_expr ( item , context ) )
return rv
if isinstance ( expr , dict ) :
rv = { }
for k , v in expr . iteritems ( ) :
rv [ k ] = eval_expr ( v , context )
kwargs = rv . pop ( "__kwargs" , None )
if kwar... |
def list_volumes ( profile , ** libcloud_kwargs ) :
'''Return a list of storage volumes for this cloud
: param profile : The profile key
: type profile : ` ` str ` `
: param libcloud _ kwargs : Extra arguments for the driver ' s list _ volumes method
: type libcloud _ kwargs : ` ` dict ` `
CLI Example :
... | conn = _get_driver ( profile = profile )
libcloud_kwargs = salt . utils . args . clean_kwargs ( ** libcloud_kwargs )
volumes = conn . list_volumes ( ** libcloud_kwargs )
ret = [ ]
for volume in volumes :
ret . append ( _simple_volume ( volume ) )
return ret |
def parse ( self ) :
'''Iterate over the lines and extract the required data .''' | for self . line in self . output : # Parse general data : charge , multiplicity , coordinates , etc .
self . index = 0
if self . line [ 1 : 13 ] == 'Total Charge' :
tokens = self . line . split ( )
self . charge = int ( tokens [ - 1 ] )
if ( self . line [ 1 : 13 ] or self . line [ 0 : 12 ] )... |
def get_db_prep_value ( self , value ) :
"""Pickle and b64encode the object , optionally compressing it .
The pickling protocol is specified explicitly ( by default 2 ) ,
rather than as - 1 or HIGHEST _ PROTOCOL , because we don ' t want the
protocol to change over time . If it did , ` ` exact ` ` and ` ` in ... | if value is not None and not isinstance ( value , PickledObject ) : # We call force _ unicode here explicitly , so that the encoded string
# isn ' t rejected by the postgresql _ psycopg2 backend . Alternatively ,
# we could have just registered PickledObject with the psycopg
# marshaller ( telling it to store it like i... |
def bump_version ( project , source , force_init ) : # type : ( str , str , bool , bool ) - > int
"""Entry point
: return :""" | file_opener = FileOpener ( )
# logger . debug ( " Starting version jiggler . . . " )
jiggler = JiggleVersion ( project , source , file_opener , force_init )
logger . debug ( "Current, next : {0} -> {1} : {2}" . format ( jiggler . current_version , jiggler . version , jiggler . schema ) )
if not jiggler . version_finder... |
def same_player ( self , other ) :
"""Compares name and color .
Returns True if both are owned by the same player .""" | return self . name == other . name and self . color == other . color |
def confirm_or_abort ( prompt , exitcode = os . EX_TEMPFAIL , msg = None , ** extra_args ) :
"""Prompt user for confirmation and exit on negative reply .
Arguments ` prompt ` and ` extra _ args ` will be passed unchanged to
` click . confirm ` : func : ( which is used for actual prompting ) .
: param str prom... | if click . confirm ( prompt , ** extra_args ) :
return True
else : # abort
if msg :
sys . stderr . write ( msg )
sys . stderr . write ( '\n' )
sys . exit ( exitcode ) |
def parse_memory ( memory ) :
"""Parses a string representing memory and returns
an integer # of bytes .
: param memory :
: return :""" | memory = str ( memory )
if 'None' in memory :
return 2147483648
# toil ' s default
try :
import re
raw_mem_split = re . split ( '([a-zA-Z]+)' , memory )
mem_split = [ ]
for r in raw_mem_split :
if r :
mem_split . append ( r . replace ( ' ' , '' ) )
if len ( mem_split ) ==... |
def drop_uda ( self , name , input_types = None , database = None , force = False ) :
"""Drop aggregate function . See drop _ udf for more information on the
parameters .""" | return self . drop_udf ( name , input_types = input_types , database = database , force = force ) |
def delif ( self , iface ) :
'''Remove the interface with the given name from this bridge .
Equivalent to brctl delif [ bridge ] [ interface ]''' | if type ( iface ) == ifconfig . Interface :
devindex = iface . index
else :
devindex = ifconfig . Interface ( iface ) . index
ifreq = struct . pack ( '16si' , self . name , devindex )
fcntl . ioctl ( ifconfig . sockfd , SIOCBRDELIF , ifreq )
return self |
def check_rules ( self ) :
"""Check if the rules are equals .
Returns
bool
True if the rules are the same
False otherwise
list
A list with the differences""" | query = """
select n.nspname as rule_schema,
c.relname as rule_table,
case r.ev_type
when '1' then 'SELECT'
when '2' then 'UPDATE'
when '3' then 'INSERT'
when '4' then 'DELETE'
else 'UNKNOWN'
end as rule_event
from pg_re... |
def upload_member_from_dir ( member_data , target_member_dir , metadata , access_token , mode = 'default' , max_size = MAX_SIZE_DEFAULT ) :
"""Upload files in target directory to an Open Humans member ' s account .
The default behavior is to overwrite files with matching filenames on
Open Humans , but not other... | if not validate_metadata ( target_member_dir , metadata ) :
raise ValueError ( 'Metadata should match directory contents!' )
project_data = { f [ 'basename' ] : f for f in member_data [ 'data' ] if f [ 'source' ] not in member_data [ 'sources_shared' ] }
for filename in metadata :
if filename in project_data an... |
def get_ip_address_from_rackspace_server ( server_id ) :
"""returns an ipaddress for a rackspace instance""" | nova = connect_to_rackspace ( )
server = nova . servers . get ( server_id )
# the server was assigned IPv4 and IPv6 addresses , locate the IPv4 address
ip_address = None
for network in server . networks [ 'public' ] :
if re . match ( '\d+\.\d+\.\d+\.\d+' , network ) :
ip_address = network
break
# fi... |
def entry_path ( cls , project , location , entry_group , entry ) :
"""Return a fully - qualified entry string .""" | return google . api_core . path_template . expand ( "projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}" , project = project , location = location , entry_group = entry_group , entry = entry , ) |
def clear_cache ( days = - 1 ) :
'''Forcibly removes all caches on a minion .
. . versionadded : : 2014.7.0
WARNING : The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it .
CLI Example :
. . code - block : : bash
salt ' * ' saltuti... | threshold = time . time ( ) - days * 24 * 60 * 60
for root , dirs , files in salt . utils . files . safe_walk ( __opts__ [ 'cachedir' ] , followlinks = False ) :
for name in files :
try :
file = os . path . join ( root , name )
mtime = os . path . getmtime ( file )
if mti... |
def _get_dominant_angle ( lines , domination_type = MEDIAN ) :
"""Picks dominant angle of a set of lines .
Args :
lines : iterable of ( x1 , y1 , x2 , y2 ) tuples that define lines .
domination _ type : either MEDIAN or MEAN .
Returns :
Dominant angle value in radians .
Raises :
ValueError : on unknow... | if domination_type == MEDIAN :
return _get_median_angle ( lines )
elif domination_type == MEAN :
return _get_mean_angle ( lines )
else :
raise ValueError ( 'Unknown domination type provided: %s' % ( domination_type ) ) |
def create_relationship ( self , relationship_form ) :
"""Creates a new ` ` Relationship ` ` .
arg : relationship _ form ( osid . relationship . RelationshipForm ) :
the form for this ` ` Relationship ` `
return : ( osid . relationship . Relationship ) - the new
` ` Relationship ` `
raise : IllegalState -... | # Implemented from template for
# osid . resource . ResourceAdminSession . create _ resource _ template
collection = JSONClientValidated ( 'relationship' , collection = 'Relationship' , runtime = self . _runtime )
if not isinstance ( relationship_form , ABCRelationshipForm ) :
raise errors . InvalidArgument ( 'argu... |
def getJSModuleURL ( self , moduleName ) :
"""Retrieve an L { URL } object which references the given module name .
This makes a ' best effort ' guess as to an fully qualified HTTPS URL
based on the hostname provided during rendering and the configuration
of the site . This is to avoid unnecessary duplicate r... | if self . _moduleRoot is None :
raise NotImplementedError ( "JS module URLs cannot be requested before rendering." )
moduleHash = self . hashCache . getModule ( moduleName ) . hashValue
return self . _moduleRoot . child ( moduleHash ) . child ( moduleName ) |
def _update_state_from_response ( self , response_json ) :
""": param response _ json : the json obj returned from query
: return :""" | power_strip = response_json . get ( 'data' )
power_strip_reading = power_strip . get ( 'last_reading' )
outlets = power_strip . get ( 'outlets' )
for outlet in outlets :
if outlet . get ( 'outlet_id' ) == str ( self . object_id ( ) ) :
outlet [ 'last_reading' ] [ 'connection' ] = power_strip_reading . get (... |
def process ( name ) :
'''Return whether the specified signature is found in the process tree . This
differs slightly from the services states , in that it may refer to a
process that is not managed via the init system .''' | # Monitoring state , no changes will be made so no test interface needed
ret = { 'name' : name , 'result' : False , 'comment' : '' , 'changes' : { } , 'data' : { } }
# Data field for monitoring state
data = __salt__ [ 'status.pid' ] ( name )
if not data :
ret [ 'result' ] = False
ret [ 'comment' ] += 'Process s... |
def normalize_fieldsets ( fieldsets ) :
"""Make sure the keys in fieldset dictionaries are strings . Returns the
normalized data .""" | result = [ ]
for name , options in fieldsets :
result . append ( ( name , normalize_dictionary ( options ) ) )
return result |
def _NormalizeDuration ( self , seconds , nanos ) :
"""Set Duration by seconds and nonas .""" | # Force nanos to be negative if the duration is negative .
if seconds < 0 and nanos > 0 :
seconds += 1
nanos -= _NANOS_PER_SECOND
self . seconds = seconds
self . nanos = nanos |
def get_commit ( profile , sha ) :
"""Fetch a commit .
Args :
profile
A profile generated from ` ` simplygithub . authentication . profile ` ` .
Such profiles tell this module ( i ) the ` ` repo ` ` to connect to ,
and ( ii ) the ` ` token ` ` to connect with .
sha
The SHA of the commit to fetch .
R... | resource = "/commits/" + sha
data = api . get_request ( profile , resource )
return prepare ( data ) |
def word_counts ( self ) :
"""Dictionary of word frequencies in this text .""" | counts = defaultdict ( int )
stripped_words = [ lowerstrip ( word ) for word in self . words ]
for word in stripped_words :
counts [ word ] += 1
return counts |
def is_portrait ( file_ ) :
"""A very handy filter to determine if an image is portrait or landscape .""" | if sorl_settings . THUMBNAIL_DUMMY :
return sorl_settings . THUMBNAIL_DUMMY_RATIO < 1
if not file_ :
return False
image_file = default . kvstore . get_or_set ( ImageFile ( file_ ) )
return image_file . is_portrait ( ) |
def read_dir ( input_dir , input_ext , func ) :
'''reads all files with extension input _ ext
in a directory input _ dir and apply function func
to their contents''' | import os
for dirpath , dnames , fnames in os . walk ( input_dir ) :
for fname in fnames :
if not dirpath . endswith ( os . sep ) :
dirpath = dirpath + os . sep
if fname . endswith ( input_ext ) :
func ( read_file ( dirpath + fname ) ) |
def get_object ( self ) :
"""If a single object has been requested , will set
` self . object ` and return the object .""" | queryset = None
slug = self . kwargs . get ( self . slug_url_kwarg , None )
if slug is not None :
queryset = self . get_queryset ( )
slug_field = self . slug_field
queryset = queryset . filter ( ** { slug_field : slug } )
try :
self . object = queryset . get ( )
except ObjectDoesNotExist :
... |
def decode_jwt ( encoded_token , secret , algorithm , identity_claim_key , user_claims_key , csrf_value = None , audience = None , leeway = 0 , allow_expired = False ) :
"""Decodes an encoded JWT
: param encoded _ token : The encoded JWT string to decode
: param secret : Secret key used to encode the JWT
: pa... | options = { }
if allow_expired :
options [ 'verify_exp' ] = False
# This call verifies the ext , iat , nbf , and aud claims
data = jwt . decode ( encoded_token , secret , algorithms = [ algorithm ] , audience = audience , leeway = leeway , options = options )
# Make sure that any custom claims we expect in the toke... |
def get_version_from_list ( v , vlist ) :
"""See if we can match v ( string ) in vlist ( list of strings )
Linux has to match in a fuzzy way .""" | if is_windows : # Simple case , just find it in the list
if v in vlist :
return v
else :
return None
else : # Fuzzy match : normalize version number first , but still return
# original non - normalized form .
fuzz = 0.001
for vi in vlist :
if math . fabs ( linux_ver_normalize ( v... |
def quaternion_inverse ( quaternion ) :
"""Return inverse of quaternion .
> > > q0 = random _ quaternion ( )
> > > q1 = quaternion _ inverse ( q0)
> > > np . allclose ( quaternion _ multiply ( q0 , q1 ) , [ 1 , 0 , 0 , 0 ] )
True""" | q = np . array ( quaternion , dtype = np . float64 , copy = True )
np . negative ( q [ 1 : ] , q [ 1 : ] )
return q / np . dot ( q , q ) |
def join_domain ( name , username = None , password = None , account_ou = None , account_exists = False , restart = False ) :
'''Checks if a computer is joined to the Domain . If the computer is not in the
Domain , it will be joined .
Args :
name ( str ) :
The name of the Domain .
username ( str ) :
Use... | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : 'Computer already added to \'{0}\'' . format ( name ) }
current_domain_dic = __salt__ [ 'system.get_domain_workgroup' ] ( )
if 'Domain' in current_domain_dic :
current_domain = current_domain_dic [ 'Domain' ]
elif 'Workgroup' in current_domain_... |
def get_codons ( variant , trimmed_cdna_ref , trimmed_cdna_alt , sequence_from_start_codon , cds_offset ) :
"""Returns indices of first and last reference codons affected by the variant ,
as well as the actual sequence of the mutated codons which replace those
reference codons .
Parameters
variant : Variant... | # index ( starting from 0 ) of first affected reference codon
ref_codon_start_offset = cds_offset // 3
# which nucleotide of the first codon got changed ?
nucleotide_offset_into_first_ref_codon = cds_offset % 3
n_ref_nucleotides = len ( trimmed_cdna_ref )
if n_ref_nucleotides == 0 :
if nucleotide_offset_into_first_... |
def fig_to_geojson ( fig = None , ** kwargs ) :
"""Returns a figure ' s GeoJSON representation as a dictionary
All arguments passed to fig _ to _ html ( )
Returns
GeoJSON dictionary""" | if fig is None :
fig = plt . gcf ( )
renderer = LeafletRenderer ( ** kwargs )
exporter = Exporter ( renderer )
exporter . run ( fig )
return renderer . geojson ( ) |
def remove_folder_content ( path , ignore_hidden_file = False ) :
"""Remove all content in the given folder .""" | for file in os . listdir ( path ) :
if ignore_hidden_file and file . startswith ( '.' ) :
continue
file_path = os . path . join ( path , file )
if os . path . isdir ( file_path ) :
shutil . rmtree ( file_path )
else :
os . remove ( file_path ) |
def read_bytes ( self , count ) :
"""Read count number of bytes .""" | if self . pos + count > self . remaining_length :
return NC . ERR_PROTOCOL , None
ba = bytearray ( count )
for x in xrange ( 0 , count ) :
ba [ x ] = self . payload [ self . pos ]
self . pos += 1
return NC . ERR_SUCCESS , ba |
def fit ( self , ** kwargs ) :
"""Call the fit method of the primitive .
The given keyword arguments will be passed directly to the ` fit `
method of the primitive instance specified in the JSON annotation .
If any of the arguments expected by the produce method had been
given during the MLBlock initializat... | if self . fit_method is not None :
fit_args = self . _fit_params . copy ( )
fit_args . update ( kwargs )
getattr ( self . instance , self . fit_method ) ( ** fit_args ) |
def get_copyright_metadata ( self ) :
"""Gets the metadata for the copyright .
return : ( osid . Metadata ) - metadata for the copyright
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template
metadata = dict ( self . _mdata [ 'copyright' ] )
metadata . update ( { 'existing_string_values' : self . _my_map [ 'copyright' ] } )
return Metadata ( ** metadata ) |
def _model_unique ( ins ) :
"""Get unique constraints info
: type ins : sqlalchemy . orm . mapper . Mapper
: rtype : list [ tuple [ str ] ]""" | unique = [ ]
for t in ins . tables :
for c in t . constraints :
if isinstance ( c , UniqueConstraint ) :
unique . append ( tuple ( col . key for col in c . columns ) )
return unique |
def get_bodies ( self , obj ) :
"""Bodies with offices up for election on election day .""" | return reverse ( 'electionnight_api_body-election-list' , request = self . context [ 'request' ] , kwargs = { 'date' : obj . date } ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.