signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _CheckLogFileSize ( cursor ) : """Warns if MySQL log file size is not large enough for blob insertions ."""
# Do not fail , because users might not be able to change this for their # database . Instead , warn the user about the impacts . innodb_log_file_size = int ( _ReadVariable ( "innodb_log_file_size" , cursor ) ) required_size = 10 * mysql_blobs . BLOB_CHUNK_SIZE if innodb_log_file_size < required_size : # See MySQL erro...
def _WsdlHasMethod ( self , method_name ) : """Determine if the wsdl contains a method . Args : method _ name : The name of the method to search . Returns : True if the method is in the WSDL , otherwise False ."""
return method_name in self . suds_client . wsdl . services [ 0 ] . ports [ 0 ] . methods
def list_all_option_values ( cls , ** kwargs ) : """List OptionValues Return a list of OptionValues This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . list _ all _ option _ values ( async = True ) > > > result = th...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _list_all_option_values_with_http_info ( ** kwargs ) else : ( data ) = cls . _list_all_option_values_with_http_info ( ** kwargs ) return data
def reindex_axis ( self , new_index , axis , method = None , limit = None , fill_value = None , copy = True ) : """Conform block manager to new index ."""
new_index = ensure_index ( new_index ) new_index , indexer = self . axes [ axis ] . reindex ( new_index , method = method , limit = limit ) return self . reindex_indexer ( new_index , indexer , axis = axis , fill_value = fill_value , copy = copy )
def reset_uniforms ( self ) : """Resets the uniforms to the Mesh object to the " " global " " coordinate system"""
self . uniforms [ 'model_matrix' ] = self . model_matrix_global . view ( ) self . uniforms [ 'normal_matrix' ] = self . normal_matrix_global . view ( )
def subset_otf_from_ufo ( self , otf_path , ufo ) : """Subset a font using export flags set by glyphsLib . There are two more settings that can change export behavior : " Export Glyphs " and " Remove Glyphs " , which are currently not supported for complexity reasons . See https : / / github . com / googlei...
from fontTools import subset # ufo2ft always inserts a " . notdef " glyph as the first glyph ufo_order = makeOfficialGlyphOrder ( ufo ) if ".notdef" not in ufo_order : ufo_order . insert ( 0 , ".notdef" ) ot_order = TTFont ( otf_path ) . getGlyphOrder ( ) assert ot_order [ 0 ] == ".notdef" assert len ( ufo_order ) ...
def sph2cart ( lon , lat ) : """Converts a longitude and latitude ( or sequence of lons and lats ) given in _ radians _ to cartesian coordinates , ` x ` , ` y ` , ` z ` , where x = 0 , y = 0 , z = 0 is the center of the globe . Parameters lon : array - like Longitude in radians lat : array - like Lati...
x = np . cos ( lat ) * np . cos ( lon ) y = np . cos ( lat ) * np . sin ( lon ) z = np . sin ( lat ) return x , y , z
def setWorkingCollisionBoundsInfo ( self , unQuadsCount ) : """Sets the Collision Bounds in the working copy ."""
fn = self . function_table . setWorkingCollisionBoundsInfo pQuadsBuffer = HmdQuad_t ( ) fn ( byref ( pQuadsBuffer ) , unQuadsCount ) return pQuadsBuffer
def reshape ( tt_array , shape , eps = 1e-14 , rl = 1 , rr = 1 ) : '''Reshape of the TT - vector [ TT1 ] = TT _ RESHAPE ( TT , SZ ) reshapes TT - vector or TT - matrix into another with mode sizes SZ , accuracy 1e - 14 [ TT1 ] = TT _ RESHAPE ( TT , SZ , EPS ) reshapes TT - vector / matrix into another with ...
tt1 = _cp . deepcopy ( tt_array ) sz = _cp . deepcopy ( shape ) ismatrix = False if isinstance ( tt1 , _matrix . matrix ) : d1 = tt1 . tt . d d2 = sz . shape [ 0 ] ismatrix = True # The size should be [ n , m ] in R ^ { d x 2} restn2_n = sz [ : , 0 ] restn2_m = sz [ : , 1 ] sz_n = _cp . copy...
def _build ( self , inputs , ** normalization_build_kwargs ) : """Assembles the ` ConvNet2D ` and connects it to the graph . Args : inputs : A 4D Tensor of shape ` [ batch _ size , input _ height , input _ width , input _ channels ] ` . * * normalization _ build _ kwargs : kwargs passed to the normalization...
if ( self . _normalization_ctor in { batch_norm . BatchNorm , batch_norm_v2 . BatchNormV2 } and "is_training" not in normalization_build_kwargs ) : raise ValueError ( "Boolean is_training flag must be explicitly specified " "when using batch normalization." ) self . _input_shape = tuple ( inputs . get_shape ( ) . a...
def first_seen ( self , first_seen ) : """Set Document first seen ."""
self . _group_data [ 'firstSeen' ] = self . _utils . format_datetime ( first_seen , date_format = '%Y-%m-%dT%H:%M:%SZ' )
def export ( g , csv_fname ) : """export a graph to CSV for simpler viewing"""
with open ( csv_fname , "w" ) as f : num_tuples = 0 f . write ( '"num","subject","predicate","object"\n' ) for subj , pred , obj in g : num_tuples += 1 f . write ( '"' + str ( num_tuples ) + '",' ) f . write ( '"' + get_string_from_rdf ( subj ) + '",' ) f . write ( '"' + get_...
def reload_if_changed ( self , force = False ) : """If the file ( s ) being watched by this object have changed , their configuration will be loaded again using ` config _ loader ` . Otherwise this is a noop . : param force : If True ignore the ` min _ interval ` and proceed to file modified comparisons . T...
if ( force or self . should_check ) and self . file_modified ( ) : return self . reload ( )
def delete_relationship ( self , json_data , relationship_field , related_id_field , view_kwargs ) : """Delete a relationship : param dict json _ data : the request params : param str relationship _ field : the model attribute used for relationship : param str related _ id _ field : the identifier field of th...
self . before_delete_relationship ( json_data , relationship_field , related_id_field , view_kwargs ) obj = self . get_object ( view_kwargs ) if obj is None : url_field = getattr ( self , 'url_field' , 'id' ) filter_value = view_kwargs [ url_field ] raise ObjectNotFound ( '{}: {} not found' . format ( self ...
def save_all ( self ) : """Save all opened files . Iterate through self . data and call save ( ) on any modified files ."""
for index in range ( self . get_stack_count ( ) ) : if self . data [ index ] . editor . document ( ) . isModified ( ) : self . save ( index )
def mixin ( self ) : """Add your own custom functions to the Underscore object , ensuring that they ' re correctly added to the OOP wrapper as well ."""
methods = self . obj for i , k in enumerate ( methods ) : setattr ( underscore , k , methods [ k ] ) self . makeStatic ( ) return self . _wrap ( self . obj )
def _rename_with_content_disposition ( self , response : HTTPResponse ) : '''Rename using the Content - Disposition header .'''
if not self . _filename : return if response . request . url_info . scheme not in ( 'http' , 'https' ) : return header_value = response . fields . get ( 'Content-Disposition' ) if not header_value : return filename = parse_content_disposition ( header_value ) if filename : dir_path = os . path . dirname...
def commit_input_persist ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) commit = ET . Element ( "commit" ) config = commit input = ET . SubElement ( commit , "input" ) persist = ET . SubElement ( input , "persist" ) persist . text = kwargs . pop ( 'persist' ) callback = kwargs . pop ( 'callback' , self . _callback ) return callback ( config )
def accept_response ( self , response_header , content = EmptyValue , content_type = EmptyValue , accept_untrusted_content = False , localtime_offset_in_seconds = 0 , timestamp_skew_in_seconds = default_ts_skew_in_seconds , ** auth_kw ) : """Accept a response to this request . : param response _ header : A ` Ha...
log . debug ( 'accepting response {header}' . format ( header = response_header ) ) parsed_header = parse_authorization_header ( response_header ) resource = Resource ( ext = parsed_header . get ( 'ext' , None ) , content = content , content_type = content_type , # The following response attributes are # in reference t...
def create_transition ( self , from_state_id , from_outcome , to_state_id , to_outcome , transition_id ) : """Creates a new transition . Lookout : Check the parameters first before creating a new transition : param from _ state _ id : The source state of the transition : param from _ outcome : The outcome of ...
# get correct states if from_state_id is not None : if from_state_id == self . state_id : from_state = self else : from_state = self . states [ from_state_id ] # finally add transition if from_outcome is not None : if from_outcome in from_state . outcomes : if to_outcome is not None ...
def _classify_target_compile_workflow ( self , target ) : """Return the compile workflow to use for this target ."""
if target . has_sources ( '.java' ) or target . has_sources ( '.scala' ) : return self . get_scalar_mirrored_target_option ( 'workflow' , target ) return None
def _display_tooltip ( self , tooltip , top ) : """Display tooltip at the specified top position ."""
QtWidgets . QToolTip . showText ( self . mapToGlobal ( QtCore . QPoint ( self . sizeHint ( ) . width ( ) , top ) ) , tooltip , self )
def add_widget ( self , w ) : """Convenience function"""
if self . layout ( ) : self . layout ( ) . addWidget ( w ) else : layout = QVBoxLayout ( self ) layout . addWidget ( w )
def boolean ( input ) : """Convert the given input to a boolean value . Intelligently handles boolean and non - string values , returning as - is and passing to the bool builtin respectively . This process is case - insensitive . Acceptable values : True * yes * on * true False * no * off * ...
try : input = input . strip ( ) . lower ( ) except AttributeError : return bool ( input ) if input in ( 'yes' , 'y' , 'on' , 'true' , 't' , '1' ) : return True if input in ( 'no' , 'n' , 'off' , 'false' , 'f' , '0' ) : return False raise ValueError ( "Unable to convert {0!r} to a boolean value." . forma...
def should_ignore_rule ( self , rule ) : """Determines whether a rule should be ignored based on the general list of commits to ignore"""
return rule . id in self . config . ignore or rule . name in self . config . ignore
def _add_matched_objects_to_database ( self , matchedObjects ) : """* add mathced objects to database * * * Key Arguments : * * - ` ` matchedObjects ` ` - - these objects matched in the neighbourhood of the ATLAS exposures ( list of dictionaries )"""
self . log . info ( 'starting the ``_add_matched_objects_to_database`` method' ) print "Adding the matched sources to the `pyephem_positions` database table" allMatches = [ ] for m in matchedObjects : allMatches += m dbSettings = self . settings [ "database settings" ] [ "atlasMovers" ] insert_list_of_dictionaries_...
def get_latlon ( self , use_cached = True ) : """Get a tuple with device latitude and longitude . . . these may be None"""
device_json = self . get_device_json ( use_cached ) lat = device_json . get ( "dpMapLat" ) lon = device_json . get ( "dpMapLong" ) return ( float ( lat ) if lat else None , float ( lon ) if lon else None , )
def get_temp_and_dew ( wxdata : str ) -> ( [ str ] , Number , Number ) : # type : ignore """Returns the report list and removed temperature and dewpoint strings"""
for i , item in reversed ( list ( enumerate ( wxdata ) ) ) : if '/' in item : # / / / 07 if item [ 0 ] == '/' : item = '/' + item . lstrip ( '/' ) # 07 / / / elif item [ - 1 ] == '/' : item = item . rstrip ( '/' ) + '/' tempdew = item . split ( '/' ) i...
def get_or_create ( cls , * props , ** kwargs ) : """Call to MERGE with parameters map . A new instance will be created and saved if does not already exists , this is an atomic operation . Parameters must contain all required properties , any non required properties with defaults will be generated . Note that...
lazy = kwargs . get ( 'lazy' , False ) relationship = kwargs . get ( 'relationship' ) # build merge query get_or_create_params = [ { "create" : cls . deflate ( p , skip_empty = True ) } for p in props ] query , params = cls . _build_merge_query ( get_or_create_params , relationship = relationship , lazy = lazy ) if 'st...
def install ( ctx , services , delete_after_install = False ) : """Install a honeypot service from the online library , local path or zipfile ."""
logger . debug ( "running command %s (%s)" , ctx . command . name , ctx . params , extra = { "command" : ctx . command . name , "params" : ctx . params } ) home = ctx . obj [ "HOME" ] services_path = os . path . join ( home , SERVICES ) installed_all_plugins = True for service in services : try : plugin_uti...
def setdefault ( elt , key , default , ctx = None ) : """Get a local property and create default value if local property does not exist . : param elt : local proprety elt to get / create . Not None methods . : param str key : proprety name . : param default : property value to set if key no in local propert...
result = default # get the best context if ctx is None : ctx = find_ctx ( elt = elt ) # get elt properties elt_properties = _ctx_elt_properties ( elt = elt , ctx = ctx , create = True ) # if key exists in elt properties if key in elt_properties : # result is elt _ properties [ key ] result = elt_properties [ ke...
def _dump_impl ( ) : # type : ( ) - > List [ FunctionData ] """Internal implementation for dump _ stats and dumps _ stats"""
filtered_signatures = _filter_types ( collected_signatures ) sorted_by_file = sorted ( iteritems ( filtered_signatures ) , key = ( lambda p : ( p [ 0 ] . path , p [ 0 ] . line , p [ 0 ] . func_name ) ) ) res = [ ] # type : List [ FunctionData ] for function_key , signatures in sorted_by_file : comments = [ _make_ty...
def evergreen ( self , included_channel_ids = None , excluded_channel_ids = None , ** kwargs ) : """Search containing any evergreen piece of Content . : included _ channel _ ids list : Contains ids for channel ids relevant to the query . : excluded _ channel _ ids list : Contains ids for channel ids excluded fr...
eqs = self . search ( ** kwargs ) eqs = eqs . filter ( Evergreen ( ) ) if included_channel_ids : eqs = eqs . filter ( VideohubChannel ( included_ids = included_channel_ids ) ) if excluded_channel_ids : eqs = eqs . filter ( VideohubChannel ( excluded_ids = excluded_channel_ids ) ) return eqs
def grow_slice ( slc , size ) : """Grow a slice object by 1 in each direction without overreaching the list . Parameters slc : slice slice object to grow size : int list length Returns slc : slice extended slice"""
return slice ( max ( 0 , slc . start - 1 ) , min ( size , slc . stop + 1 ) )
def get_default_renderer ( self , view ) : """Return an instance of the first valid renderer . ( Don ' t use another documenting renderer . )"""
renderers = [ renderer for renderer in view . renderer_classes if not issubclass ( renderer , BrowsableAPIRenderer ) ] non_template_renderers = [ renderer for renderer in renderers if not hasattr ( renderer , 'get_template_names' ) ] if not renderers : return None elif non_template_renderers : return non_templa...
def from_string ( string : str ) : """Creates a new Spec object from a given string . : param string : The contents of a spec file . : return : A new Spec object ."""
spec = Spec ( ) parse_context = { "current_subpackage" : None } for line in string . splitlines ( ) : spec , parse_context = _parse ( spec , parse_context , line ) return spec
def _get_dst_dir ( dst_dir ) : """Prefix the provided string with working directory and return a str . : param dst _ dir : A string to be prefixed with the working dir . : return : str"""
wd = os . getcwd ( ) _makedirs ( dst_dir ) return os . path . join ( wd , dst_dir )
def from_template ( args ) : """Create a new oct project from existing template : param Namespace args : command line arguments"""
project_name = args . name template = args . template with tarfile . open ( template ) as tar : prefix = os . path . commonprefix ( tar . getnames ( ) ) check_template ( tar . getnames ( ) , prefix ) tar . extractall ( project_name , members = get_members ( tar , prefix ) )
def destroy_decompress ( dinfo ) : """Wraps openjpeg library function opj _ destroy _ decompress ."""
argtypes = [ ctypes . POINTER ( DecompressionInfoType ) ] OPENJPEG . opj_destroy_decompress . argtypes = argtypes OPENJPEG . opj_destroy_decompress ( dinfo )
def clean ( self , text , guess = True , format = None , ** kwargs ) : """The classic : date parsing , every which way ."""
# handle date / datetime before converting to text . date = self . _clean_datetime ( text ) if date is not None : return date text = stringify ( text ) if text is None : return if format is not None : # parse with a specified format try : obj = datetime . strptime ( text , format ) return ob...
def list_machine_group ( self , project_name , offset = 0 , size = 100 ) : """list machine group names in a project Unsuccessful opertaion will cause an LogException . : type project _ name : string : param project _ name : the Project name : type offset : int : param offset : the offset of all group name...
# need to use extended method to get more if int ( size ) == - 1 or int ( size ) > MAX_LIST_PAGING_SIZE : return list_more ( self . list_machine_group , int ( offset ) , int ( size ) , MAX_LIST_PAGING_SIZE , project_name ) headers = { } params = { } resource = "/machinegroups" params [ 'offset' ] = str ( offset ) p...
def filter_ordered_statistics ( ordered_statistics , ** kwargs ) : """Filter OrderedStatistic objects . Arguments : ordered _ statistics - - A OrderedStatistic iterable object . Keyword arguments : min _ confidence - - The minimum confidence of relations ( float ) . min _ lift - - The minimum lift of rela...
min_confidence = kwargs . get ( 'min_confidence' , 0.0 ) min_lift = kwargs . get ( 'min_lift' , 0.0 ) for ordered_statistic in ordered_statistics : if ordered_statistic . confidence < min_confidence : continue if ordered_statistic . lift < min_lift : continue yield ordered_statistic
def _root ( self ) : """Attribute referencing the root node of the tree . : returns : the root node of the tree containing this instance . : rtype : Node"""
_n = self while _n . parent : _n = _n . parent return _n
def from_coeff ( self , chebcoeff , domain = None , prune = True , vscale = 1. ) : """Initialise from provided coefficients prune : Whether to prune the negligible coefficients vscale : the scale to use when pruning"""
coeffs = np . asarray ( chebcoeff ) if prune : N = self . _cutoff ( coeffs , vscale ) pruned_coeffs = coeffs [ : N ] else : pruned_coeffs = coeffs values = self . polyval ( pruned_coeffs ) return self ( values , domain , vscale )
def get_function_in_models ( service , operation ) : """refers to definition of API in botocore , and autogenerates function You can see example of elbv2 from link below . https : / / github . com / boto / botocore / blob / develop / botocore / data / elbv2/2015-12-01 / service - 2 . json"""
client = boto3 . client ( service ) aws_operation_name = to_upper_camel_case ( operation ) op_model = client . _service_model . operation_model ( aws_operation_name ) inputs = op_model . input_shape . members if not hasattr ( op_model . output_shape , 'members' ) : outputs = { } else : outputs = op_model . outp...
def _relative_to_abs_sls ( relative , sls ) : '''Convert ` ` relative ` ` sls reference into absolute , relative to ` ` sls ` ` .'''
levels , suffix = re . match ( r'^(\.+)(.*)$' , relative ) . groups ( ) level_count = len ( levels ) p_comps = sls . split ( '.' ) if level_count > len ( p_comps ) : raise SaltRenderError ( 'Attempted relative include goes beyond top level package' ) return '.' . join ( p_comps [ : - level_count ] + [ suffix ] )
def is_same ( type1 , type2 ) : """returns True , if type1 and type2 are same types"""
nake_type1 = remove_declarated ( type1 ) nake_type2 = remove_declarated ( type2 ) return nake_type1 == nake_type2
def monmap ( cluster , hostname ) : """Example usage : : > > > from ceph _ deploy . util . paths import mon > > > mon . monmap ( ' mycluster ' , ' myhostname ' ) / var / lib / ceph / tmp / mycluster . myhostname . monmap"""
monmap mon_map_file = '%s.%s.monmap' % ( cluster , hostname ) return join ( constants . tmp_path , mon_map_file )
def _get_pk_from_identity ( obj ) : """Copied / pasted , and fixed , from WTForms _ sqlalchemy due to issue w / SQLAlchemy > = 1.2."""
from sqlalchemy . orm . util import identity_key cls , key = identity_key ( instance = obj ) [ 0 : 2 ] return ":" . join ( text_type ( x ) for x in key )
def min ( self , spec ) : """Adds ` min ` operator that specifies lower bound for specific index . : Parameters : - ` spec ` : a list of field , limit pairs specifying the inclusive lower bound for all keys of a specific index in order . . . versionadded : : 2.7"""
if not isinstance ( spec , ( list , tuple ) ) : raise TypeError ( "spec must be an instance of list or tuple" ) self . __check_okay_to_chain ( ) self . __min = SON ( spec ) return self
def _set_auth_type ( self , v , load = False ) : """Setter method for auth _ type , mapped from YANG variable / routing _ system / interface / ve / ipv6 / ipv6 _ vrrp _ extended / auth _ type ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ auth _ type is c...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = auth_type . auth_type , is_container = 'container' , presence = False , yang_name = "auth-type" , rest_name = "auth-type" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths ...
def tablespace_list ( user = None , host = None , port = None , maintenance_db = None , password = None , runas = None ) : '''Return dictionary with information about tablespaces of a Postgres server . CLI Example : . . code - block : : bash salt ' * ' postgres . tablespace _ list . . versionadded : : 2015....
ret = { } query = ( 'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", ' 'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" ' 'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner' ) rows = __salt__ [ 'postgres.psql_query' ] ( query , runas = runas , host = host , user...
def dist_points ( bin_edges , d ) : """Return an array of values according to a distribution Points are calculated at the center of each bin"""
bc = bin_centers ( bin_edges ) if d is not None : d = DISTS [ d [ 'type' ] ] ( d , bc ) return d , bc
def update ( self ) : """Update hook"""
super ( AnalysisRequestAnalysesView , self ) . update ( ) analyses = self . context . getAnalyses ( full_objects = True ) self . analyses = dict ( [ ( a . getServiceUID ( ) , a ) for a in analyses ] ) self . selected = self . analyses . keys ( )
def invalidation_hash ( self , fingerprint_strategy = None ) : """: API : public"""
fingerprint_strategy = fingerprint_strategy or DefaultFingerprintStrategy ( ) if fingerprint_strategy not in self . _cached_fingerprint_map : self . _cached_fingerprint_map [ fingerprint_strategy ] = self . compute_invalidation_hash ( fingerprint_strategy ) return self . _cached_fingerprint_map [ fingerprint_strate...
def clear_worker_output ( self ) : """Drops all of the worker output collections Args : None Returns : Nothing"""
self . data_store . clear_worker_output ( ) # Have the plugin manager reload all the plugins self . plugin_manager . load_all_plugins ( ) # Store information about commands and workbench self . _store_information ( )
async def get_real_ext_ip ( self ) : """Return real external IP address ."""
while self . _ip_hosts : try : timeout = aiohttp . ClientTimeout ( total = self . _timeout ) async with aiohttp . ClientSession ( timeout = timeout , loop = self . _loop ) as session , session . get ( self . _pop_random_ip_host ( ) ) as resp : ip = await resp . text ( ) except asynci...
def get_organization ( self , organization_id ) : """Get an organization for a given organization ID : param organization _ id : str : return : Organization"""
url = 'rest/servicedeskapi/organization/{}' . format ( organization_id ) return self . get ( url , headers = self . experimental_headers )
def collate_fonts_data ( fonts_data ) : """Collate individual fonts data into a single glyph data list ."""
glyphs = { } for family in fonts_data : for glyph in family : if glyph [ 'unicode' ] not in glyphs : glyphs [ glyph [ 'unicode' ] ] = glyph else : c = glyphs [ glyph [ 'unicode' ] ] [ 'contours' ] glyphs [ glyph [ 'unicode' ] ] [ 'contours' ] = c | glyph [ 'contou...
def _write ( self , frame ) : """Write a YubiKeyFrame to the USB HID . Includes polling for YubiKey readiness before each write ."""
for data in frame . to_feature_reports ( debug = self . debug ) : debug_str = None if self . debug : ( data , debug_str ) = data # first , we ensure the YubiKey will accept a write self . _waitfor_clear ( yubikey_defs . SLOT_WRITE_FLAG ) self . _raw_write ( data , debug_str ) return True
def str_to_datetime ( ts ) : """Format a string to a datetime object . This functions supports several date formats like YYYY - MM - DD , MM - DD - YYYY , YY - MM - DD , YYYY - MM - DD HH : mm : SS + HH : MM , among others . When the timezone is not provided , UTC + 0 will be set as default ( using ` dateut...
def parse_datetime ( ts ) : dt = dateutil . parser . parse ( ts ) if not dt . tzinfo : dt = dt . replace ( tzinfo = dateutil . tz . tzutc ( ) ) return dt if not ts : raise InvalidDateError ( date = str ( ts ) ) try : # Try to remove additional information after # timezone section because it cann...
def construct_stone_pile ( levels : int ) -> list : """Constructs a pyramid of stones where the number of stones on each level is determined by a rule . If the total number of levels is odd , the number of stones on the next level is the next odd number . If the total number of levels is even , the next level c...
return [ levels + 2 * i for i in range ( levels ) ]
def forwards ( self , orm ) : "Write your forwards methods here ."
PERM_CONF = { "publish_content" : "Can publish content" , "publish_own_content" : "Can publish own content" , "change_content" : "Can change content" , "promote_content" : "Can promote content" } GROUP_CONF = dict ( contributor = ( ) , author = ( "publish_own_content" , ) , editor = ( "publish_content" , "change_conten...
def is_valid_interval ( self , lower , upper ) : """Return False if [ lower : upper ] is not a valid subitems interval . If it is , then returns a tuple of ( lower index , upper index )"""
try : lower_idx = self . data . index ( lower ) upper_idx = self . data . index ( upper ) return ( lower_idx , upper_idx ) if lower_idx <= upper_idx else False except ValueError : return False
def remove_move ( name ) : """Remove item from six . moves ."""
try : delattr ( _MovedItems , name ) except AttributeError : try : del moves . __dict__ [ name ] except KeyError : raise AttributeError ( "no such move, %r" % ( name , ) )
def logout ( self ) : """Log out of the account ."""
self . _master_token = None self . _auth_token = None self . _email = None self . _android_id = None
def publish_workflow_submission ( self , user_id , workflow_id_or_name , parameters ) : """Publish workflow submission parameters ."""
msg = { "user" : user_id , "workflow_id_or_name" : workflow_id_or_name , "parameters" : parameters } self . _publish ( msg )
def transform_returns ( self , raw_lines , tre_return_grammar = None , use_mock = None , is_async = False ) : """Apply TCO , TRE , or async universalization to the given function ."""
lines = [ ] # transformed lines tco = False # whether tco was done tre = False # whether tre was done level = 0 # indentation level disabled_until_level = None # whether inside of a disabled block attempt_tre = tre_return_grammar is not None # whether to even attempt tre attempt_tco = not is_async and not self . no_tco...
def predefinedEntity ( name ) : """Check whether this name is an predefined entity ."""
ret = libxml2mod . xmlGetPredefinedEntity ( name ) if ret is None : raise treeError ( 'xmlGetPredefinedEntity() failed' ) return xmlEntity ( _obj = ret )
def load ( source , ** kwargs ) -> JsonObj : """Deserialize a JSON source . : param source : a URI , File name or a . read ( ) - supporting file - like object containing a JSON document : param kwargs : arguments . see : json . load for details : return : JsonObj representing fp"""
if isinstance ( source , str ) : if '://' in source : req = Request ( source ) req . add_header ( "Accept" , "application/json, text/json;q=0.9" ) with urlopen ( req ) as response : jsons = response . read ( ) else : with open ( source ) as f : jsons = f ....
def untlpy2dcpy ( untl_elements , ** kwargs ) : """Convert the UNTL elements structure into a DC structure . kwargs can be passed to the function for certain effects : ark : Takes an ark string and creates an identifier element out of it . domain _ name : Takes a domain string and creates an ark URL from it ...
sDate = None eDate = None ark = kwargs . get ( 'ark' , None ) domain_name = kwargs . get ( 'domain_name' , None ) scheme = kwargs . get ( 'scheme' , 'http' ) resolve_values = kwargs . get ( 'resolve_values' , None ) resolve_urls = kwargs . get ( 'resolve_urls' , None ) verbose_vocabularies = kwargs . get ( 'verbose_voc...
def getCell ( self , row , width = None ) : 'Return DisplayWrapper for displayable cell value .'
cellval = wrapply ( self . getValue , row ) typedval = wrapply ( self . type , cellval ) if isinstance ( typedval , TypedWrapper ) : if isinstance ( cellval , TypedExceptionWrapper ) : # calc failed exc = cellval . exception if cellval . forwarded : dispval = str ( cellval ) ...
def shutdown ( self ) : """shutdown"""
self . debug_log ( 'shutdown - start' ) # Only initiate shutdown once if not self . shutdown_now : self . debug_log ( 'shutdown - still shutting down' ) # Cancels the scheduled Timer , allows exit immediately if self . timer : self . timer . cancel ( ) self . timer = None return else : ...
def reload_component ( self , name ) : """Reloads given Component . : param name : Component name . : type name : unicode : return : Method success . : rtype : bool"""
if not name in self . __engine . components_manager . components : raise manager . exceptions . ComponentExistsError ( "{0} | '{1}' Component isn't registered in the Components Manager!" . format ( self . __class__ . __name__ , name ) ) component = self . __engine . components_manager . components [ name ] LOGGER ....
def update ( self , updatePortalParameters , clearEmptyFields = False ) : """The Update operation allows administrators only to update the organization information such as name , description , thumbnail , and featured groups . Inputs : updatePortalParamters - parameter . PortalParameters object that holds i...
url = self . root + "/update" params = { "f" : "json" , "clearEmptyFields" : clearEmptyFields } if isinstance ( updatePortalParameters , parameters . PortalParameters ) : params . update ( updatePortalParameters . value ) elif isinstance ( updatePortalParameters , dict ) : for k , v in updatePortalParameters . ...
def spop ( self , key , count = None , * , encoding = _NOTSET ) : """Remove and return one or multiple random members from a set ."""
args = [ key ] if count is not None : args . append ( count ) return self . execute ( b'SPOP' , * args , encoding = encoding )
def create_reaction ( self , reaction_type ) : """: calls : ` POST / repos / : owner / : repo / issues / : number / reactions < https : / / developer . github . com / v3 / reactions > ` _ : param reaction _ type : string : rtype : : class : ` github . Reaction . Reaction `"""
assert isinstance ( reaction_type , ( str , unicode ) ) , "reaction type should be a string" assert reaction_type in [ "+1" , "-1" , "laugh" , "confused" , "heart" , "hooray" ] , "Invalid reaction type (https://developer.github.com/v3/reactions/#reaction-types)" post_parameters = { "content" : reaction_type , } headers...
def put ( self , item : T , context : PipelineContext = None ) -> None : """Puts an objects into the data sink . The objects may be transformed into a new type for insertion if necessary . Args : item : The objects to be inserted into the data sink . context : The context of the insertion ( mutable ) ."""
LOGGER . info ( "Converting item \"{item}\" for sink \"{sink}\"" . format ( item = item , sink = self . _sink ) ) item = self . _transform ( data = item , context = context ) LOGGER . info ( "Puting item \"{item}\" into sink \"{sink}\"" . format ( item = item , sink = self . _sink ) ) self . _sink . put ( self . _store...
def save_model ( self , request , obj , form , change ) : '''Our custom addition to the view adds an easy radio button choice for the new state . This is meant to be for tutors . We need to peel this choice from the form data and set the state accordingly . The radio buttons have no default , so that we can k...
if 'newstate' in request . POST : if request . POST [ 'newstate' ] == 'finished' : obj . state = Submission . GRADED elif request . POST [ 'newstate' ] == 'unfinished' : obj . state = Submission . GRADING_IN_PROGRESS obj . save ( )
def logstr ( self ) : """handler the log records to formatted string"""
result = [ ] formater = LogFormatter ( color = False ) for record in self . logs : if isinstance ( record , six . string_types ) : result . append ( pretty_unicode ( record ) ) else : if record . exc_info : a , b , tb = record . exc_info tb = hide_me ( tb , globals ( ) ) ...
def replace_requirements ( self , infilename , outfile_initial = None ) : """Recursively replaces the requirements in the files with the content of the requirements . Returns final temporary file opened for reading ."""
infile = open ( infilename , 'r' ) # extract the requirements for this file that were not skipped from the global database _indexes = tuple ( z [ 0 ] for z in filter ( lambda x : x [ 1 ] == infilename , enumerate ( self . req_parents ) ) ) req_paths = tuple ( z [ 1 ] for z in filter ( lambda x : x [ 0 ] in _indexes , e...
def handle_session_cookie ( self ) : """Handle JSESSIONID cookie logic"""
# If JSESSIONID support is disabled in the settings , ignore cookie logic if not self . server . settings [ 'jsessionid' ] : return cookie = self . cookies . get ( 'JSESSIONID' ) if not cookie : cv = 'dummy' else : cv = cookie . value self . set_cookie ( 'JSESSIONID' , cv )
def announce_urls ( self , default = [ ] ) : # pylint : disable = dangerous - default - value """Get a list of all announce URLs . Returns ` default ` if no trackers are found at all ."""
try : response = self . _engine . _rpc . t . multicall ( self . _fields [ "hash" ] , 0 , "t.url=" , "t.is_enabled=" ) except xmlrpc . ERRORS as exc : raise error . EngineError ( "While getting announce URLs for #%s: %s" % ( self . _fields [ "hash" ] , exc ) ) if response : return [ i [ 0 ] for i in response...
def query_ec_number ( ) : """Returns list of Enzyme Commission Numbers ( EC numbers ) by query parameters tags : - Query functions parameters : - name : ec _ number in : query type : string required : false description : Enzyme Commission Number default : ' 1.1.1.1' - name : entry _ name in : ...
args = get_args ( request_args = request . args , allowed_str_args = [ 'ec_number' , 'entry_name' ] , allowed_int_args = [ 'limit' ] ) return jsonify ( query . ec_number ( ** args ) )
def copy ( self ) : """Convert ` ` Dictator ` ` to standard ` ` dict ` ` object > > > dc = Dictator ( ) > > > dc [ ' l0 ' ] = [ 1 , 2] > > > dc [ ' 1 ' ] = ' abc ' > > > d = dc . copy ( ) > > > type ( d ) dict { ' l0 ' : [ ' 1 ' , ' 2 ' ] , ' 1 ' : ' abc ' } > > > dc . clear ( ) : return : Python ...
logger . debug ( 'call to_dict' ) return { key : self . get ( key ) for key in self . keys ( ) }
def _load ( self , url , verbose ) : """Execute a request against the Salesking API to fetch the items : param url : url to fetch : return response : raises SaleskingException with the corresponding http errors"""
msg = u"_load url: %s" % url self . _last_query_str = url log . debug ( msg ) if verbose : print msg response = self . __api__ . request ( url ) return response
def check ( self , url_data ) : """Try to ask GeoIP database for country info ."""
data = url_data . get_content ( ) infected , errors = scan ( data , self . clamav_conf ) if infected or errors : for msg in infected : url_data . add_warning ( u"Virus scan infection: %s" % msg ) for msg in errors : url_data . add_warning ( u"Virus scan error: %s" % msg ) else : url_data . a...
def isom ( self , coolingFactor = None , EdgeAttribute = None , initialAdaptation = None , maxEpoch = None , minAdaptation = None , minRadius = None , network = None , NodeAttribute = None , nodeList = None , radius = None , radiusConstantTime = None , singlePartition = None , sizeFactor = None , verbose = None ) : ...
network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ 'coolingFactor' , 'EdgeAttribute' , 'initialAdaptation' , 'maxEpoch' , 'minAdaptation' , 'minRadius' , 'network' , 'NodeAttribute' , 'nodeList' , 'radius' , 'radiusConstantTime' , 'singlePartition' , 'sizeFactor' ] , [ coolingFactor ,...
def uppass ( tree , feature ) : """UPPASS traverses the tree starting from the tips and going up till the root , and assigns to each parent node a state based on the states of its child nodes . if N is a tip : S ( N ) < - state of N else : L , R < - left and right children of N UPPASS ( L ) UPPASS ( R...
ps_feature = get_personalized_feature_name ( feature , BU_PARS_STATES ) for node in tree . traverse ( 'postorder' ) : if not node . is_leaf ( ) : children_states = get_most_common_states ( getattr ( child , ps_feature ) for child in node . children ) node_states = getattr ( node , ps_feature ) ...
def from_array ( name , array , dim_names = None ) : """Construct a LIGO Light Weight XML Array document subtree from a numpy array object . Example : > > > import numpy , sys > > > a = numpy . arange ( 12 , dtype = " double " ) > > > a . shape = ( 4 , 3) > > > from _ array ( u " test " , a ) . write ( ...
# Type must be set for . _ _ init _ _ ( ) ; easier to set Name afterwards # to take advantage of encoding handled by attribute proxy doc = Array ( Attributes ( { u"Type" : ligolwtypes . FromNumPyType [ str ( array . dtype ) ] } ) ) doc . Name = name for n , dim in enumerate ( reversed ( array . shape ) ) : child = ...
def query ( self , query , * args , ** kwargs ) : """Run a statement on the database directly . Allows for the execution of arbitrary read / write queries . A query can either be a plain text string , or a ` SQLAlchemy expression < http : / / docs . sqlalchemy . org / en / latest / core / tutorial . html # se...
if isinstance ( query , six . string_types ) : query = text ( query ) _step = kwargs . pop ( '_step' , QUERY_STEP ) rp = self . executable . execute ( query , * args , ** kwargs ) return ResultIter ( rp , row_type = self . row_type , step = _step )
def useradd ( pwfile , user , password , opts = '' , runas = None ) : '''Add a user to htpasswd file using the htpasswd command . If the htpasswd file does not exist , it will be created . pwfile Path to htpasswd file user User name password User password opts Valid options that can be passed are ...
if not os . path . exists ( pwfile ) : opts += 'c' cmd = [ 'htpasswd' , '-b{0}' . format ( opts ) , pwfile , user , password ] return __salt__ [ 'cmd.run_all' ] ( cmd , runas = runas , python_shell = False )
def generate_from_text ( self , text ) : """Generate wordcloud from text . The input " text " is expected to be a natural text . If you pass a sorted list of words , words will appear in your output twice . To remove this duplication , set ` ` collocations = False ` ` . Calls process _ text and generate _ f...
words = self . process_text ( text ) self . generate_from_frequencies ( words ) return self
def get_view_nodes_from_indexes ( self , * indexes ) : """Returns the View Nodes from given indexes . : param view : View . : type view : QWidget : param \ * indexes : Indexes . : type \ * indexes : list : return : View nodes . : rtype : dict"""
nodes = { } model = self . model ( ) if not model : return nodes if not hasattr ( model , "get_node" ) : raise NotImplementedError ( "{0} | '{1}' Model doesn't implement a 'get_node' method!" . format ( __name__ , model ) ) if not hasattr ( model , "get_attribute" ) : raise NotImplementedError ( "{0} | '{1}...
def request_announcement_view ( request ) : """The request announcement page ."""
if request . method == "POST" : form = AnnouncementRequestForm ( request . POST ) logger . debug ( form ) logger . debug ( form . data ) if form . is_valid ( ) : teacher_objs = form . cleaned_data [ "teachers_requested" ] logger . debug ( "teacher objs:" ) logger . debug ( teache...
def canonical_chimera_labeling ( G , t = None ) : """Returns a mapping from the labels of G to chimera - indexed labeling . Parameters G : NetworkX graph A Chimera - structured graph . t : int ( optional , default 4) Size of the shore within each Chimera tile . Returns chimera _ indices : dict A map...
adj = G . adj if t is None : if hasattr ( G , 'edges' ) : num_edges = len ( G . edges ) else : num_edges = len ( G . quadratic ) t = _chimera_shore_size ( adj , num_edges ) chimera_indices = { } row = col = 0 root = min ( adj , key = lambda v : len ( adj [ v ] ) ) horiz , verti = rooted_tile...
def get_download_url ( self , proapi = False ) : """Get this file ' s download URL : param bool proapi : whether to use pro API"""
if self . _download_url is None : self . _download_url = self . api . _req_files_download_url ( self . pickcode , proapi ) return self . _download_url
def unify_partitions ( self ) : """For all of the segments for a partition , create the parent partition , combine the children into the parent , and delete the children ."""
partitions = self . collect_segment_partitions ( ) # For each group , copy the segment partitions to the parent partitions , then # delete the segment partitions . with self . progress . start ( 'coalesce' , 0 , message = 'Coalescing partition segments' ) as ps : for name , segments in iteritems ( partitions ) : ...
def set_input ( self , filename , pass_to_command_line = True ) : """Add an input to the node by adding a - - input option . @ param filename : option argument to pass as input . @ bool pass _ to _ command _ line : add input as a variable option ."""
self . __input = filename if pass_to_command_line : self . add_var_opt ( 'input' , filename ) self . add_input_file ( filename )
def extract_message_value ( self , name ) : '''search message to find and extract a named value'''
name += ":" assert ( self . _message ) _start = self . _message . find ( name ) if _start >= 0 : _start += len ( name ) + 1 _end = self . _message . find ( "\n" , _start ) _value = self . _message [ _start : _end ] return _value . strip ( ) return None