signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def attention_bias_ignore_padding ( memory_padding ) : """Create an bias tensor to be added to attention logits . Args : memory _ padding : a float ` Tensor ` with shape [ batch , memory _ length ] . Returns : a ` Tensor ` with shape [ batch , 1 , 1 , memory _ length ] ."""
ret = memory_padding * large_compatible_negative ( memory_padding . dtype ) return tf . expand_dims ( tf . expand_dims ( ret , axis = 1 ) , axis = 1 )
def callsigns ( self ) -> Set [ str ] : """Return only the most relevant callsigns"""
sub = self . data . query ( "callsign == callsign" ) return set ( cs for cs in sub . callsign if len ( cs ) > 3 and " " not in cs )
def _get ( self , node , key ) : """get value inside a node : param node : node in form of list , or BLANK _ NODE : param key : nibble list without terminator : return : BLANK _ NODE if does not exist , otherwise value or hash"""
node_type = self . _get_node_type ( node ) if node_type == NODE_TYPE_BLANK : return BLANK_NODE if node_type == NODE_TYPE_BRANCH : # already reach the expected node if not key : return node [ - 1 ] sub_node = self . _decode_to_node ( node [ key [ 0 ] ] ) return self . _get ( sub_node , key [ 1 : ...
def codes_write ( handle , outfile ) : # type : ( cffi . FFI . CData , T . BinaryIO ) - > None """Write a coded message to a file . If the file does not exist , it is created . : param str path : ( optional ) the path to the GRIB file ; defaults to the one of the open index ."""
mess = ffi . new ( 'const void **' ) mess_len = ffi . new ( 'size_t*' ) codes_get_message = check_return ( lib . codes_get_message ) codes_get_message ( handle , mess , mess_len ) message = ffi . buffer ( mess [ 0 ] , size = mess_len [ 0 ] ) outfile . write ( message )
def decode_int ( tag , bits_per_char = 6 ) : """Decode string into int assuming encoding with ` encode _ int ( ) ` It is using 2 , 4 or 6 bits per coding character ( default 6 ) . Parameters : tag : str Encoded integer . bits _ per _ char : int The number of bits per coding character . Returns : int : t...
if bits_per_char == 6 : return _decode_int64 ( tag ) if bits_per_char == 4 : return _decode_int16 ( tag ) if bits_per_char == 2 : return _decode_int4 ( tag ) raise ValueError ( '`bits_per_char` must be in {6, 4, 2}' )
def cget ( self , key ) : """Query widget option . : param key : option name : type key : str : return : value of the option To get the list of options for this widget , call the method : meth : ` ~ Balloon . keys ` ."""
if key == "headertext" : return self . __headertext elif key == "text" : return self . __text elif key == "width" : return self . __width elif key == "timeout" : return self . _timeout elif key == "background" : return self . __background else : return ttk . Frame . cget ( self , key )
def get_homogenous_list_type ( list_ ) : """Returns the best matching python type even if it is an ndarray assumes all items in the list are of the same type . does not check this"""
# TODO Expand and make work correctly if HAVE_NUMPY and isinstance ( list_ , np . ndarray ) : item = list_ elif isinstance ( list_ , list ) and len ( list_ ) > 0 : item = list_ [ 0 ] else : item = None if item is not None : if is_float ( item ) : type_ = float elif is_int ( item ) : ...
def handle_input ( self ) : """Sends differences in the device state to the MicroBitPad as events ."""
difference = self . check_state ( ) if not difference : return self . events = [ ] self . handle_new_events ( difference ) self . update_timeval ( ) self . events . append ( self . sync_marker ( self . timeval ) ) self . write_to_pipe ( self . events )
def get_bundles ( ) : """Used to cache the bundle definitions rather than loading from config every time they ' re used"""
global _cached_bundles if not _cached_bundles : _cached_bundles = BundleManager ( ) for bundle_conf in bundles_settings . BUNDLES : _cached_bundles [ bundle_conf [ 0 ] ] = Bundle ( bundle_conf ) return _cached_bundles
def project ( X , Z , use_jit = False , debug = False ) : """Project tensor Z on the tangent space of tensor X . X is a tensor in the TT format . Z can be a tensor in the TT format or a list of tensors ( in this case the function computes projection of the sum off all tensors in the list : project ( X , Z )...
zArr = None if isinstance ( Z , tt . vector ) : zArr = [ Z ] else : zArr = Z # Get rid of redundant ranks ( they cause technical difficulties ) . X = X . round ( eps = 0 ) numDims , modeSize = X . d , X . n coresX = tt . tensor . to_list ( X ) coresZ = [ None ] * len ( zArr ) for idx in xrange ( len ( zArr ) ) ...
def manage ( settingspath , root_dir , argv ) : """Manage all processes"""
# add settings . json to environment variables os . environ [ ENV_VAR_SETTINGS ] = settingspath # add root _ dir os . environ [ ENV_VAR_ROOT_DIR ] = root_dir # get datasets list with open ( settingspath ) as settings_file : settings = json . load ( settings_file ) # manage args datasets_list = generate_datasets_lis...
def _simple_response_to_error_adapter ( self , status , original_body ) : """Convert a single error response ."""
body = original_body . copy ( ) code = body . pop ( 'code' ) title = body . pop ( 'message' ) meta = body # save whatever is left in the response e = [ ErrorDetails ( status , code , title ) ] return e , meta
def visit_shapes ( self , expr : ShExJ . shapeExpr , f : Callable [ [ Any , ShExJ . shapeExpr , "Context" ] , None ] , arg_cntxt : Any , visit_center : _VisitorCenter = None , follow_inner_shapes : bool = True ) -> None : """Visit expr and all of its " descendant " shapes . : param expr : root shape expression ...
if visit_center is None : visit_center = _VisitorCenter ( f , arg_cntxt ) has_id = getattr ( expr , 'id' , None ) is not None if not has_id or not ( visit_center . already_seen_shape ( expr . id ) or visit_center . actively_visiting_shape ( expr . id ) ) : # Visit the root expression if has_id : visit_c...
def convert ( self , expr ) : """Override Backend . convert ( ) to add fast paths for BVVs and BoolVs ."""
if type ( expr ) is BV : if expr . op == "BVV" : cached_obj = self . _object_cache . get ( expr . _cache_key , None ) if cached_obj is None : cached_obj = self . BVV ( * expr . args ) self . _object_cache [ expr . _cache_key ] = cached_obj return cached_obj if type ( ...
def formfield_for_dbfield ( self , db_field , ** kwargs ) : """Override the default widget for Foreignkey fields if they are specified in the related _ search _ fields class attribute ."""
if isinstance ( db_field , models . ForeignKey ) and db_field . name in self . related_search_fields : help_text = self . get_help_text ( db_field . name , db_field . remote_field . model . _meta . object_name ) if kwargs . get ( 'help_text' ) : help_text = six . u ( '%s %s' % ( kwargs [ 'help_text' ] ,...
def build ( self , start , end , symbols = None ) : """Return the list of basic blocks . : int start : Start address of the disassembling process . : int end : End address of the disassembling process ."""
symbols = { } if not symbols else symbols # First pass : Recover BBs . bbs = self . _recover_bbs ( start , end , symbols ) # Second pass : Split overlapping basic blocks introduced by back edges . bbs = self . _split_bbs ( bbs , symbols ) # Third pass : Extract call targets for further analysis . call_targets = self . ...
def leaves_are_consistent ( self ) : """Return ` ` True ` ` if the sync map fragments which are the leaves of the sync map tree ( except for HEAD and TAIL leaves ) are all consistent , that is , their intervals do not overlap in forbidden ways . : rtype : bool . . versionadded : : 1.7.0"""
self . log ( u"Checking if leaves are consistent" ) leaves = self . leaves ( ) if len ( leaves ) < 1 : self . log ( u"Empty leaves => return True" ) return True min_time = min ( [ l . interval . begin for l in leaves ] ) self . log ( [ u" Min time: %.3f" , min_time ] ) max_time = max ( [ l . interval . end for...
def pip_upgrade_all ( line ) : """Attempt to upgrade all packages"""
from pip import get_installed_distributions user = set ( d . project_name for d in get_installed_distributions ( user_only = True ) ) all = set ( d . project_name for d in get_installed_distributions ( ) ) for dist in all - user : do_pip ( [ "install" , "--upgrade" , dist ] ) for dist in user : do_pip ( [ "inst...
def _receive_message ( self ) : """Internal coroutine for receiving messages"""
while True : try : if self . _socket . getsockopt ( zmq . TYPE ) == zmq . ROUTER : zmq_identity , msg_bytes = yield from self . _socket . recv_multipart ( ) if msg_bytes == b'' : # send ACK for connection probes LOGGER . debug ( "ROUTER PROBE FROM %s" , zmq_identity )...
def print_multi_line ( content , force_single_line , sort_key ) : """' sort _ key ' 参数只在 dict 模式时有效 ' sort _ key ' parameter only available in ' dict ' mode"""
global last_output_lines global overflow_flag global is_atty if not is_atty : if isinstance ( content , list ) : for line in content : print ( line ) elif isinstance ( content , dict ) : for k , v in sorted ( content . items ( ) , key = sort_key ) : print ( "{}: {}" . for...
def get_document_field_display ( self , field_name , field ) : """Render a link to a document"""
document = getattr ( self . instance , field_name ) if document : return mark_safe ( '<a href="%s">%s <span class="meta">(%s, %s)</span></a>' % ( document . url , document . title , document . file_extension . upper ( ) , filesizeformat ( document . file . size ) , ) ) return self . model_admin . get_empty_value_di...
def check_roles ( self , account , aws_policies , aws_roles ) : """Iterate through the roles of a specific account and create or update the roles if they ' re missing or does not match the roles from Git . Args : account ( : obj : ` Account ` ) : The account to check roles on aws _ policies ( : obj : ` dict...
self . log . debug ( 'Checking roles for {}' . format ( account . account_name ) ) max_session_duration = self . dbconfig . get ( 'role_timeout_in_hours' , self . ns , 8 ) * 60 * 60 sess = get_aws_session ( account ) iam = sess . client ( 'iam' ) # Build a list of default role policies and extra account specific role p...
def reduce_by_device ( parallelism , data , reduce_fn ) : """Reduces data per device . This can be useful , for example , if we want to all - reduce n tensors on k < n devices ( like during eval when we have only one device ) . We call reduce _ by _ device ( ) to first sum the tensors per device , then call o...
unique_devices = [ ] device_to_data = { } for dev , datum in zip ( parallelism . devices , data ) : if dev not in device_to_data : unique_devices . append ( dev ) device_to_data [ dev ] = [ datum ] else : device_to_data [ dev ] . append ( datum ) device_parallelism = Parallelism ( unique...
def line_intersection_2D ( abarg , cdarg ) : '''line _ intersection ( ( a , b ) , ( c , d ) ) yields the intersection point between the lines that pass through the given pairs of points . If any lines are parallel , ( numpy . nan , numpy . nan ) is returned ; note that a , b , c , and d can all be 2 x n matrice...
( ( x1 , y1 ) , ( x2 , y2 ) ) = abarg ( ( x3 , y3 ) , ( x4 , y4 ) ) = cdarg dx12 = ( x1 - x2 ) dx34 = ( x3 - x4 ) dy12 = ( y1 - y2 ) dy34 = ( y3 - y4 ) denom = dx12 * dy34 - dy12 * dx34 unit = np . isclose ( denom , 0 ) if unit is True : return ( np . nan , np . nan ) denom = unit + denom q12 = ( x1 * y2 - y1 * x2 ...
def use_federated_book_view ( self ) : """Pass through to provider CommentLookupSession . use _ federated _ book _ view"""
self . _book_view = FEDERATED # self . _ get _ provider _ session ( ' comment _ lookup _ session ' ) # To make sure the session is tracked for session in self . _get_provider_sessions ( ) : try : session . use_federated_book_view ( ) except AttributeError : pass
def _get_site_term ( self , C , vs30 ) : """Returns only a linear site amplification term"""
dg1 , dg2 = self . _get_regional_site_term ( C ) return ( C [ "g1" ] + dg1 ) + ( C [ "g2" ] + dg2 ) * np . log ( vs30 )
def _get_ensemble_bed_files ( items ) : """get all ensemble structural BED file calls , skipping any normal samples from tumor / normal calls"""
bed_files = [ ] for data in items : for sv in data . get ( "sv" , [ ] ) : if sv [ "variantcaller" ] == "sv-ensemble" : if ( "vrn_file" in sv and not vcfutils . get_paired_phenotype ( data ) == "normal" and file_exists ( sv [ "vrn_file" ] ) ) : bed_files . append ( sv [ "vrn_file"...
def draw_uppercase_key ( self , surface , key ) : """Default drawing method for uppercase key . Drawn as character key . : param surface : Surface background should be drawn in . : param key : Target key to be drawn ."""
key . value = u'\u21e7' if key . is_activated ( ) : key . value = u'\u21ea' self . draw_character_key ( surface , key , True )
def rename ( self , channel_name , new_name ) : """https : / / api . slack . com / methods / channels . rename"""
channel_id = self . get_channel_id ( channel_name ) self . params . update ( { 'channel' : channel_id , 'name' : new_name , } ) return FromUrl ( 'https://slack.com/api/channels.rename' , self . _requests ) ( data = self . params ) . post ( )
def fixChromName ( name , orgn = "medicago" ) : """Convert quirky chromosome names encountered in different release files , which are very project specific , into a more general format . For example , in Medicago Convert a seqid like ` Mt3.5.1 _ Chr1 ` to ` chr1 ` ` Mt3.5 _ Chr3 ` to ` chr3 ` ` chr01 ...
import re mtr_pat1 = re . compile ( r"Mt[0-9]+\.[0-9]+[\.[0-9]+]{0,}_([a-z]+[0-9]+)" ) mtr_pat2 = re . compile ( r"([A-z0-9]+)_[A-z]+_[A-z]+" ) zmays_pat = re . compile ( r"[a-z]+:[A-z0-9]+:([A-z0-9]+):[0-9]+:[0-9]+:[0-9]+" ) zmays_sub = { 'mitochondrion' : 'Mt' , 'chloroplast' : 'Pt' } if orgn == "medicago" : for ...
def _dump_to_pages ( dump ) : """Extract pages from an xml dump . Args : dump : a unicode string Returns : a list of unicode strings"""
pos = 0 ret = [ ] start_tag = u"<page>\n" end_tag = u"</page>\n" while True : start_pos = dump . find ( start_tag , pos ) if start_pos == - 1 : break start_pos += len ( start_tag ) end_pos = dump . find ( end_tag , start_pos ) if end_pos == - 1 : break ret . append ( dump [ start...
def goto_line ( self , line , column = 0 , move = True ) : """Moves the text cursor to the specified position . . : param line : Number of the line to go to ( 0 based ) : param column : Optional column number . Default is 0 ( start of line ) . : param move : True to move the cursor . False will return the cur...
text_cursor = self . move_cursor_to ( line ) if column : text_cursor . movePosition ( text_cursor . Right , text_cursor . MoveAnchor , column ) if move : block = text_cursor . block ( ) # unfold parent fold trigger if the block is collapsed try : folding_panel = self . _editor . panels . get ( '...
def findzc ( x , thresh , t_max = None ) : '''Find cues to each zero - crossing in vector x . To be accepted as a zero - crossing , the signal must pass from below - thresh to above thresh , or vice versa , in no more than t _ max samples . Args thresh : ( float ) magnitude threshold for detecting a zero ...
import numpy # positive threshold : p ( over ) n ( under ) pt_p = x > thresh pt_n = ~ pt_p # negative threshold : p ( over ) n ( under ) nt_n = x < - thresh nt_p = ~ nt_n # Over positive threshold + thresh # neg to pos pt_np = ( pt_p [ : - 1 ] & pt_n [ 1 : ] ) . nonzero ( ) [ 0 ] # pos to neg pt_pn = ( pt_n [ : - 1 ] &...
def get_cot_artifacts ( context ) : """Generate the artifact relative paths and shas for the chain of trust . Args : context ( scriptworker . context . Context ) : the scriptworker context . Returns : dict : a dictionary of { " path / to / artifact " : { " hash _ alg " : " . . . " } , . . . }"""
artifacts = { } filepaths = filepaths_in_dir ( context . config [ 'artifact_dir' ] ) hash_alg = context . config [ 'chain_of_trust_hash_algorithm' ] for filepath in sorted ( filepaths ) : path = os . path . join ( context . config [ 'artifact_dir' ] , filepath ) sha = get_hash ( path , hash_alg = hash_alg ) ...
def IntegerDifference ( left : vertex_constructor_param_types , right : vertex_constructor_param_types , label : Optional [ str ] = None ) -> Vertex : """Subtracts one vertex from another : param left : the vertex to be subtracted from : param right : the vertex to subtract"""
return Integer ( context . jvm_view ( ) . IntegerDifferenceVertex , label , cast_to_integer_vertex ( left ) , cast_to_integer_vertex ( right ) )
def clean_recipe_build ( self , args ) : """Deletes the build files of the given recipe . This is intended for debug purposes . You may experience strange behaviour or problems with some recipes if their build has made unexpected state changes . If this happens , run clean _ builds , or attempt to clean oth...
recipe = Recipe . get_recipe ( args . recipe , self . ctx ) info ( 'Cleaning build for {} recipe.' . format ( recipe . name ) ) recipe . clean_build ( ) if not args . no_clean_dists : self . clean_dists ( args )
def execute_command ( self , parts , dry_run ) : """Execute a command . Parameters parts : list Sequence of strings constituting a command . dry _ run : bool Whether to just log the command instead of executing it . Returns status : int Status code of the executed command or 0 if ` dry _ run ` is ` ...
if dry_run : self . logger . info ( "dry-run command '%s'" , " " . join ( map ( str , parts ) ) ) return 0 else : # pragma : no cover self . logger . debug ( "executing command '%s'" , " " . join ( map ( str , parts ) ) ) status_code = os . spawnvpe ( os . P_WAIT , parts [ 0 ] , parts , os . environ ) ...
def MAKE_WPARAM ( wParam ) : """Convert arguments to the WPARAM type . Used automatically by SendMessage , PostMessage , etc . You shouldn ' t need to call this function ."""
wParam = ctypes . cast ( wParam , LPVOID ) . value if wParam is None : wParam = 0 return wParam
def hours_estimate ( self , branch = 'master' , grouping_window = 0.5 , single_commit_hours = 0.5 , limit = None , days = None , committer = True , by = None , ignore_globs = None , include_globs = None ) : """inspired by : https : / / github . com / kimmobrunfeldt / git - hours / blob / 8aaeee237cb9d9028e7a2592a25...
if limit is not None : limit = int ( limit / len ( self . repo_dirs ) ) if committer : com = 'committer' else : com = 'author' df = pd . DataFrame ( columns = [ com , 'hours' , 'repository' ] ) for repo in self . repos : try : ch = repo . hours_estimate ( branch , grouping_window = grouping_wind...
def get_fc2 ( supercell , symmetry , dataset , atom_list = None , decimals = None ) : """Force constants are computed . Force constants , Phi , are calculated from sets for forces , F , and atomic displacement , d : Phi = - F / d This is solved by matrix pseudo - inversion . Crystal symmetry is included w...
if atom_list is None : fc_dim0 = supercell . get_number_of_atoms ( ) else : fc_dim0 = len ( atom_list ) force_constants = np . zeros ( ( fc_dim0 , supercell . get_number_of_atoms ( ) , 3 , 3 ) , dtype = 'double' , order = 'C' ) # Fill force _ constants [ displaced _ atoms , all _ atoms _ in _ supercell ] atom_l...
def start_standing_subprocess ( cmd , shell = False , env = None ) : """Starts a long - running subprocess . This is not a blocking call and the subprocess started by it should be explicitly terminated with stop _ standing _ subprocess . For short - running commands , you should use subprocess . check _ call ...
logging . debug ( 'Starting standing subprocess with: %s' , cmd ) proc = subprocess . Popen ( cmd , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . PIPE , shell = shell , env = env ) # Leaving stdin open causes problems for input , e . g . breaking the # code . inspect ( ) shell ( http : ...
def p_enum_constant ( t ) : """enum _ constant : ID EQUALS value"""
global name_dict , error_occurred id = t [ 1 ] value = t [ 3 ] lineno = t . lineno ( 1 ) if id_unique ( id , 'enum' , lineno ) : info = name_dict [ id ] = const_info ( id , value , lineno , enum = True ) if not ( value [ 0 ] . isdigit ( ) or value [ 0 ] == '-' ) : # We have a name instead of a constant , make s...
def send_durable_exchange_message ( self , exchange_name , body ) : """Send a message with the specified body to an exchange . : param exchange _ name : str : name of the exchange to send the message into : param body : str : contents of the message : return Bool : True when delivery confirmed"""
self . connect ( ) channel = self . connection . channel ( ) # Fanout will send message to multiple subscribers channel . exchange_declare ( exchange = exchange_name , type = 'fanout' ) result = channel . basic_publish ( exchange = exchange_name , routing_key = '' , body = body , properties = pika . BasicProperties ( d...
def value_validate ( self , value ) : """Converts the input single value into the expected Python data type , raising django . core . exceptions . ValidationError if the data can ' t be converted . Returns the converted value . Subclasses should override this ."""
if not isinstance ( value , six . integer_types ) : raise tldap . exceptions . ValidationError ( "should be a integer" ) try : return str ( value ) except ( TypeError , ValueError ) : raise tldap . exceptions . ValidationError ( "is invalid integer" )
def _catalog_check ( self , cat_name , append = False ) : """Check to see if the name of the ingested catalog is valid Parameters cat _ name : str The name of the catalog in the Catalog object append : bool Append the catalog rather than replace Returns bool True if good catalog name else False"""
good = True # Make sure the attribute name is good if cat_name [ 0 ] . isdigit ( ) : print ( "No names beginning with numbers please!" ) good = False # Make sure catalog is unique if not append and cat_name in self . catalogs : print ( "Catalog {} already ingested. Set 'append=True' to add more records." . ...
def compile_mof_string ( self , mof_str , namespace = None , search_paths = None , verbose = None ) : """Compile the MOF definitions in the specified string and add the resulting CIM objects to the specified CIM namespace of the mock repository . If the namespace does not exist , : exc : ` ~ pywbem . CIMError...
namespace = namespace or self . default_namespace # if not self . _ validate _ namespace ( namespace ) : TODO # self . add _ namespace ( namespace ) self . _validate_namespace ( namespace ) mofcomp = MOFCompiler ( _MockMOFWBEMConnection ( self ) , search_paths = search_paths , verbose = verbose ) mofcomp . compile_stri...
def get_fragment_language ( ) -> ParserElement : """Build a protein fragment parser ."""
_fragment_value_inner = fragment_range | missing_fragment ( FRAGMENT_MISSING ) _fragment_value = _fragment_value_inner | And ( [ Suppress ( '"' ) , _fragment_value_inner , Suppress ( '"' ) ] ) parser_element = fragment_tag + nest ( _fragment_value + Optional ( WCW + quote ( FRAGMENT_DESCRIPTION ) ) ) return parser_elem...
def _set_logging ( logger_name = "colin" , level = logging . INFO , handler_class = logging . StreamHandler , handler_kwargs = None , format = '%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s' , date_format = '%H:%M:%S' ) : """Set personal logger for this library . : param logger _ name : str...
if level != logging . NOTSET : logger = logging . getLogger ( logger_name ) logger . setLevel ( level ) # do not readd handlers if they are already present if not [ x for x in logger . handlers if isinstance ( x , handler_class ) ] : handler_kwargs = handler_kwargs or { } handler = handl...
def checkPerformance ( self ) -> Optional [ bool ] : """Check if master instance is slow and send an instance change request . : returns True if master performance is OK , False if performance degraded , None if the check was needed"""
logger . trace ( "{} checking its performance" . format ( self ) ) # Move ahead only if the node has synchronized its state with other # nodes if not self . isParticipating : return if self . view_change_in_progress : return if not self . _update_new_ordered_reqs_count ( ) : logger . trace ( "{} ordered no ...
def _tofloat ( obj ) : """Convert to float if object is a float string ."""
if "inf" in obj . lower ( ) . strip ( ) : return obj try : return int ( obj ) except ValueError : try : return float ( obj ) except ValueError : return obj
async def update ( self , fields = '' ) : '''reload object info from emby | coro | Parameters fields : str additional fields to request when updating See Also refresh : same thing send : post :'''
path = 'Users/{{UserId}}/Items/{}' . format ( self . id ) info = await self . connector . getJson ( path , remote = False , Fields = 'Path,Overview,' + fields ) self . object_dict . update ( info ) self . extras = { } return self
def open_shot_path ( self , * args , ** kwargs ) : """Open the currently selected shot in the filebrowser : returns : None : rtype : None : raises : None"""
f = self . shot_path_le . text ( ) d = os . path . dirname ( f ) osinter = get_interface ( ) osinter . open_path ( d )
def find_minimum_spanning_forest_as_subgraphs ( graph ) : """Calculates the minimum spanning forest and returns a list of trees as subgraphs ."""
forest = find_minimum_spanning_forest ( graph ) list_of_subgraphs = [ get_subgraph_from_edge_list ( graph , edge_list ) for edge_list in forest ] return list_of_subgraphs
def add_action ( self , actor , action , date , type = None , committees = None , legislators = None , ** kwargs ) : """Add an action that was performed on this bill . : param actor : a string representing who performed the action . If the action is associated with one of the chambers this should be ' upper '...
def _cleanup_list ( obj , default ) : if not obj : obj = default elif isinstance ( obj , string_types ) : obj = [ obj ] elif not isinstance ( obj , list ) : obj = list ( obj ) return obj type = _cleanup_list ( type , [ 'other' ] ) committees = _cleanup_list ( committees , [ ] ) l...
def _linearize ( interface ) : """Return a list of all the bases of a given interface in depth - first order . @ param interface : an Interface object . @ return : a L { list } of Interface objects , the input in all its bases , in subclass - to - base - class , depth - first order ."""
L = [ interface ] for baseInterface in interface . __bases__ : if baseInterface is not Interface : L . extend ( _linearize ( baseInterface ) ) return L
def oauth_client_create ( self , name , redirect_uri , ** kwargs ) : """Make a new OAuth Client and return it"""
params = { "label" : name , "redirect_uri" : redirect_uri , } params . update ( kwargs ) result = self . client . post ( '/account/oauth-clients' , data = params ) if not 'id' in result : raise UnexpectedResponseError ( 'Unexpected response when creating OAuth Client!' , json = result ) c = OAuthClient ( self . cli...
def tokenize ( self , string ) : '''Maps a string to an iterator over tokens . In other words : [ char ] - > [ token ]'''
new_lexer = ply . lex . lex ( module = self , debug = self . debug , errorlog = logger ) new_lexer . latest_newline = 0 new_lexer . string_value = None new_lexer . input ( string ) while True : t = new_lexer . token ( ) if t is None : break t . col = t . lexpos - new_lexer . latest_newline yield...
def getConfigRoot ( cls , create = False ) : """Return the mapped configuration root node"""
try : return manager . gettree ( getattr ( cls , 'configkey' ) , create ) except AttributeError : return None
def import_table_in_db ( self , file_path , use_columns_with_index , column_names_in_db , table ) : """Imports data from CTD file into database : param str file _ path : path to file : param list [ int ] use _ columns _ with _ index : list of column indices in file : param list [ str ] column _ names _ in _ d...
chunks = pd . read_table ( file_path , usecols = use_columns_with_index , names = column_names_in_db , header = None , comment = '#' , index_col = False , chunksize = 1000000 , dtype = self . get_dtypes ( table . model ) ) for chunk in chunks : # this is an evil hack because CTD is not using the MESH prefix in this tab...
def query_pager_by_slug ( slug , current_page_num = 1 , tag = '' , order = False ) : '''Query pager via category slug .'''
cat_rec = MCategory . get_by_slug ( slug ) if cat_rec : cat_id = cat_rec . uid else : return None # The flowing code is valid . if cat_id . endswith ( '00' ) : # The first level category , using the code bellow . cat_con = TabPost2Tag . par_id == cat_id else : cat_con = TabPost2Tag . tag_id == cat_id if...
def calc_core_bytes ( self ) : """Convert all used annotation fields into bytes to write"""
# The difference sample to write if len ( self . sample ) == 1 : sampdiff = np . array ( [ self . sample [ 0 ] ] ) else : sampdiff = np . concatenate ( ( [ self . sample [ 0 ] ] , np . diff ( self . sample ) ) ) # Create a copy of the annotation object with a # compact version of fields to write compact_annotat...
def dispersion ( words , corpus , y = None , ax = None , colors = None , colormap = None , labels = None , annotate_docs = False , ignore_case = False , ** kwargs ) : """Displays lexical dispersion plot for words in a corpus This helper function is a quick wrapper to utilize the DisperstionPlot Visualizer for o...
# Instantiate the visualizer visualizer = DispersionPlot ( words , ax = ax , colors = colors , colormap = colormap , ignore_case = ignore_case , labels = labels , annotate_docs = annotate_docs , ** kwargs ) # Fit and transform the visualizer ( calls draw ) visualizer . fit ( corpus , y , ** kwargs ) # Return the axes o...
def ReadAllClientActionRequests ( self , client_id ) : """Reads all client action requests available for a given client _ id ."""
res = [ ] for key , orig_request in iteritems ( self . client_action_requests ) : request_client_id , _ , _ = key if request_client_id != client_id : continue request = orig_request . Copy ( ) current_lease = self . client_action_request_leases . get ( key ) request . ttl = db . Database . C...
def ismatch ( a , b ) : """Method to allow smart comparisons between classes , instances , and string representations of units and give the right answer . For internal use only ."""
# Try the easy case if a == b : return True else : # Try isinstance in both orders try : if isinstance ( a , b ) : return True except TypeError : try : if isinstance ( b , a ) : return True except TypeError : # Try isinstance ( a , type ( b ) )...
def _write_utf8 ( write , value ) : """Writes a length - prefixed UTF - 8 string ."""
write ( 'h' , len ( value ) ) write . io . write ( value . encode ( 'utf-8' ) )
def run_changed_file_cmd ( cmd , fp , pretty ) : """running commands on changes . pretty the parsed file"""
with open ( fp ) as f : raw = f . read ( ) # go sure regarding quotes : for ph in ( dir_mon_filepath_ph , dir_mon_content_raw , dir_mon_content_pretty ) : if ph in cmd and not ( '"%s"' % ph ) in cmd and not ( "'%s'" % ph ) in cmd : cmd = cmd . replace ( ph , '"%s"' % ph ) cmd = cmd . replace ( dir_mon_f...
def validate_collections ( self , model , context = None ) : """Validate collection properties Performs validation on collection properties to return a result object . : param model : object or dict : param context : object , dict or None : return : shiftschema . result . Result"""
result = Result ( ) for property_name in self . collections : prop = self . collections [ property_name ] collection = self . get ( model , property_name ) errors = prop . validate ( value = collection , model = model , context = context ) if len ( errors ) : result . add_collection_errors ( pro...
def curve_specialize ( curve , new_curve ) : """Image for : meth ` . Curve . specialize ` docstring ."""
if NO_IMAGES : return ax = curve . plot ( 256 ) interval = r"$\left[0, 1\right]$" line = ax . lines [ - 1 ] line . set_label ( interval ) color1 = line . get_color ( ) new_curve . plot ( 256 , ax = ax ) interval = r"$\left[-\frac{1}{4}, \frac{3}{4}\right]$" line = ax . lines [ - 1 ] line . set_label ( interval ) ax...
def insrtc ( item , inset ) : """Insert an item into a character set . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / insrtc _ c . html : param item : Item to be inserted . : type item : str or list of str : param inset : Insertion set . : type inset : spiceypy . utils . s...
assert isinstance ( inset , stypes . SpiceCell ) if isinstance ( item , list ) : for c in item : libspice . insrtc_c ( stypes . stringToCharP ( c ) , ctypes . byref ( inset ) ) else : item = stypes . stringToCharP ( item ) libspice . insrtc_c ( item , ctypes . byref ( inset ) )
def forbid_multi_line_headers ( name , val ) : """Forbid multi - line headers , to prevent header injection ."""
val = smart_text ( val ) if "\n" in val or "\r" in val : raise BadHeaderError ( "Header values can't contain newlines " "(got %r for header %r)" % ( val , name ) ) try : val = val . encode ( "ascii" ) except UnicodeEncodeError : if name . lower ( ) in ( "to" , "from" , "cc" ) : result = [ ] ...
def selected_item ( self ) : """: obj : ` consolemenu . items . MenuItem ` : The item in : attr : ` items ` that the user most recently selected , or None ."""
if self . items and self . selected_option != - 1 : return self . items [ self . current_option ] else : return None
def setup_pilotpoints_grid ( ml = None , sr = None , ibound = None , prefix_dict = None , every_n_cell = 4 , use_ibound_zones = False , pp_dir = '.' , tpl_dir = '.' , shapename = "pp.shp" ) : """setup regularly - spaced ( gridded ) pilot point parameterization Parameters ml : flopy . mbase a flopy mbase dervi...
from . import pp_utils warnings . warn ( "setup_pilotpoint_grid has moved to pp_utils..." , PyemuWarning ) return pp_utils . setup_pilotpoints_grid ( ml = ml , sr = sr , ibound = ibound , prefix_dict = prefix_dict , every_n_cell = every_n_cell , use_ibound_zones = use_ibound_zones , pp_dir = pp_dir , tpl_dir = tpl_dir ...
def _admx_policy_parent_walk ( path , policy_namespace , parent_category , policy_nsmap , return_full_policy_names , adml_language ) : '''helper function to recursively walk up the ADMX namespaces and build the hierarchy for the policy'''
admx_policy_definitions = _get_policy_definitions ( language = adml_language ) category_xpath_string = '/policyDefinitions/categories/{0}:category[@name="{1}"]' using_xpath_string = '/policyDefinitions/policyNamespaces/{0}:using' if parent_category . find ( ':' ) >= 0 : # the parent is in another namespace policy_n...
def compute_ng_stat ( gene_graph , pos_ct , alpha = .5 ) : """Compute the clustering score for the gene on its neighbor graph . Parameters gene _ graph : dict Graph of spatially near codons . keys = nodes , edges = key - > value . pos _ ct : dict missense mutation count for each codon alpha : float sm...
# skip if there are no missense mutations if not len ( pos_ct ) : return 1.0 , 0 max_pos = max ( gene_graph ) codon_vals = np . zeros ( max_pos + 1 ) # smooth out mutation counts for pos in pos_ct : mut_count = pos_ct [ pos ] # update neighbor values neighbors = list ( gene_graph [ pos ] ) num_neigh...
def from_date ( cls , date ) : """Returns a Month instance from the given datetime . date or datetime . datetime object"""
try : date = date . date ( ) except AttributeError : pass return cls ( date . year , date . month )
def xml ( self , attribs = None , elements = None , skipchildren = False ) : """See : meth : ` AbstractElement . xml `"""
if not attribs : attribs = { } E = ElementMaker ( namespace = "http://ilk.uvt.nl/folia" , nsmap = { None : "http://ilk.uvt.nl/folia" , 'xml' : "http://www.w3.org/XML/1998/namespace" } ) e = super ( AbstractSpanAnnotation , self ) . xml ( attribs , elements , True ) for child in self : if isinstance ( child , ( ...
def make_fig ( self ) : """Figure constructor , called before ` self . plot ( ) `"""
self . fig = plt . figure ( figsize = ( 8 , 4 ) ) self . _all_figures . append ( self . fig )
def Many2ManyThroughModel ( field ) : '''Create a Many2Many through model with two foreign key fields and a CompositeFieldId depending on the two foreign keys .'''
from stdnet . odm import ModelType , StdModel , ForeignKey , CompositeIdField name_model = field . model . _meta . name name_relmodel = field . relmodel . _meta . name # The two models are the same . if name_model == name_relmodel : name_relmodel += '2' through = field . through # Create the through model if throug...
def updateVocalAuto ( self , component , files ) : """Updates the auto - parameter with selected * component * to have * files * . Adds auto - parameter if not already present . The auto - parameter is expected to have only one selected component ( the one given ) . If length of files < 1 , removes the auto -...
auto_model = self . model ( ) . autoParams ( ) row = auto_model . fileParameter ( component ) if len ( files ) > 1 : clean_component = self . model ( ) . data ( self . model ( ) . indexByComponent ( component ) , AbstractDragView . DragRole ) p = { 'parameter' : 'filename' , 'names' : files , 'selection' : [ cl...
def _flatten ( self , iterator , ** filter_options ) : '''iterator here gives as lists of tuples . Method flattens the structure to a single list of tuples .'''
resp = list ( ) for entry in iterator : for tup in entry : if self . _matches_filter ( tup , ** filter_options ) : resp . append ( tup ) return resp
def get_catalog_nodes ( self , catalog_id , ancestor_levels , descendant_levels , include_siblings ) : """Gets a portion of the hierarchy for the given catalog . arg : catalog _ id ( osid . id . Id ) : the ` ` Id ` ` to query arg : ancestor _ levels ( cardinal ) : the maximum number of ancestor levels to incl...
# Implemented from template for # osid . resource . BinHierarchySession . get _ bin _ nodes return objects . CatalogNode ( self . get_catalog_node_ids ( catalog_id = catalog_id , ancestor_levels = ancestor_levels , descendant_levels = descendant_levels , include_siblings = include_siblings ) . _my_map , runtime = self ...
def update ( self , adgroup_id , catmatch_id , max_price , is_default_price , online_status , nick = None ) : '''xxxxx . xxxxx . adgroup . catmatch . update 更新一个推广组的类目出价 , 可以设置类目出价 、 是否使用默认出价 、 是否打开类目出价'''
request = TOPRequest ( 'xxxxx.xxxxx.adgroup.catmatch.update' ) request [ 'adgroup_id' ] = adgroup_id request [ 'catmatch_id' ] = catmatch_id request [ 'max_price' ] = max_price request [ 'is_default_price' ] = is_default_price request [ 'online_status' ] = online_status if nick != None : request [ 'nick' ] = nick s...
def receive ( self ) : """Receives incoming websocket messages , and puts them on the Client queue for processing . : return :"""
while self . running : if self . _receiver_lock . acquire ( blocking = False ) : try : raw = self . conn . recv ( ) except WebSocketTimeoutException : self . _receiver_lock . release ( ) continue except WebSocketConnectionClosedException : # this needs to ...
def get_team_push_restrictions ( self ) : """: rtype : : class : ` github . PaginatedList . PaginatedList ` of : class : ` github . Team . Team `"""
if self . _team_push_restrictions is github . GithubObject . NotSet : return None return github . PaginatedList . PaginatedList ( github . Team . Team , self . _requester , self . _team_push_restrictions , None )
def complete_path ( curr_dir , last_dir ) : """Return the path to complete that matches the last entered component . If the last entered component is ~ , expanded path would not match , so return all of the available paths . : param curr _ dir : str : param last _ dir : str : return : str"""
if not last_dir or curr_dir . startswith ( last_dir ) : return curr_dir elif last_dir == '~' : return os . path . join ( last_dir , curr_dir )
def patch_splitMax ( self , patches ) : """Look through the patches and break up any which are longer than the maximum limit of the match algorithm . Intended to be called only from within patch _ apply . Args : patches : Array of Patch objects ."""
patch_size = self . Match_MaxBits if patch_size == 0 : # Python has the option of not splitting strings due to its ability # to handle integers of arbitrary precision . return for x in range ( len ( patches ) ) : if patches [ x ] . length1 <= patch_size : continue bigpatch = patches [ x ] # Remo...
def impute_and_confidence ( self , M_c , X_L , X_D , Y , Q , seed , n ) : """Impute values and confidence of the value from the predictive distribution of the given latent state . : param Y : A list of constraints to apply when sampling . Each constraint is a triplet of ( r , d , v ) : r is the row index , d ...
get_next_seed = make_get_next_seed ( seed ) if isinstance ( X_L , ( list , tuple ) ) : assert isinstance ( X_D , ( list , tuple ) ) # TODO : multistate impute doesn ' t exist yet # e , confidence = su . impute _ and _ confidence _ multistate ( # M _ c , X _ L , X _ D , Y , Q , n , self . get _ next _ se...
def VerifyStructure ( self , parser_mediator , line ) : """Verify that this file is a SkyDrive old log file . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . line ( str ) : line from a text file . Returns : bool : Tru...
try : structure = self . _LINE . parseString ( line ) except pyparsing . ParseException : logger . debug ( 'Not a SkyDrive old log file' ) return False day_of_month , month , year , hours , minutes , seconds , milliseconds = ( structure . date_time ) time_elements_tuple = ( year , month , day_of_month , hou...
def init_app ( self , app , context = DEFAULT_DICT ) : """Lazy constructor for the : class : ` Component ` class . This method will allow the component to be used like a Flask extension / singleton . Args : app ( flask . Flask ) : The Application to base this Component upon . Useful for app wide singleton...
if context is not _CONTEXT_MISSING : self . update_context ( context , app = app ) # do not readd callbacks if already present ; and if there ' s no context # present , there ' s no real need to add callbacks if ( app not in _CONTEXT_CALLBACK_MAP and context is not _CONTEXT_MISSING ) : key = self . _get_context...
def _make_dav_request ( self , method , path , ** kwargs ) : """Makes a WebDAV request : param method : HTTP method : param path : remote path of the targetted file : param \ * \ * kwargs : optional arguments that ` ` requests . Request . request ` ` accepts : returns array of : class : ` FileInfo ` if the ...
if self . _debug : print ( 'DAV request: %s %s' % ( method , path ) ) if kwargs . get ( 'headers' ) : print ( 'Headers: ' , kwargs . get ( 'headers' ) ) path = self . _normalize_path ( path ) res = self . _session . request ( method , self . _webdav_url + parse . quote ( self . _encode_string ( path ) )...
def _GenerateInitConfigs ( self , template_dir , rpm_build_dir ) : """Generates init - system configs ."""
client_name = config . CONFIG . Get ( "Client.name" , context = self . context ) initd_target_filename = os . path . join ( rpm_build_dir , "etc/init.d" , client_name ) # Generate init . d utils . EnsureDirExists ( os . path . dirname ( initd_target_filename ) ) self . GenerateFile ( os . path . join ( template_dir , "...
def get_tree ( self ) : """Returns a : class : ` Con ` instance with all kinds of methods and selectors . Start here with exploration . Read up on the : class : ` Con ` stuffs . : rtype : Con"""
data = self . message ( MessageType . GET_TREE , '' ) return Con ( json . loads ( data ) , None , self )
def raw_cube_array ( self ) : """Return read - only ndarray of measure values from cube - response . The shape of the ndarray mirrors the shape of the ( raw ) cube response . Specifically , it includes values for missing elements , any MR _ CAT dimensions , and any prunable rows and columns ."""
array = np . array ( self . _flat_values ) . reshape ( self . _all_dimensions . shape ) # - - - must be read - only to avoid hard - to - find bugs - - - array . flags . writeable = False return array
def flip_for ( self , twig = None , expression = None , ** kwargs ) : """flip the constraint to solve for for any of the parameters in the expression expression ( optional if sympy available , required if not )"""
_orig_expression = self . get_value ( ) # try to get the parameter from the bundle kwargs [ 'twig' ] = twig newly_constrained_var = self . _get_var ( ** kwargs ) newly_constrained_param = self . get_parameter ( ** kwargs ) check_kwargs = { k : v for k , v in newly_constrained_param . meta . items ( ) if k not in [ 'con...
def upgrade_code ( self ) : '''For installers which follow the Microsoft Installer standard , returns the ` ` Upgrade code ` ` . Returns : value ( str ) : ` ` Upgrade code ` ` GUID for installed software .'''
if not self . __squid : # Must have a valid squid for an upgrade code to exist return '' # GUID / SQUID are unique , so it does not matter if they are 32bit or # 64bit or user install so all items are cached into a single dict have_scan_key = '{0}\\{1}\\{2}' . format ( self . __reg_hive , self . __reg_upgradecode_p...
def get_instance ( self , payload ) : """Build an instance of PhoneNumberInstance : param dict payload : Payload response from the API : returns : twilio . rest . trunking . v1 . trunk . phone _ number . PhoneNumberInstance : rtype : twilio . rest . trunking . v1 . trunk . phone _ number . PhoneNumberInstance...
return PhoneNumberInstance ( self . _version , payload , trunk_sid = self . _solution [ 'trunk_sid' ] , )
def get_distance ( self , node ) : """Get the distance beetween 2 nodes Args : node ( object ) : The other node ."""
delta = ( node . pos [ 0 ] - self . pos [ 0 ] , node . pos [ 1 ] - self . pos [ 1 ] ) return sqrt ( delta [ 0 ] ** 2 + delta [ 1 ] ** 2 )
def read_namespaced_horizontal_pod_autoscaler_status ( self , name , namespace , ** kwargs ) : # noqa : E501 """read _ namespaced _ horizontal _ pod _ autoscaler _ status # noqa : E501 read status of the specified HorizontalPodAutoscaler # noqa : E501 This method makes a synchronous HTTP request by default . To...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . read_namespaced_horizontal_pod_autoscaler_status_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 else : ( data ) = self . read_namespaced_horizontal_pod_autoscaler_status_with_http_info ( name , namespac...
def optimization_loop ( self , timeSeries , forecastingMethod , remainingParameters , currentParameterValues = None ) : """The optimization loop . This function is called recursively , until all parameter values were evaluated . : param TimeSeries timeSeries : TimeSeries instance that requires an optimized fore...
if currentParameterValues is None : currentParameterValues = { } # The most inner loop is reached if 0 == len ( remainingParameters ) : # set the forecasting parameters for parameter in currentParameterValues : forecastingMethod . set_parameter ( parameter , currentParameterValues [ parameter ] ) # ...
def build_all_keys_dict ( self ) : """build _ all _ keys _ dict"""
log . info ( "finding keys" ) for k in self . eth_keys : ak = "{}" . format ( k ) if ak not in self . all_keys : self . all_keys [ ak ] = k # end of building all eths for k in self . ip_keys : ak = "{}" . format ( k ) if ak not in self . all_keys : self . all_keys [ ak ] = k # end of bui...