signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def read_config ( config_file = CONFIG_FILE_DEFAULT , override_url = None ) :
'''Read configuration file , perform sanity check and return configuration
dictionary used by other functions .''' | config = ConfigParser ( )
config . read_dict ( DEFAULT_SETTINGS )
try :
config . readfp ( open ( config_file ) )
logger . debug ( "Using config file at " + config_file )
except :
logger . error ( "Could not find {0}, running with defaults." . format ( config_file ) )
if not logger . handlers : # Before doin... |
def case_sensitive_name ( self , package_name ) :
"""Return case - sensitive package name given any - case package name
@ param project _ name : PyPI project name
@ type project _ name : string""" | if len ( self . environment [ package_name ] ) :
return self . environment [ package_name ] [ 0 ] . project_name |
def validate_blogname ( fn ) :
"""Decorator to validate the blogname and let you pass in a blogname like :
client . blog _ info ( ' codingjester ' )
or
client . blog _ info ( ' codingjester . tumblr . com ' )
or
client . blog _ info ( ' blog . johnbunting . me ' )
and query all the same blog .""" | @ wraps ( fn )
def add_dot_tumblr ( * args , ** kwargs ) :
if ( len ( args ) > 1 and ( "." not in args [ 1 ] ) ) :
args = list ( args )
args [ 1 ] += ".tumblr.com"
return fn ( * args , ** kwargs )
return add_dot_tumblr |
def asyncPipeStringtokenizer ( context = None , _INPUT = None , conf = None , ** kwargs ) :
"""A string module that asynchronously splits a string into tokens
delimited by separators . Loopable .
Parameters
context : pipe2py . Context object
_ INPUT : twisted Deferred iterable of items or strings
conf : {... | conf [ 'delimiter' ] = conf . pop ( 'to-str' , dict . get ( conf , 'delimiter' ) )
splits = yield asyncGetSplits ( _INPUT , conf , ** cdicts ( opts , kwargs ) )
parsed = yield asyncDispatch ( splits , * get_async_dispatch_funcs ( ) )
items = yield asyncStarMap ( partial ( maybeDeferred , parse_result ) , parsed )
_OUTP... |
def get_regex ( resolver_or_pattern ) :
"""Utility method for django ' s deprecated resolver . regex""" | try :
regex = resolver_or_pattern . regex
except AttributeError :
regex = resolver_or_pattern . pattern . regex
return regex |
def document ( self , document ) :
"""Associate a : class : ` ~ elasticsearch _ dsl . Document ` subclass with an index .
This means that , when this index is created , it will contain the
mappings for the ` ` Document ` ` . If the ` ` Document ` ` class doesn ' t have a
default index yet ( by defining ` ` cl... | self . _doc_types . append ( document )
# If the document index does not have any name , that means the user
# did not set any index already to the document .
# So set this index as document index
if document . _index . _name is None :
document . _index = self
return document |
def info ( self ) :
"""小组信息
: return : 小组信息
: rtype : dict
返回值示例 : :
' title ' : u ' title ' , # 标题
' leader ' : u ' leader ' , # 组长
' date _ created ' : datetime . datetime ( 2013 , 10 , 6 , 0 , 0 ) , # 创建日期
' rank ' : 1000 , # 排名
' number ' : 10 , # 当前成员数
' max _ number ' : 20 , # 最大成员数
' rate... | html = self . request ( self . team_url ) . text
soup = BeautifulSoup ( html )
team_header = soup . find_all ( class_ = 'team-header' ) [ 0 ]
# 标题
title = team_header . find_all ( class_ = 'title' ) [ 0 ] . text . strip ( )
# 组长
leader = team_header . find_all ( class_ = 'leader' ) [ 0 ] . find_all ( 'a' ) [ 0 ] . text... |
def gen_image ( img , width , height , outfile , img_type = 'grey' ) :
"""Save an image with the given parameters .""" | assert len ( img ) == width * height or len ( img ) == width * height * 3
if img_type == 'grey' :
misc . imsave ( outfile , img . reshape ( width , height ) )
elif img_type == 'color' :
misc . imsave ( outfile , img . reshape ( 3 , width , height ) ) |
async def search ( self , term : str , limit : int = 3 ) -> 'List[Word]' :
"""Performs a search for a term and returns a list of possible matching : class : ` Word `
objects .
Args :
term : The term to be defined .
limit ( optional ) : Max amount of results returned .
Defaults to 3.
Note :
The API wil... | resp = await self . _get ( term = term )
words = resp [ 'list' ]
return [ Word ( x ) for x in words [ : limit ] ] |
def event_loop ( self ) :
"""asyncio . BaseEventLoop : the running event loop .
This fixture mainly exists to allow for overrides during unit tests .""" | if not self . _event_loop :
self . _event_loop = asyncio . get_event_loop ( )
return self . _event_loop |
def export_to_bw2 ( self ) :
"""Export the lcopt model in the native brightway 2 format
returns name , database
to use it to export , then import to brightway : :
name , db = model . export _ to _ bw2 ( )
import brightway2 as bw
bw . projects . set _ current ( ' MyProject ' )
new _ db = bw . Database ( ... | my_exporter = Bw2Exporter ( self )
name , bw2db = my_exporter . export_to_bw2 ( )
return name , bw2db |
def _group_by_equal_size ( obj_list , tot_groups , threshold = pow ( 2 , 32 ) ) :
"""Partition a list of objects evenly and by file size
Files are placed according to largest file in the smallest bucket . If the
file is larger than the given threshold , then it is placed in a new bucket
by itself .
: param ... | sorted_obj_list = sorted ( [ ( obj [ 'size' ] , obj ) for obj in obj_list ] , reverse = True )
groups = [ ( random . random ( ) , [ ] ) for _ in range ( tot_groups ) ]
if tot_groups <= 1 :
groups = _group_by_size_greedy ( obj_list , tot_groups )
return groups
heapq . heapify ( groups )
for obj in sorted_obj_lis... |
def dependencies ( self ) :
"""Returns the dependencies of the package .
: return : the list of Dependency objects
: rtype : list of Dependency""" | result = [ ]
dependencies = javabridge . get_collection_wrapper ( javabridge . call ( self . jobject , "getDependencies" , "()Ljava/util/List;" ) )
for dependency in dependencies :
result . append ( Dependency ( dependency ) )
return result |
def get_seconds_description ( self ) :
"""Generates a description for only the SECONDS portion of the expression
Returns :
The SECONDS description""" | return self . get_segment_description ( self . _expression_parts [ 0 ] , _ ( "every second" ) , lambda s : s , lambda s : _ ( "every {0} seconds" ) . format ( s ) , lambda s : _ ( "seconds {0} through {1} past the minute" ) , lambda s : _ ( "at {0} seconds past the minute" ) ) |
def upload_microscope_files ( self , plate_name , acquisition_name , path , parallel = 1 , retry = 5 , convert = None , delete_after_upload = False , _deprecated_directory_option = False ) :
'''Uploads microscope files contained in ` path ` .
If ` path ` is a directory , upload all files contained in it .
Param... | if _deprecated_directory_option :
logger . warn ( "The `--directory` option is now superfluous." " You can remove it from the command line." )
# TODO : consider using os . walk ( ) to screen subdirectories recursively
logger . info ( 'upload microscope files for experiment "%s", plate "%s" ' 'and acquisition "%s"' ... |
def nl_skipped_handler_debug ( msg , arg ) :
"""https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / handlers . c # L134.""" | ofd = arg or _LOGGER . debug
ofd ( '-- Debug: Skipped message: ' + print_header_content ( nlmsg_hdr ( msg ) ) )
return NL_SKIP |
def add_md ( text , s , level = 0 ) :
"""Adds text to the readme at the given level""" | if level > 0 :
if text != "" :
text += "\n"
text += "#" * level
text += " "
text += s + "\n"
if level > 0 :
text += "\n"
return text |
def run_parallel ( workflow , * , n_threads , registry , db_file , echo_log = True , always_cache = False ) :
"""Run a workflow in parallel threads , storing results in a Sqlite3
database .
: param workflow : Workflow or PromisedObject to evaluate .
: param n _ threads : number of threads to use ( in addition... | if echo_log :
logging . getLogger ( 'noodles' ) . setLevel ( logging . DEBUG )
logging . debug ( "--- start log ---" )
with JobDB ( db_file , registry ) as db :
job_queue = Queue ( )
result_queue = Queue ( )
job_logger = make_logger ( "worker" , push_map , db )
result_logger = make_logger ( "wor... |
def tasks ( self , task_cls = None ) :
""": meth : ` . WTaskRegistryBase . tasks ` implementation""" | result = [ ]
for tasks in self . __registry . values ( ) :
result . extend ( tasks )
if task_cls is not None :
result = filter ( lambda x : issubclass ( x , task_cls ) , result )
return tuple ( result ) |
def on_key ( self , view , key , event ) :
"""Trigger the key event
Parameters
view : int
The ID of the view that sent this event
key : int
The code of the key that was pressed
data : bytes
The msgpack encoded key event""" | d = self . declaration
r = { 'key' : key , 'result' : False }
d . key_event ( r )
return r [ 'result' ] |
def _show_popup ( self , index = 0 ) :
"""Shows the popup at the specified index .
: param index : index
: return :""" | full_prefix = self . _helper . word_under_cursor ( select_whole_word = False ) . selectedText ( )
if self . _case_sensitive :
self . _completer . setCaseSensitivity ( QtCore . Qt . CaseSensitive )
else :
self . _completer . setCaseSensitivity ( QtCore . Qt . CaseInsensitive )
# set prefix
self . _completer . se... |
def from_input ( cls , input_file = sys . stdin , modify = None , backend = None ) :
"""Creates a Task object , directly from the stdin , by reading one line .
If modify = True , two lines are used , first line interpreted as the
original state of the Task object , and second line as its new ,
modified value ... | # Detect the hook type if not given directly
name = os . path . basename ( sys . argv [ 0 ] )
modify = name . startswith ( 'on-modify' ) if modify is None else modify
# Create the TaskWarrior instance if none passed
if backend is None :
backends = importlib . import_module ( 'tasklib.backends' )
hook_parent_dir... |
def readInputFile ( self , card_name , directory , session , spatial = False , spatialReferenceID = None , ** kwargs ) :
"""Read specific input file for a GSSHA project to the database .
Args :
card _ name ( str ) : Name of GSSHA project card .
directory ( str ) : Directory containing all GSSHA model files . ... | self . project_directory = directory
with tmp_chdir ( directory ) : # Read in replace param file
replaceParamFile = self . _readReplacementFiles ( directory , session , spatial , spatialReferenceID )
return self . _readXputFile ( self . INPUT_FILES , card_name , directory , session , spatial , spatialReferenceI... |
def messageReceived ( self , message ) :
"""Called on incoming message from ZeroMQ .
Dispatches message to back to the requestor .
: param message : message data""" | msgId , msg = message [ 0 ] , message [ 2 : ]
self . _releaseId ( msgId )
d , canceller = self . _requests . pop ( msgId , ( None , None ) )
if canceller is not None and canceller . active ( ) :
canceller . cancel ( )
if d is None : # reply came for timed out or cancelled request , drop it silently
return
d . c... |
def getContextsForExpression ( self , body , getFingerprint = None , startIndex = 0 , maxResults = 5 , sparsity = 1.0 ) :
"""Get semantic contexts for the input expression
Args :
body , ExpressionOperation : The JSON encoded expression to be evaluated ( required )
getFingerprint , bool : Configure if the fing... | return self . _expressions . getContextsForExpression ( self . _retina , body , getFingerprint , startIndex , maxResults , sparsity ) |
def change_status ( self , bucket , key , status , cond ) :
"""修改文件的状态
修改文件的存储类型为可用或禁用 :
Args :
bucket : 待操作资源所在空间
key : 待操作资源文件名
storage _ type : 待操作资源存储类型 , 0为启用 , 1为禁用""" | resource = entry ( bucket , key )
if cond and isinstance ( cond , dict ) :
condstr = ""
for k , v in cond . items ( ) :
condstr += "{0}={1}&" . format ( k , v )
condstr = urlsafe_base64_encode ( condstr [ : - 1 ] )
return self . __rs_do ( 'chstatus' , resource , 'status/{0}' . format ( status ) ... |
def apply_patches ( self ) :
"""Applies the patches .
: return : Method success .
: rtype : bool""" | success = True
for name , patch in sorted ( self ) :
success = self . apply_patch ( patch )
return success |
def weights ( self ) :
"""TODO : add documentation
( Nx3)""" | if self . _weights is not None and len ( self . _weights ) :
return self . _weights
else :
return np . full ( ( self . Ntriangles , 3 ) , 1. / 3 ) |
def get_design_document ( self , ddoc_id ) :
"""Retrieves a design document . If a design document exists remotely
then that content is wrapped in a DesignDocument object and returned
to the caller . Otherwise a " shell " DesignDocument object is returned .
: param str ddoc _ id : Design document id
: retur... | ddoc = DesignDocument ( self , ddoc_id )
try :
ddoc . fetch ( )
except HTTPError as error :
if error . response . status_code != 404 :
raise
return ddoc |
def serialize ( self , as_dict = False , sort = None ) :
"""Dump built files as a list or dictionary , for JSON or other serialization .
sort : a key function to sort a list , or simply True""" | files = getattr ( self , 'files' , self . run ( ) )
if as_dict :
return dict ( ( fn , p . to_dict ( ) ) for fn , p in files . items ( ) )
# generate a list
data = ( p . to_dict ( ) for p in files . values ( ) )
if callable ( sort ) :
return sorted ( data , key = sort )
elif sort is True :
return sorted ( da... |
def Polygon ( pos = ( 0 , 0 , 0 ) , normal = ( 0 , 0 , 1 ) , nsides = 6 , r = 1 , c = "coral" , bc = "darkgreen" , lw = 1 , alpha = 1 , followcam = False ) :
"""Build a 2D polygon of ` nsides ` of radius ` r ` oriented as ` normal ` .
: param followcam : if ` True ` the text will auto - orient itself to the activ... | ps = vtk . vtkRegularPolygonSource ( )
ps . SetNumberOfSides ( nsides )
ps . SetRadius ( r )
ps . SetNormal ( - np . array ( normal ) )
ps . Update ( )
tf = vtk . vtkTriangleFilter ( )
tf . SetInputConnection ( ps . GetOutputPort ( ) )
tf . Update ( )
mapper = vtk . vtkPolyDataMapper ( )
mapper . SetInputConnection ( t... |
def _not_empty ( self , view , slice_ ) :
"""Checks if the density is too low .""" | img2d = self . _get_axis ( self . _image , view , slice_ )
return ( np . count_nonzero ( img2d ) / img2d . size ) > self . _min_density |
def conditional_probability_alive_matrix ( self , max_frequency = None , max_recency = None ) :
"""Compute the probability alive matrix .
Parameters
max _ frequency : float , optional
the maximum frequency to plot . Default is max observed frequency .
max _ recency : float , optional
the maximum recency t... | max_frequency = max_frequency or int ( self . data [ "frequency" ] . max ( ) )
max_recency = max_recency or int ( self . data [ "T" ] . max ( ) )
return np . fromfunction ( self . conditional_probability_alive , ( max_frequency + 1 , max_recency + 1 ) , T = max_recency ) . T |
def find_requirements ( max_depth = 3 ) :
"""Returns the path of a Pipfile in parent directories .""" | i = 0
for c , d , f in walk_up ( os . getcwd ( ) ) :
i += 1
if i < max_depth :
if "requirements.txt" :
r = os . path . join ( c , "requirements.txt" )
if os . path . isfile ( r ) :
return r
raise RuntimeError ( "No requirements.txt found!" ) |
def login ( self , username = None , password = None ) :
"""Login to a vSphere server .
> > > client . login ( username = ' Administrator ' , password = ' strongpass ' )
: param username : The username to authenticate as .
: type username : str
: param password : The password to authenticate with .
: type... | if username is None :
username = self . username
if password is None :
password = self . password
logger . debug ( "Logging into server" )
self . sc . sessionManager . Login ( userName = username , password = password )
self . _logged_in = True |
def pole ( self , strike , dip , * args , ** kwargs ) :
"""Plot points representing poles to planes on the axes . Additional
arguments and keyword arguments are passed on to ` ax . plot ` .
Parameters
strike , dip : numbers or sequences of numbers
The strike and dip of the plane ( s ) in degrees . The dip d... | lon , lat = stereonet_math . pole ( strike , dip )
args , kwargs = self . _point_plot_defaults ( args , kwargs )
return self . plot ( lon , lat , * args , ** kwargs ) |
def _get_stddevs ( self , C , rup , dists , sites , stddev_types ) :
"""Returns the aleatory uncertainty terms described in equations ( 13 ) to
(17)""" | stddevs = [ ]
num_sites = len ( sites . vs30 )
tau = self . _get_inter_event_tau ( C , rup . mag , num_sites )
phi = self . _get_intra_event_phi ( C , rup . mag , dists . rjb , sites . vs30 , num_sites )
for stddev_type in stddev_types :
assert stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stdde... |
def fetch_open_data ( cls , ifo , start , end , sample_rate = 4096 , tag = None , version = None , format = 'hdf5' , host = GWOSC_DEFAULT_HOST , verbose = False , cache = None , ** kwargs ) :
"""Fetch open - access data from the LIGO Open Science Center
Parameters
ifo : ` str `
the two - character prefix of t... | from . io . losc import fetch_losc_data
return fetch_losc_data ( ifo , start , end , sample_rate = sample_rate , tag = tag , version = version , format = format , verbose = verbose , cache = cache , host = host , cls = cls , ** kwargs ) |
def add_global_ip ( self , version = 4 , test_order = False ) :
"""Adds a global IP address to the account .
: param int version : Specifies whether this is IPv4 or IPv6
: param bool test _ order : If true , this will only verify the order .""" | # This method is here to improve the public interface from a user ' s
# perspective since ordering a single global IP through the subnet
# interface is not intuitive .
return self . add_subnet ( 'global' , version = version , test_order = test_order ) |
def get_admin_url ( self , query_params = None , use_path = False ) :
"""Returns the URL for viewing a FileNode in the admin .""" | if not query_params :
query_params = { }
url = ''
if self . is_top_node ( ) :
url = reverse ( 'admin:media_tree_filenode_changelist' ) ;
elif use_path and ( self . is_folder ( ) or self . pk ) :
url = reverse ( 'admin:media_tree_filenode_open_path' , args = ( self . get_path ( ) , ) ) ;
elif self . is_folde... |
def asymmetric_round_price_to_penny ( price , prefer_round_down , diff = ( 0.0095 - .005 ) ) :
"""Asymmetric rounding function for adjusting prices to two places in a way
that " improves " the price . For limit prices , this means preferring to
round down on buys and preferring to round up on sells . For stop p... | # Subtracting an epsilon from diff to enforce the open - ness of the upper
# bound on buys and the lower bound on sells . Using the actual system
# epsilon doesn ' t quite get there , so use a slightly less epsilon - ey value .
epsilon = float_info . epsilon * 10
diff = diff - epsilon
# relies on rounding half away fro... |
def lookup_asn ( self , * args , ** kwargs ) :
"""Temporary wrapper for IP ASN lookups ( moved to
asn . IPASN . lookup ( ) ) . This will be removed in a future
release .""" | from warnings import warn
warn ( 'Net.lookup_asn() has been deprecated and will be removed. ' 'You should now use asn.IPASN.lookup() for IP ASN lookups.' )
from . asn import IPASN
response = None
ipasn = IPASN ( self )
return ipasn . lookup ( * args , ** kwargs ) , response |
def add ( self , elem ) :
"""Adds a JWK object to the set
: param elem : the JWK object to add .
: raises TypeError : if the object is not a JWK .""" | if not isinstance ( elem , JWK ) :
raise TypeError ( 'Only JWK objects are valid elements' )
set . add ( self , elem ) |
def on_open ( self , info ) :
"""sockjs - tornado on _ open handler""" | # Store some properties
self . ip = info . ip
# Create fake request object
self . request = info
# Call open
self . open ( ) |
def version ( self , content_type = "*/*" ) :
"""versioning is based off of this post
http : / / urthen . github . io / 2013/05/09 / ways - to - version - your - api /""" | v = ""
accept_header = self . get_header ( 'accept' , "" )
if accept_header :
a = AcceptHeader ( accept_header )
for mt in a . filter ( content_type ) :
v = mt [ 2 ] . get ( "version" , "" )
if v :
break
return v |
def getsizeof ( o , ids = None ) :
'''Find the memory footprint of a Python object recursively , see
https : / / code . tutsplus . com / tutorials / understand - how - much - memory - your - python - objects - use - - cms - 25609
: param o : the object
: returns : the size in bytes''' | ids = ids or set ( )
if id ( o ) in ids :
return 0
nbytes = sys . getsizeof ( o )
ids . add ( id ( o ) )
if isinstance ( o , Mapping ) :
return nbytes + sum ( getsizeof ( k , ids ) + getsizeof ( v , ids ) for k , v in o . items ( ) )
elif isinstance ( o , Container ) :
return nbytes + sum ( getsizeof ( x , ... |
def create_activity ( self , name , activity_type , start_date_local , elapsed_time , description = None , distance = None ) :
"""Create a new manual activity .
If you would like to create an activity from an uploaded GPS file , see the
: meth : ` stravalib . client . Client . upload _ activity ` method instead... | if isinstance ( elapsed_time , timedelta ) :
elapsed_time = unithelper . timedelta_to_seconds ( elapsed_time )
if isinstance ( distance , Quantity ) :
distance = float ( unithelper . meters ( distance ) )
if isinstance ( start_date_local , datetime ) :
start_date_local = start_date_local . strftime ( "%Y-%m... |
def start ( self ) :
"""Start the client and connect""" | # TODO ( NM 2015-03-12 ) Some checking to prevent multiple calls to start ( )
host , port = self . address
ic = self . _inspecting_client = self . inspecting_client_factory ( host , port , self . _ioloop_set_to )
self . ioloop = ic . ioloop
if self . _preset_protocol_flags :
ic . preset_protocol_flags ( self . _pre... |
def build_service ( service_descriptor , did ) :
"""Build a service .
: param service _ descriptor : Tuples of length 2 . The first item must be one of ServiceTypes
and the second item is a dict of parameters and values required by the service
: param did : DID , str
: return : Service""" | assert isinstance ( service_descriptor , tuple ) and len ( service_descriptor ) == 2 , 'Unknown service descriptor format.'
service_type , kwargs = service_descriptor
if service_type == ServiceTypes . METADATA :
return ServiceFactory . build_metadata_service ( did , kwargs [ 'metadata' ] , kwargs [ 'serviceEndpoint... |
def Field_to_xarray ( field ) :
'''Convert a climlab . Field object to xarray . DataArray''' | dom = field . domain
dims = [ ] ;
dimlist = [ ] ;
coords = { } ;
for axname in dom . axes :
dimlist . append ( axname )
try :
assert field . interfaces [ dom . axis_index [ axname ] ]
bounds_name = axname + '_bounds'
dims . append ( bounds_name )
coords [ bounds_name ] = dom . ax... |
def extractFromSQLFile ( self , filePointer , delimiter = ";" ) :
"""Process an SQL file and extract all the queries sorted .
: param filePointer : < io . TextIOWrapper > file pointer to SQL file
: return : < list > list of queries""" | data = filePointer . read ( )
# reading file and splitting it into lines
dataLines = [ ]
dataLinesIndex = 0
for c in data :
if len ( dataLines ) - 1 < dataLinesIndex :
dataLines . append ( "" )
if c == "\r\n" or c == "\r" or c == "\n" :
dataLinesIndex += 1
else :
dataLines [ dataLine... |
def get_file_path ( self , name , relative_path ) :
"""Return the path to a resource file .""" | dist = self . get_distribution ( name )
if dist is None :
raise LookupError ( 'no distribution named %r found' % name )
return dist . get_resource_path ( relative_path ) |
def rsem_multimapping_plot ( self ) :
"""Make a line plot showing the multimapping levels""" | pconfig = { 'id' : 'rsem_multimapping_rates' , 'title' : 'RSEM: Multimapping Rates' , 'ylab' : 'Counts' , 'xlab' : 'Number of alignments' , 'xDecimals' : False , 'ymin' : 0 , 'tt_label' : '<b>{point.x} alignments</b>: {point.y:.0f}' , }
self . add_section ( name = 'Multimapping rates' , anchor = 'rsem_multimapping' , d... |
def set ( self , value ) :
"""Set the value of the bar . If the value is out of bound , sets it to an extremum""" | value = min ( self . max , max ( self . min , value ) )
self . _value = value
start_new_thread ( self . func , ( self . get ( ) , ) ) |
def map ( self , callback ) :
"""Run a map over each of the item .
: param callback : The map function
: type callback : callable
: rtype : Collection""" | if isinstance ( self . _items , dict ) :
return Collection ( list ( map ( callback , self . _items . values ( ) ) ) )
return Collection ( list ( map ( callback , self . _items ) ) ) |
def get_activity_admin_session ( self , proxy , * args , ** kwargs ) :
"""Gets the ` ` OsidSession ` ` associated with the activity administration service .
: param proxy : a proxy
: type proxy : ` ` osid . proxy . Proxy ` `
: return : an ` ` ActivityAdminSession ` `
: rtype : ` ` osid . learning . Activity... | if not self . supports_activity_admin ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . ActivityAdminSession ( proxy = proxy , runtime = self . _runtime )
except AttributeError :
... |
def public_pair_to_sec ( public_pair , compressed = True ) :
"""Convert a public pair ( a pair of bignums corresponding to a public key ) to the
gross internal sec binary format used by OpenSSL .""" | x_str = to_bytes_32 ( public_pair [ 0 ] )
if compressed :
return int2byte ( ( 2 + ( public_pair [ 1 ] & 1 ) ) ) + x_str
y_str = to_bytes_32 ( public_pair [ 1 ] )
return b'\4' + x_str + y_str |
def reset ( self , lineno = None , offset = None , type_ = None ) :
"""This is called when we need to reinitialize the instance state""" | self . lineno = self . lineno if lineno is None else lineno
self . type_ = self . type_ if type_ is None else type_
self . offset = self . offset if offset is None else offset
self . callable = True
self . params = SymbolPARAMLIST ( )
self . body = SymbolBLOCK ( )
self . __kind = KIND . unknown
self . local_symbol_tabl... |
def validate_netmask ( s ) :
"""Validate that a dotted - quad ip address is a valid netmask .
> > > validate _ netmask ( ' 0.0.0.0 ' )
True
> > > validate _ netmask ( ' 128.0.0.0 ' )
True
> > > validate _ netmask ( ' 255.0.0.0 ' )
True
> > > validate _ netmask ( ' 255.255.255.255 ' )
True
> > > va... | if validate_ip ( s ) : # Convert to binary string , strip ' 0b ' prefix , 0 pad to 32 bits
mask = bin ( ip2network ( s ) ) [ 2 : ] . zfill ( 32 )
# all left most bits must be 1 , all right most must be 0
seen0 = False
for c in mask :
if '1' == c :
if seen0 :
return Fa... |
def _job_sorting_key ( self , job ) :
"""Get the sorting key of a CFGJob instance .
: param CFGJob job : the CFGJob object .
: return : An integer that determines the order of this job in the queue .
: rtype : int""" | if self . _base_graph is None : # we don ' t do sorting if there is no base _ graph
return 0
MAX_JOBS = 1000000
if job . addr not in self . _node_addr_visiting_order :
return MAX_JOBS
return self . _node_addr_visiting_order . index ( job . addr ) |
def run ( connection ) :
"""Parse arguments and start upload / download""" | parser = argparse . ArgumentParser ( description = """
Process database dumps.
Either download of upload a dump file to the objectstore.
downloads the latest dump and uploads with envronment and date
into given container destination
""" )
parser . add_argument ( 'location' , nargs = 1 , default = ... |
def get_domain_class_member_attribute_iterator ( ent ) :
"""Returns an iterator over all terminal attributes in the given registered
resource .""" | for attr in itervalues_ ( ent . __everest_attributes__ ) :
if attr . kind == RESOURCE_ATTRIBUTE_KINDS . MEMBER :
yield attr |
def _encode_observations ( self , observations ) :
"""Encodes observations as PNG .""" | return [ Observation ( self . _session . obj . run ( self . _encoded_image_t . obj , feed_dict = { self . _decoded_image_p . obj : observation } ) , self . _decode_png ) for observation in observations ] |
def new_percent_saved ( report_stats ) :
"""Spit out how much space the optimization saved .""" | size_in = report_stats . bytes_in
if size_in > 0 :
size_out = report_stats . bytes_out
ratio = size_out / size_in
kb_saved = _humanize_bytes ( size_in - size_out )
else :
ratio = 0
kb_saved = 0
percent_saved = ( 1 - ratio ) * 100
result = '{:.{prec}f}% ({})' . format ( percent_saved , kb_saved , pre... |
def change_option ( self , option_name , new_value ) :
"""Change a config option .
This function is called if sig _ option _ changed is received . If the
option changed is the dataframe format , then the leading ' % ' character
is stripped ( because it can ' t be stored in the user config ) . Then ,
the sig... | if option_name == 'dataframe_format' :
assert new_value . startswith ( '%' )
new_value = new_value [ 1 : ]
self . sig_option_changed . emit ( option_name , new_value ) |
def lcm ( num1 , num2 ) :
"""Find the lowest common multiple of 2 numbers
: type num1 : number
: param num1 : The first number to find the lcm for
: type num2 : number
: param num2 : The second number to find the lcm for""" | if num1 > num2 :
bigger = num1
else :
bigger = num2
while True :
if bigger % num1 == 0 and bigger % num2 == 0 :
return bigger
bigger += 1 |
def parse_date ( my_date ) :
"""Parse a date into canonical format of datetime . dateime .
: param my _ date : Either datetime . datetime or string in
' % Y - % m - % dT % H : % M : % SZ ' format .
: return : A datetime . datetime .
PURPOSE : Parse a date and make sure it has no time zone .""" | if isinstance ( my_date , datetime . datetime ) :
result = my_date
elif isinstance ( my_date , str ) :
result = datetime . datetime . strptime ( my_date , '%Y-%m-%dT%H:%M:%SZ' )
else :
raise ValueError ( 'Unexpected date format for "%s" of type "%s"' % ( str ( my_date ) , type ( my_date ) ) )
assert result ... |
def rst_to_notebook ( infile , outfile ) :
"""Convert an rst file to a notebook file .""" | # Read infile into a string
with open ( infile , 'r' ) as fin :
rststr = fin . read ( )
# Convert string from rst to markdown
mdfmt = 'markdown_github+tex_math_dollars+fenced_code_attributes'
mdstr = pypandoc . convert_text ( rststr , mdfmt , format = 'rst' , extra_args = [ '--atx-headers' ] )
# In links , replace ... |
def enrolled_device_id ( self , enrolled_device_id ) :
"""Sets the enrolled _ device _ id of this EnrollmentIdentity .
The ID of the device in the Device Directory once it has been registered .
: param enrolled _ device _ id : The enrolled _ device _ id of this EnrollmentIdentity .
: type : str""" | if enrolled_device_id is None :
raise ValueError ( "Invalid value for `enrolled_device_id`, must not be `None`" )
if enrolled_device_id is not None and not re . search ( '^[A-Za-z0-9]{32}' , enrolled_device_id ) :
raise ValueError ( "Invalid value for `enrolled_device_id`, must be a follow pattern or equal to `... |
def json ( self , data ) :
"""Encodes the dictionary being passed to JSON and sets the Header to application / json""" | self . write ( json_ . encode ( data ) )
self . set_header ( 'Content-type' , 'application/json' ) |
def list_gebouwen_adapter ( obj , request ) :
"""Adapter for rendering a list of
: class : ` crabpy . gateway . crab . Gebouw ` to json .""" | return { 'id' : obj . id , 'aard' : { 'id' : obj . aard . id , 'naam' : obj . aard . naam , 'definitie' : obj . aard . definitie } , 'status' : { 'id' : obj . status . id , 'naam' : obj . status . naam , 'definitie' : obj . status . definitie } } |
def open_window ( self , private = False ) :
"""Open a new browser window .
Args :
private ( bool ) : Optional parameter to open a private browsing
window . Defaults to False .
Returns :
: py : class : ` BrowserWindow ` : Opened window .""" | handles_before = self . selenium . window_handles
self . switch_to ( )
with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : # Opens private or non - private window
self . selenium . find_element ( * self . _file_menu_button_locator ) . click ( )
if private :
self . selenium . find_eleme... |
def sojourn_time ( p ) :
"""Calculate sojourn time based on a given transition probability matrix .
Parameters
p : array
( k , k ) , a Markov transition probability matrix .
Returns
: array
( k , ) , sojourn times . Each element is the expected time a Markov
chain spends in each states before leaving ... | p = np . asarray ( p )
pii = p . diagonal ( )
if not ( 1 - pii ) . all ( ) :
print ( "Sojourn times are infinite for absorbing states!" )
return 1 / ( 1 - pii ) |
def FromType ( ftype ) :
"""DocField subclasses factory , creates a convenient field to store
data from a given Type .
attribute precedence :
* ` ` | attrs | > 0 ` ` ( ` ` multi ` ` and ` ` uniq ` ` are implicit ) = > VectorField
* ` ` uniq ` ` ( ` ` multi ` ` is implicit ) = > SetField
* ` ` multi ` ` an... | if ftype . attrs is not None and len ( ftype . attrs ) :
return VectorField ( ftype )
elif ftype . uniq :
return SetField ( ftype )
elif ftype . multi :
return ListField ( ftype )
else :
return ValueField ( ftype ) |
def connect ( self , addr ) :
'''Call adb connect
Return true when connect success''' | if addr . find ( ':' ) == - 1 :
addr += ':5555'
output = self . run_cmd ( 'connect' , addr )
return 'unable to connect' not in output |
def release ( self ) :
"""Release the pidfile .
Close and delete the Pidfile .
: return : None""" | try :
self . pidfile . close ( )
os . remove ( self . _pidfile )
except OSError as err :
if err . errno != 2 :
raise |
def find_one_sql ( table , filter , fields = None ) :
'''> > > find _ one _ sql ( ' tbl ' , { ' foo ' : 10 , ' bar ' : ' baz ' } )
( ' SELECT * FROM tbl WHERE bar = $ 1 AND foo = $ 2 ' , [ ' baz ' , 10 ] )
> > > find _ one _ sql ( ' tbl ' , { ' id ' : 10 } , fields = [ ' foo ' , ' bar ' ] )
( ' SELECT foo , b... | keys , values = _split_dict ( filter )
fields = ', ' . join ( fields ) if fields else '*'
where = _pairs ( keys )
sql = 'SELECT {} FROM {} WHERE {}' . format ( fields , table , where )
return sql , values |
def add_edges ( self , edges , src_field = None , dst_field = None ) :
"""Add edges to the SGraph . Edges should be input as a list of
: class : ` ~ turicreate . Edge ` objects , an : class : ` ~ turicreate . SFrame ` , or a
Pandas DataFrame . If the new edges are in an SFrame or DataFrame , then
` ` src _ fi... | sf = _edge_data_to_sframe ( edges , src_field , dst_field )
with cython_context ( ) :
proxy = self . __proxy__ . add_edges ( sf . __proxy__ , _SRC_VID_COLUMN , _DST_VID_COLUMN )
return SGraph ( _proxy = proxy ) |
def is_possible_number_for_type ( numobj , numtype ) :
"""Convenience wrapper around is _ possible _ number _ for _ type _ with _ reason .
Instead of returning the reason for failure , this method returns true if
the number is either a possible fully - qualified number ( containing the area
code and country c... | result = is_possible_number_for_type_with_reason ( numobj , numtype )
return ( result == ValidationResult . IS_POSSIBLE or result == ValidationResult . IS_POSSIBLE_LOCAL_ONLY ) |
def _repr_html_ ( self , ** kwargs ) :
"""Displays the HTML Map in a Jupyter notebook .""" | if self . _parent is None :
self . add_to ( Figure ( ) )
out = self . _parent . _repr_html_ ( ** kwargs )
self . _parent = None
else :
out = self . _parent . _repr_html_ ( ** kwargs )
return out |
def set_command_attributes ( self , name , attributes ) :
"""Sets the xml attributes of a specified command .""" | if self . command_exists ( name ) :
command = self . commands . get ( name )
command [ 'attributes' ] = attributes |
def _call ( self , x ) :
"""Apply the functional to the given point .""" | x_norm = self . __norm ( x )
if x_norm > 1 :
return np . inf
else :
return 0 |
def heightmap_add_fbm ( hm : np . ndarray , noise : tcod . noise . Noise , mulx : float , muly : float , addx : float , addy : float , octaves : float , delta : float , scale : float , ) -> None :
"""Add FBM noise to the heightmap .
The noise coordinate for each map cell is
` ( ( x + addx ) * mulx / width , ( y... | noise = noise . noise_c if noise is not None else ffi . NULL
lib . TCOD_heightmap_add_fbm ( _heightmap_cdata ( hm ) , noise , mulx , muly , addx , addy , octaves , delta , scale , ) |
def sum ( a , axis = - 1 ) :
"""Sum TT - vector over specified axes""" | d = a . d
crs = _vector . vector . to_list ( a . tt if isinstance ( a , _matrix . matrix ) else a )
if axis < 0 :
axis = range ( a . d )
elif isinstance ( axis , int ) :
axis = [ axis ]
axis = list ( axis ) [ : : - 1 ]
for ax in axis :
crs [ ax ] = _np . sum ( crs [ ax ] , axis = 1 )
rleft , rright = cr... |
def add_member ( self , address , ** kwargs ) :
"""Add a member to a group .
All Fiesta membership options can be passed in as keyword
arguments . Some valid options include :
- ` group _ name ` : Since each member can access a group using
their own name , you can override the ` group _ name ` in this
met... | path = 'membership/%s' % self . id
kwargs [ "address" ] = address
if "group_name" not in kwargs and self . default_name :
kwargs [ "group_name" ] = self . default_name
response_data = self . api . request ( path , kwargs )
if 'user_id' in response_data :
user_id = response_data [ 'user_id' ]
return FiestaUs... |
def validate ( self ) :
"""Could this config be used to send a real email ?""" | missing = [ ]
for k , v in self . _map . items ( ) :
attr = getattr ( self , k , False )
if not attr or attr == CONFIG_PLACEHOLDER :
missing . append ( v )
if missing :
return "Missing or invalid config values: {}" . format ( ", " . join ( sorted ( missing ) ) ) |
def bind ( self , lan ) :
"""bind to a LAN .""" | if _debug :
Node . _debug ( "bind %r" , lan )
lan . add_node ( self ) |
def rand_imancon_NOTWORKING ( x , rho ) :
"""Iman - Conover Method to generate random ordinal variables .
Implementation from Mildenhall ( 2005 ) that is NOT working .
x : ndarray
< obs x cols > matrix with " cols " ordinal variables
that are uncorrelated .
rho : ndarray
Spearman Rank Correlation Matrix... | import numpy as np
from scipy . stats import norm
import warnings
warnings . warn ( ( "This implementation of the the Iman-Conover methods is " "not working properly. Please check if 'Y=ox.rand_imancon(X,C)' " "are close to the target correlation C. For example " " 'Cnew=ox.corr_tau(Y)' and 'np.abs(C - Cnew)'. " ) )
# ... |
def lazy_enumerate ( self , ** kwargs ) :
'''Enumerate without evaluating any sets .''' | kwargs [ 'lazy' ] = True
for item in self . enumerate ( ** kwargs ) :
yield item |
def fetch_album_name ( self ) :
"""Get the name of the album from lastfm .""" | response = get_lastfm ( 'track.getInfo' , artist = self . artist , track = self . title )
if response :
try :
self . album = response [ 'track' ] [ 'album' ] [ 'title' ]
logger . debug ( 'Found album %s from lastfm' , self . album )
except Exception :
logger . warning ( 'Could not fetch ... |
def setupScene ( self ) :
"Purpose : create a sea of cubes" | if self . m_pHMD is None :
return
vertdataarray = list ( )
matScale = Matrix4 ( )
matScale . scale ( self . m_fScale , self . m_fScale , self . m_fScale )
matTransform = Matrix4 ( )
matTransform . translate ( [ - ( float ( self . m_iSceneVolumeWidth ) * self . m_fScaleSpacing ) / 2.0 , - ( float ( self . m_iSceneVo... |
def get_word_saliency ( topic_word_distrib , doc_topic_distrib , doc_lengths ) :
"""Calculate word saliency according to Chuang et al . 2012.
saliency ( w ) = p ( w ) * distinctiveness ( w )
J . Chuang , C . Manning , J . Heer 2012 : " Termite : Visualization Techniques for Assessing Textual Topic Models " """ | p_t = get_marginal_topic_distrib ( doc_topic_distrib , doc_lengths )
p_w = get_marginal_word_distrib ( topic_word_distrib , p_t )
return p_w * get_word_distinctiveness ( topic_word_distrib , p_t ) |
def _project_perturbation ( perturbation , epsilon , input_image , clip_min = None , clip_max = None ) :
"""Project ` perturbation ` onto L - infinity ball of radius ` epsilon ` .
Also project into hypercube such that the resulting adversarial example
is between clip _ min and clip _ max , if applicable .""" | if clip_min is None or clip_max is None :
raise NotImplementedError ( "_project_perturbation currently has clipping " "hard-coded in." )
# Ensure inputs are in the correct range
with tf . control_dependencies ( [ utils_tf . assert_less_equal ( input_image , tf . cast ( clip_max , input_image . dtype ) ) , utils_tf ... |
def formfield_for_foreignkey_helper ( inline , * args , ** kwargs ) :
"""The implementation for ` ` RelatedContentInline . formfield _ for _ foreignkey ` `
This takes the takes all of the ` ` args ` ` and ` ` kwargs ` ` from the call to
` ` formfield _ for _ foreignkey ` ` and operates on this . It returns the ... | db_field = args [ 0 ]
if db_field . name != "related_type" :
return args , kwargs
initial_filter = getattr ( settings , RELATED_TYPE_INITIAL_FILTER , False )
if "initial" not in kwargs and initial_filter : # TODO : handle gracefully if unable to load and in non - debug
initial = RelatedType . objects . get ( **... |
def throttle ( self , wait = True ) :
"""If the wait parameter is True , this method returns True after suspending the current
thread as necessary to ensure that no less than the configured minimum interval passed
since the most recent time an invocation of this method returned True in any thread .
If the wai... | # I think there is a race in Thread . start ( ) , hence the lock
with self . thread_start_lock :
if not self . thread_started :
self . thread . start ( )
self . thread_started = True
return self . semaphore . acquire ( blocking = wait ) |
def setup ( self ) :
"""Setup .""" | self . comments = self . config [ 'comments' ]
self . docstrings = self . config [ 'docstrings' ]
self . strings = self . config [ 'strings' ]
self . group_comments = self . config [ 'group_comments' ]
self . string_types , self . wild_string_types = self . eval_string_type ( self . config [ 'string_types' ] )
self . d... |
def draw ( vertexes , edges ) :
"""Build a DAG and draw it in ASCII .
Args :
vertexes ( list ) : list of graph vertexes .
edges ( list ) : list of graph edges .""" | # pylint : disable = too - many - locals
# NOTE : coordinates might me negative , so we need to shift
# everything to the positive plane before we actually draw it .
Xs = [ ]
# pylint : disable = invalid - name
Ys = [ ]
# pylint : disable = invalid - name
sug = _build_sugiyama_layout ( vertexes , edges )
for vertex in ... |
def edit ( text , pos , key ) :
"""Process a key input in the context of a line , and return the
resulting text and cursor position .
` text ' and ` key ' must be of type str or unicode , and ` pos ' must be
an int in the range [ 0 , len ( text ) ] .
If ` key ' is in keys ( ) , the corresponding command is ... | if key in _key_bindings :
return _key_bindings [ key ] ( text , pos )
elif len ( key ) == 1 :
return text [ : pos ] + key + text [ pos : ] , pos + 1
else :
return text , pos |
def load_known_hosts ( self , filename = None ) :
"""Load host keys from an openssh : file : ` known _ hosts ` - style file . Can
be called multiple times .
If * filename * is not specified , looks in the default locations i . e . : file : ` ~ / . ssh / known _ hosts ` and : file : ` ~ / ssh / known _ hosts ` f... | if filename is None :
filename = os . path . expanduser ( '~/.ssh/known_hosts' )
try :
self . _host_keys . load ( filename )
except IOError : # for windows
filename = os . path . expanduser ( '~/ssh/known_hosts' )
try :
self . _host_keys . load ( filename )
except... |
def _run_container ( self , run_command_instance , callback ) :
"""this is internal method""" | tmpfile = os . path . join ( get_backend_tmpdir ( ) , random_tmp_filename ( ) )
# the cid file must not exist
run_command_instance . options += [ "--cidfile=%s" % tmpfile ]
logger . debug ( "podman command: %s" % run_command_instance )
response = callback ( )
# and we need to wait now ; inotify would be better but is w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.