signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def isUpdated ( self ) : """Figures out if the file had previously errored and hasn ' t been fixed since given a numerical time"""
modified_time = self . getmtime ( ) valid = modified_time > self . __stamp return valid
def get_uri_name ( url ) : """Gets the file name from the end of the URL . Only useful for PyBEL ' s testing though since it looks specifically if the file is from the weird owncloud resources distributed by Fraunhofer"""
url_parsed = urlparse ( url ) url_parts = url_parsed . path . split ( '/' ) log . info ( 'url parts: %s' , url_parts ) return url_parts [ - 1 ]
def output ( self ) : """Returns the default workflow outputs in an ordered dictionary . At the moment this is just the collection of outputs of the branch tasks , stored with the key ` ` " collection " ` ` ."""
if self . task . target_collection_cls is not None : cls = self . task . target_collection_cls elif self . task . outputs_siblings : cls = SiblingFileCollection else : cls = TargetCollection targets = luigi . task . getpaths ( self . task . get_branch_tasks ( ) ) collection = cls ( targets , threshold = sel...
def GameTypeEnum ( ctx ) : """Game Type Enumeration ."""
return Enum ( ctx , RM = 0 , Regicide = 1 , DM = 2 , Scenario = 3 , Campaign = 4 , KingOfTheHill = 5 , WonderRace = 6 , DefendTheWonder = 7 , TurboRandom = 8 )
def get_mysql_pool ( host = None , user = None , password = None , charset = 'utf8' , db = None , size = None , isSync = True , ioloop = None ) : """使用工厂方法返回一个连接池"""
factory = mysql_pool_factory ( isSync ) kwargs = { 'host' : host , 'user' : user , 'password' : password , 'charset' : charset , 'db' : db , 'size' : size , } return factory ( ** kwargs )
def getCmdOpts ( self , text ) : '''Use the _ cmd _ syntax def to split / parse / normalize the cmd line . Args : text ( str ) : Command to process . Notes : This is implemented independent of argparse ( et al ) due to the need for syntax aware argument splitting . Also , allows different split per comm...
off = 0 _ , off = s_syntax . nom ( text , off , s_syntax . whites ) name , off = s_syntax . meh ( text , off , s_syntax . whites ) _ , off = s_syntax . nom ( text , off , s_syntax . whites ) opts = { } args = collections . deque ( [ synt for synt in self . _cmd_syntax if not synt [ 0 ] . startswith ( '-' ) ] ) switches...
def send_reset_password_link ( request ) : '''Send email with reset password link .'''
if not registration_settings . RESET_PASSWORD_VERIFICATION_ENABLED : raise Http404 ( ) serializer = SendResetPasswordLinkSerializer ( data = request . data ) serializer . is_valid ( raise_exception = True ) login = serializer . validated_data [ 'login' ] user = None for login_field in get_login_fields ( ) : use...
def run_numerical_analysis ( table , schema_list , args ) : """Find min / max values for the numerical columns and writes a json file . Args : table : Reference to FederatedTable ( if bigquery _ table is false ) or a regular Table ( otherwise ) schema _ list : Bigquery schema json object args : the comman...
import google . datalab . bigquery as bq # Get list of numerical columns . numerical_columns = [ ] for col_schema in schema_list : col_type = col_schema [ 'type' ] . lower ( ) if col_type == 'integer' or col_type == 'float' : numerical_columns . append ( col_schema [ 'name' ] ) # Run the numerical analy...
def updatePotentialRadius ( sp , newPotentialRadius ) : """Change the potential radius for all columns : return :"""
oldPotentialRadius = sp . _potentialRadius sp . _potentialRadius = newPotentialRadius numColumns = np . prod ( sp . getColumnDimensions ( ) ) for columnIndex in xrange ( numColumns ) : potential = sp . _mapPotential ( columnIndex ) sp . _potentialPools . replace ( columnIndex , potential . nonzero ( ) [ 0 ] ) s...
def get_field_infos ( code , free_format ) : """Gets the list of pic fields information from line | start | to line | end | . : param code : code to parse : returns : the list of pic fields info found in the specified text ."""
offset = 0 field_infos = [ ] lines = _clean_code ( code ) previous_offset = 0 for row in process_cobol ( lines , free_format ) : fi = PicFieldInfo ( ) fi . name = row [ "name" ] fi . level = row [ "level" ] fi . pic = row [ "pic" ] fi . occurs = row [ "occurs" ] fi . redefines = row [ "redefines...
def get_datafeed_stats ( self , datafeed_id = None , params = None ) : """` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / ml - get - datafeed - stats . html > ` _ : arg datafeed _ id : The ID of the datafeeds stats to fetch : arg allow _ no _ datafeeds : Whether to ignore ...
return self . transport . perform_request ( "GET" , _make_path ( "_ml" , "datafeeds" , datafeed_id , "_stats" ) , params = params )
def _validate_names ( self , name = None , names = None , deep = False ) : """Handles the quirks of having a singular ' name ' parameter for general Index and plural ' names ' parameter for MultiIndex ."""
from copy import deepcopy if names is not None and name is not None : raise TypeError ( "Can only provide one of `names` and `name`" ) elif names is None and name is None : return deepcopy ( self . names ) if deep else self . names elif names is not None : if not is_list_like ( names ) : raise TypeE...
def addAction ( self , action ) : """Adds the inputed action to this toolbar . : param action | < QAction >"""
super ( XDockToolbar , self ) . addAction ( action ) label = XDockActionLabel ( action , self . minimumPixmapSize ( ) , self ) label . setPosition ( self . position ( ) ) layout = self . layout ( ) layout . insertWidget ( layout . count ( ) - 1 , label )
def _correct_qualimap_genome_results ( samples ) : """fixing java . lang . Double . parseDouble error on entries like " 6,082.49" """
for s in samples : if verify_file ( s . qualimap_genome_results_fpath ) : correction_is_needed = False with open ( s . qualimap_genome_results_fpath , 'r' ) as f : content = f . readlines ( ) metrics_started = False for line in content : if ">> Ref...
def _encode_item ( self , item ) : '''Encode an item object @ requires : The object be serializable'''
if self . encoding . __name__ == 'pickle' : return self . encoding . dumps ( item , protocol = - 1 ) else : return self . encoding . dumps ( item )
def batchsd ( trace , batches = 5 ) : """Calculates the simulation standard error , accounting for non - independent samples . The trace is divided into batches , and the standard deviation of the batch means is calculated ."""
if len ( np . shape ( trace ) ) > 1 : dims = np . shape ( trace ) # ttrace = np . transpose ( np . reshape ( trace , ( dims [ 0 ] , sum ( dims [ 1 : ] ) ) ) ) ttrace = np . transpose ( [ t . ravel ( ) for t in trace ] ) return np . reshape ( [ batchsd ( t , batches ) for t in ttrace ] , dims [ 1 : ] ) e...
def on_directory_button_tool_clicked ( self ) : """Autoconnect slot activated when directory button is clicked ."""
# noinspection PyCallByClass , PyTypeChecker # set up parameter from dialog input_path = self . layer . currentLayer ( ) . source ( ) input_directory , self . output_filename = os . path . split ( input_path ) file_extension = os . path . splitext ( self . output_filename ) [ 1 ] self . output_filename = os . path . sp...
def load_layer_without_provider ( layer_uri , layer_name = 'tmp' ) : """Helper to load a layer when don ' t know the driver . Don ' t use it , it ' s an empiric function to try each provider one per one . OGR / GDAL is printing a lot of error saying that the layer is not valid . : param layer _ uri : Layer UR...
# Let ' s try the most common vector driver layer = QgsVectorLayer ( layer_uri , layer_name , VECTOR_DRIVERS [ 0 ] ) if layer . isValid ( ) : return layer # Let ' s try the most common raster driver layer = QgsRasterLayer ( layer_uri , layer_name , RASTER_DRIVERS [ 0 ] ) if layer . isValid ( ) : return layer # ...
def parse_request ( self , request , parameters = None , fake_method = None ) : '''Parse WebOb request'''
return ( request . method , request . url , request . headers , request . POST . mixed ( ) )
def deinit ( bus = DEFAULT_SPI_BUS , chip_select = DEFAULT_SPI_CHIP_SELECT ) : """Stops interrupts on all boards . Only required when using : func : ` digital _ read ` and : func : ` digital _ write ` . : param bus : SPI bus / dev / spidev < bus > . < chipselect > ( default : { bus } ) : type bus : int : pa...
global _pifacedigitals for pfd in _pifacedigitals : try : pfd . deinit_board ( ) except AttributeError : pass
def split_marker ( marker , fg_id = 1 , bg_id = 2 ) : """Splits an integer marker image into two binary image containing the foreground and background markers respectively . All encountered 1 ' s are hereby treated as foreground , all 2 ' s as background , all 0 ' s as neutral marker and all others are ignore...
img_marker = scipy . asarray ( marker ) img_fgmarker = scipy . zeros ( img_marker . shape , scipy . bool_ ) img_fgmarker [ img_marker == fg_id ] = True img_bgmarker = scipy . zeros ( img_marker . shape , scipy . bool_ ) img_bgmarker [ img_marker == bg_id ] = True return img_fgmarker , img_bgmarker
def Lc ( self , value ) : """set col rotation"""
assert value . shape == ( self . P , self . P ) , 'dimension mismatch' self . _Lc = value self . clear_cache ( )
def has_module_perms ( self , user_obj , app_label ) : """Check if user have permission of specified app Parameters user _ obj : django user model instance A django user model instance which be checked app _ label : string Django application name Returns boolean Whether the specified user have any p...
cache_name = "_has_module_perms_%s_%s_cache" % ( app_label , user_obj . pk ) if hasattr ( self , cache_name ) : return getattr ( self , cache_name ) if self . app_label != app_label : setattr ( self , cache_name , False ) else : for permission in self . get_supported_permissions ( ) : if user_obj . ...
def parse_rules ( data , chain ) : """Parse the rules for the specified chain ."""
rules = [ ] for line in data . splitlines ( True ) : m = re_rule . match ( line ) if m and m . group ( 3 ) == chain : rule = parse_rule ( m . group ( 4 ) ) rule . packets = int ( m . group ( 1 ) ) rule . bytes = int ( m . group ( 2 ) ) rules . append ( rule ) return rules
def _decode_input_tensor_to_features_dict ( feature_map , hparams ) : """Convert the interactive input format ( see above ) to a dictionary . Args : feature _ map : dict with inputs . hparams : model hyperparameters Returns : a features dictionary , as expected by the decoder ."""
inputs = tf . convert_to_tensor ( feature_map [ "inputs" ] ) input_is_image = False x = inputs p_hparams = hparams . problem_hparams # Add a third empty dimension x = tf . expand_dims ( x , axis = [ 2 ] ) x = tf . to_int32 ( x ) input_space_id = tf . constant ( p_hparams . input_space_id ) target_space_id = tf . consta...
def check_expression ( testing_framework , expression_dict ) : """> > > class mock _ framework : . . . def assertIn ( self , item , list , msg = " Failed asserting item is in list " ) : . . . if item not in list : raise Exception ( msg ) . . . def assertTrue ( self , value , msg = " Failed asserting true " ) ...
expression_sub = get_expression_sub ( ) for expression_type_name , expression_type in expression_dict . items ( ) : for name , expression_object in expression_type . items ( ) : if 'Matches' in expression_object . keys ( ) : for test in expression_object [ 'Matches' ] . split ( '|' ) : # Substit...
def Channels ( module ) : '''Returns the channels contained in the given K2 module .'''
nums = { 2 : 1 , 3 : 5 , 4 : 9 , 6 : 13 , 7 : 17 , 8 : 21 , 9 : 25 , 10 : 29 , 11 : 33 , 12 : 37 , 13 : 41 , 14 : 45 , 15 : 49 , 16 : 53 , 17 : 57 , 18 : 61 , 19 : 65 , 20 : 69 , 22 : 73 , 23 : 77 , 24 : 81 } if module in nums : return [ nums [ module ] , nums [ module ] + 1 , nums [ module ] + 2 , nums [ module ] ...
def _send ( self , messagetype , packet ) : """Send the GNTP Packet"""
packet . validate ( ) data = packet . encode ( ) logger . debug ( 'To : %s:%s <%s>\n%s' , self . hostname , self . port , packet . __class__ , data ) s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) s . settimeout ( self . socketTimeout ) try : s . connect ( ( self . hostname , self . port ) ) s ...
def verify_message ( data_to_verify , signature , verify_cert ) : """Function parses an ASN . 1 encrypted message and extracts / decrypts the original message . : param data _ to _ verify : A byte string of the data to be verified against the signature . : param signature : A CMS ASN . 1 byte string contain...
cms_content = cms . ContentInfo . load ( signature ) digest_alg = None if cms_content [ 'content_type' ] . native == 'signed_data' : for signer in cms_content [ 'content' ] [ 'signer_infos' ] : signed_attributes = signer [ 'signed_attrs' ] . copy ( ) digest_alg = signer [ 'digest_algorithm' ] [ 'alg...
def dir ( base_dir : str , rr_id : str ) -> str : """Return correct subdirectory of input base dir for artifacts corresponding to input rev reg id . : param base _ dir : base directory for tails files , thereafter split by cred def id : param rr _ id : rev reg id"""
LOGGER . debug ( 'Tails.dir >>> base_dir: %s, rr_id: %s' , base_dir , rr_id ) if not ok_rev_reg_id ( rr_id ) : LOGGER . debug ( 'Tails.dir <!< Bad rev reg id %s' , rr_id ) raise BadIdentifier ( 'Bad rev reg id {}' . format ( rr_id ) ) rv = join ( base_dir , rev_reg_id2cred_def_id ( rr_id ) ) LOGGER . debug ( 'T...
async def _make_qr ( self , qr : QuickRepliesList . BaseOption , request : Request ) : """Generate a single quick reply ' s content ."""
if isinstance ( qr , QuickRepliesList . TextOption ) : return { 'content_type' : 'text' , 'title' : await render ( qr . text , request ) , 'payload' : qr . slug , } elif isinstance ( qr , QuickRepliesList . LocationOption ) : return { 'content_type' : 'location' , }
def create_embedded_class ( self , method ) : """Build the estimator class . Returns : return : string The built class as string ."""
temp_class = self . temp ( 'embedded.class' ) return temp_class . format ( class_name = self . class_name , method_name = self . method_name , method = method , n_features = self . n_features )
def describe ( df , dtype = None ) : """Print a description of a Pandas dataframe . Parameters df : Pandas . DataFrame dtype : dict Maps column names to types"""
if dtype is None : dtype = { } print ( 'Number of datapoints: {datapoints}' . format ( datapoints = len ( df ) ) ) column_info , column_info_meta = _get_column_info ( df , dtype ) if len ( column_info [ 'int' ] ) > 0 : _describe_int ( df , column_info ) if len ( column_info [ 'float' ] ) > 0 : _describe_flo...
def get_reservations_for_booking_ids ( self , booking_ids ) : """Gets booking information for a given list of booking ids . : param booking _ ids : a booking id or a list of room ids ( comma separated ) . : type booking _ ids : string"""
try : resp = self . _request ( "GET" , "/1.1/space/booking/{}" . format ( booking_ids ) ) except resp . exceptions . HTTPError as error : raise APIError ( "Server Error: {}" . format ( error ) ) return resp . json ( )
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_local_interface_name ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_lldp_neighbor_detail = ET . Element ( "get_lldp_neighbor_detail" ) config = get_lldp_neighbor_detail output = ET . SubElement ( get_lldp_neighbor_detail , "output" ) lldp_neighbor_detail = ET . SubElement ( output , "lldp-neighbor-detail" ) remote_interface_name_key = ET . SubElem...
def compute_route_time_series ( feed : "Feed" , trip_stats_subset : DataFrame , dates : List [ str ] , freq : str = "5Min" , * , split_directions : bool = False , ) -> DataFrame : """Compute route stats in time series form for the trips that lie in the trip stats subset and that start on the given dates . Param...
dates = feed . restrict_dates ( dates ) if not dates : return pd . DataFrame ( ) activity = feed . compute_trip_activity ( dates ) ts = trip_stats_subset . copy ( ) # Collect stats for each date , memoizing stats by trip ID sequence # to avoid unnecessary re - computations . # Store in dictionary of the form # trip...
def _encode_var ( cls , var ) : """Encodes a variable to the appropriate string format for ini files . : param var : The variable to encode : return : The ini representation of the variable : rtype : str"""
if isinstance ( var , str ) : if any ( _ in var for _ in cls . requires_quotes ) : # NOTE : quoted strings should just use ' " ' according to the spec return '"' + var . replace ( '"' , '\\"' ) + '"' return var else : return str ( var )
def command ( self , command ) : """Run a command on the currently active container . : rtype : CommandReply"""
return self . _conn . command ( '[con_id="{}"] {}' . format ( self . id , command ) )
def _run_info_from_yaml ( dirs , run_info_yaml , config , sample_names = None , is_cwl = False , integrations = None ) : """Read run information from a passed YAML file ."""
validate_yaml ( run_info_yaml , run_info_yaml ) with open ( run_info_yaml ) as in_handle : loaded = yaml . safe_load ( in_handle ) fc_name , fc_date = None , None if dirs . get ( "flowcell" ) : try : fc_name , fc_date = flowcell . parse_dirname ( dirs . get ( "flowcell" ) ) except ValueError : ...
def get_port ( self , adapter_number , port_number ) : """Return the port for this adapter _ number and port _ number or returns None if the port is not found"""
for port in self . ports : if port . adapter_number == adapter_number and port . port_number == port_number : return port return None
def connect_after ( self , detailed_signal , handler , * args ) : """connect _ after ( detailed _ signal : str , handler : function , * args ) - > handler _ id : int The connect _ after ( ) method is similar to the connect ( ) method except that the handler is added to the signal handler list after the defaul...
flags = GConnectFlags . CONNECT_AFTER return self . __connect ( flags , detailed_signal , handler , * args )
def is_prime ( n ) : """Return True if x is prime , False otherwise . We use the Miller - Rabin test , as given in Menezes et al . p . 138. This test is not exact : there are composite values n for which it returns True . In testing the odd numbers from 1000001 to 199999, about 66 composites got past the ...
# ( This is used to study the risk of false positives : ) global miller_rabin_test_count miller_rabin_test_count = 0 if n <= smallprimes [ - 1 ] : if n in smallprimes : return True else : return False if gcd ( n , 2 * 3 * 5 * 7 * 11 ) != 1 : return False # Choose a number of iterations suffi...
def usesTime ( self , fmt = None ) : '''Check if the format uses the creation time of the record .'''
if fmt is None : fmt = self . _fmt if not isinstance ( fmt , basestring ) : fmt = fmt [ 0 ] return fmt . find ( '%(asctime)' ) >= 0
def init_process ( self ) -> None : """GunicornWorker 初始化回调"""
default_loop = asyncio . get_event_loop ( ) if default_loop . is_running ( ) : default_loop . close ( ) self . loop = asyncio . new_event_loop ( ) asyncio . set_event_loop ( self . loop ) else : self . loop = default_loop super ( ) . init_process ( )
def list_delete ( self , id ) : """Delete a list ."""
id = self . __unpack_id ( id ) self . __api_request ( 'DELETE' , '/api/v1/lists/{0}' . format ( id ) )
def modify ( self , ** kwargs ) : """We need to implement the custom exclusive parameter check ."""
self . _check_exclusive_parameters ( ** kwargs ) return super ( Rule , self ) . _modify ( ** kwargs )
def get_nodes ( self , request ) : """This method is used to build the menu tree ."""
nodes = [ ] for scientist in Scientist . objects . filter ( current = True , visible = True ) : node = NavigationNode ( scientist . full_name , reverse ( 'lab_members:scientist_detail' , args = ( scientist . slug , ) ) , scientist . slug ) nodes . append ( node ) if Scientist . objects . filter ( current = Fals...
def api_ebuio_forum_get_topics_by_tag_for_user ( request , key = None , hproPk = None , tag = None , userPk = None ) : """Return the list of topics using the tag pk"""
# Check API key ( in order to be sure that we have a valid one and that ' s correspond to the project if not check_api_key ( request , key , hproPk ) : return HttpResponseForbidden if settings . PIAPI_STANDALONE : return HttpResponse ( json . dumps ( { 'error' : 'no-on-ebuio' } ) , content_type = "application/j...
def set_options ( self , options ) : """options = [ { ' product _ option ' : instance of ProductFinalOption , ' product _ final ' : instance of ProductFinal , ' quantity ' : Float"""
with transaction . atomic ( ) : for option in options : opt = self . line_basket_option_sales . filter ( product_option = option [ 'product_option' ] ) . first ( ) if opt : # edit change = False if opt . quantity != option [ 'quantity' ] : opt . quantity = opt...
def _name_messages_complete ( self ) : """Check if all name messages have been received"""
for channel in range ( 1 , self . number_of_channels ( ) + 1 ) : try : for name_index in range ( 1 , 4 ) : if not isinstance ( self . _name_data [ channel ] [ name_index ] , str ) : return False except Exception : return False return True
def print_context_info ( self ) : """Prints moderngl context info ."""
print ( "Context Version:" ) print ( 'ModernGL:' , moderngl . __version__ ) print ( 'vendor:' , self . ctx . info [ 'GL_VENDOR' ] ) print ( 'renderer:' , self . ctx . info [ 'GL_RENDERER' ] ) print ( 'version:' , self . ctx . info [ 'GL_VERSION' ] ) print ( 'python:' , sys . version ) print ( 'platform:' , sys . platfo...
def close ( self ) : """Closes this VPCS VM ."""
if not ( yield from super ( ) . close ( ) ) : return False nio = self . _ethernet_adapter . get_nio ( 0 ) if isinstance ( nio , NIOUDP ) : self . manager . port_manager . release_udp_port ( nio . lport , self . _project ) if self . _local_udp_tunnel : self . manager . port_manager . release_udp_port ( self ...
def resolve_json_id ( self , json_id , allow_no_match = False ) : """Given an id found in scraped JSON , return a DB id for the object . params : json _ id : id from json allow _ no _ match : just return None if id can ' t be resolved returns : database id raises : ValueError if id couldn ' t be resol...
if not json_id : return None if json_id . startswith ( '~' ) : # keep caches of all the pseudo - ids to avoid doing 1000s of lookups during import if json_id not in self . pseudo_id_cache : spec = get_pseudo_id ( json_id ) spec = self . limit_spec ( spec ) if isinstance ( spec , Q ) : ...
def make_model ( self , grounding_ontology = 'UN' , grounding_threshold = None ) : """Return a networkx MultiDiGraph representing a causal analysis graph . Parameters grounding _ ontology : Optional [ str ] The ontology from which the grounding should be taken ( e . g . UN , FAO ) grounding _ threshold : ...
if grounding_threshold is not None : self . grounding_threshold = grounding_threshold self . grounding_ontology = grounding_ontology # Filter to Influence Statements which are currently supported statements = [ stmt for stmt in self . statements if isinstance ( stmt , Influence ) ] # Initialize graph self . CAG = n...
def qualname ( self ) -> str : """Returns the fully qualified name of the class - under - construction , if possible , otherwise just the class name ."""
if self . module : return self . module + '.' + self . name return self . name
def find_codon_mismatches ( sbjct_start , sbjct_seq , qry_seq ) : """This function takes two alligned sequence ( subject and query ) , and the position on the subject where the alignment starts . The sequences are compared codon by codon . If a mis matches is found it is saved in ' mis _ matches ' . If a gap ...
mis_matches = [ ] # Find start pos of first codon in frame , i _ start codon_offset = ( sbjct_start - 1 ) % 3 i_start = 0 if codon_offset != 0 : i_start = 3 - codon_offset sbjct_start = sbjct_start + i_start # Set sequences in frame sbjct_seq = sbjct_seq [ i_start : ] qry_seq = qry_seq [ i_start : ] # Find codon nu...
def save_profile ( self , userdata , data ) : """Save user profile modifications"""
result = userdata error = False # Check if updating username . if not userdata [ "username" ] and "username" in data : if re . match ( r"^[-_|~0-9A-Z]{4,}$" , data [ "username" ] , re . IGNORECASE ) is None : error = True msg = _ ( "Invalid username format." ) elif self . database . users . find...
def add_attribute ( self , attrkey , attrvalue , append = False , oldvalue = None ) : """Add an attribute to this feature . Feature attributes are stored as nested dictionaries . Each feature can only have one ID , so ID attribute mapping is ' string ' to ' string ' . All other attributes can have multiple va...
# Handle ID / Parent relationships if attrkey == 'ID' : if self . children is not None : oldid = self . get_attribute ( 'ID' ) for child in self . children : child . add_attribute ( 'Parent' , attrvalue , oldvalue = oldid ) self . _attrs [ attrkey ] = attrvalue if self . is_multi...
def main ( ) : '''Main routine .'''
# validate command line arguments argparser = argparse . ArgumentParser ( ) argparser . add_argument ( '--uri' , '-u' , required = True , action = 'store' , help = 'Template URI' ) argparser . add_argument ( '--params' , '-f' , required = True , action = 'store' , help = 'Parameters json file' ) argparser . add_argumen...
def writeConfig ( self ) : """Persists the value of the : attr : ` AbstractJobStore . config ` attribute to the job store , so that it can be retrieved later by other instances of this class ."""
with self . writeSharedFileStream ( 'config.pickle' , isProtected = False ) as fileHandle : pickle . dump ( self . __config , fileHandle , pickle . HIGHEST_PROTOCOL )
def init_db ( ) : """Initialize a new database with the default tables for chill . Creates the following tables : Chill Node Node _ Node Route Query Template"""
with current_app . app_context ( ) : for filename in CHILL_CREATE_TABLE_FILES : db . execute ( text ( fetch_query_string ( filename ) ) )
def init_with_keytab ( self ) : """Initialize credential cache with keytab"""
creds_opts = { 'usage' : 'initiate' , 'name' : self . _cleaned_options [ 'principal' ] , } store = { } if self . _cleaned_options [ 'keytab' ] != DEFAULT_KEYTAB : store [ 'client_keytab' ] = self . _cleaned_options [ 'keytab' ] if self . _cleaned_options [ 'ccache' ] != DEFAULT_CCACHE : store [ 'ccache' ] = sel...
def write_record ( self , event_str ) : """Writes a serialized event to file ."""
header = struct . pack ( 'Q' , len ( event_str ) ) header += struct . pack ( 'I' , masked_crc32c ( header ) ) footer = struct . pack ( 'I' , masked_crc32c ( event_str ) ) self . _writer . write ( header + event_str + footer )
def scales ( scale = None ) : """Displays a color scale ( HTML ) Parameters : scale : str Color scale name If no scale name is provided then all scales are returned ( max number for each scale ) If scale = ' all ' then all scale combinations available will be returned Example : scales ( ' accent '...
if scale : if scale == 'all' : display ( HTML ( cl . to_html ( _scales ) ) ) else : display ( HTML ( cl . to_html ( get_scales ( scale ) ) ) ) else : s = '' keys = list ( _scales_names . keys ( ) ) keys . sort ( ) for k in keys : scale = get_scales ( k ) s += '<di...
def _do_anchor ( self , anchor ) : """Collects preposition anchors and attachments in a dictionary . Once the dictionary has an entry for both the anchor and the attachment , they are linked ."""
if anchor : for x in anchor . split ( "-" ) : A , P = None , None if x . startswith ( "A" ) and len ( self . chunks ) > 0 : # anchor A , P = x , x . replace ( "A" , "P" ) self . _anchors [ A ] = self . chunks [ - 1 ] if x . startswith ( "P" ) and len ( self . pnp ) > ...
def description_for_number ( numobj , lang , script = None , region = None ) : """Return a text description of a PhoneNumber object for the given language . The description might consist of the name of the country where the phone number is from and / or the name of the geographical area the phone number is fr...
ntype = number_type ( numobj ) if ntype == PhoneNumberType . UNKNOWN : return "" elif not is_number_type_geographical ( ntype , numobj . country_code ) : return country_name_for_number ( numobj , lang , script , region ) return description_for_valid_number ( numobj , lang , script , region )
def buildFinished ( self , build , wfb ) : """This is called when the Build has finished ( either success or failure ) . Any exceptions during the build are reported with results = FAILURE , not with an errback ."""
# by the time we get here , the Build has already released the worker , # which will trigger a check for any now - possible build requests # ( maybeStartBuilds ) results = build . build_status . getResults ( ) self . building . remove ( build ) if results == RETRY : d = self . _resubmit_buildreqs ( build ) d . ...
def times ( A , b , offset = 0 ) : """Times the view of A with b in place ( ! ) . Returns modified A Broadcasting is allowed , thus b can be scalar . if offset is not zero , make sure b is of right shape ! : param ndarray A : 2 dimensional array : param ndarray - like b : either one dimensional or scalar ...
return _diag_ufunc ( A , b , offset , np . multiply )
def generate_sky_catalog ( image , refwcs , ** kwargs ) : """Build source catalog from input image using photutils . This script borrows heavily from build _ source _ catalog . The catalog returned by this function includes sources found in all chips of the input image with the positions translated to the coo...
# Extract source catalogs for each chip source_cats = generate_source_catalog ( image , ** kwargs ) # Build source catalog for entire image master_cat = None numSci = countExtn ( image , extname = 'SCI' ) # if no refwcs specified , build one now . . . if refwcs is None : refwcs = build_reference_wcs ( [ image ] ) f...
def whoami ( self ) : """Return a Deferred which fires with a 2 - tuple of ( dotted quad ip , port number ) ."""
def cbWhoAmI ( result ) : return result [ 'address' ] return self . callRemote ( WhoAmI ) . addCallback ( cbWhoAmI )
def ToScriptHash ( data , unhex = True ) : """Get a script hash of the data . Args : data ( bytes ) : data to hash . unhex ( bool ) : ( Default ) True . Set to unhexlify the stream . Use when the bytes are not raw bytes ; i . e . b ' aabb ' Returns : UInt160 : script hash ."""
if len ( data ) > 1 and unhex : data = binascii . unhexlify ( data ) return UInt160 ( data = binascii . unhexlify ( bytes ( Crypto . Hash160 ( data ) , encoding = 'utf-8' ) ) )
def get_render_data ( self , ** kwargs ) : """Adds the model _ name to the context , then calls super ."""
kwargs [ 'model_name' ] = self . model_name kwargs [ 'model_name_plural' ] = self . model_name_plural return super ( ModelCMSView , self ) . get_render_data ( ** kwargs )
def ts_stream_keys ( self , table , timeout = None ) : """Streams keys from a timeseries table , returning an iterator that yields lists of keys ."""
msg_code = riak . pb . messages . MSG_CODE_TS_LIST_KEYS_REQ codec = self . _get_codec ( msg_code ) msg = codec . encode_timeseries_listkeysreq ( table , timeout ) self . _send_msg ( msg . msg_code , msg . data ) return PbufTsKeyStream ( self , codec , self . _ts_convert_timestamp )
def _start_browsing_some_sites ( self ) : '''Starts browsing some sites . Raises : NoBrowsersAvailable if none available'''
# acquire _ multi ( ) raises NoBrowsersAvailable if none available browsers = self . _browser_pool . acquire_multi ( ( self . _browser_pool . num_available ( ) + 1 ) // 2 ) try : sites = self . _frontier . claim_sites ( len ( browsers ) ) except : self . _browser_pool . release_all ( browsers ) raise for i ...
def cues ( self , rename_inhibitors = False ) : """Returns stimuli and inhibitors species of this experimental setup Parameters rename _ inhibitors : boolean If True , rename inhibitors with an ending ' i ' as in MIDAS files . Returns list List of species names in order : first stimuli followed by inhib...
if rename_inhibitors : return self . stimuli + [ i + 'i' for i in self . inhibitors ] else : return self . stimuli + self . inhibitors
def vec_angle ( vec1 , vec2 ) : """Angle between two R - dimensional vectors . Angle calculated as : . . math : : \\ arccos \\ left [ \\ frac { \\ mathsf { vec1 } \ cdot \\ mathsf { vec2 } } { \\ left \\ | \\ mathsf { vec1} \\ right \\ | \\ left \\ | \\ mathsf { vec2} \\ right \\ | } \\ right ] Para...
# Imports import numpy as np from scipy import linalg as spla from . . const import PRM # Check shape and equal length if len ( vec1 . shape ) != 1 : raise ValueError ( "'vec1' is not a vector" ) # # end if if len ( vec2 . shape ) != 1 : raise ValueError ( "'vec2' is not a vector" ) # # end if if vec1 . shape [...
async def close ( self ) -> None : """Explicit exit . Closes pool . For use when keeping pool open across multiple calls ."""
LOGGER . debug ( 'NodePool.close >>>' ) if not self . handle : LOGGER . warning ( 'Abstaining from closing pool %s: already closed' , self . name ) else : await pool . close_pool_ledger ( self . handle ) self . _handle = None LOGGER . debug ( 'NodePool.close <<<' )
def ccmod_xstep ( k ) : """Do the X step of the ccmod stage . The only parameter is the slice index ` k ` and there are no return values ; all inputs and outputs are from and to global variables ."""
YU = mp_D_Y - mp_D_U [ k ] b = mp_ZSf [ k ] + mp_drho * sl . rfftn ( YU , None , mp_cri . axisN ) Xf = sl . solvedbi_sm ( mp_Zf [ k ] , mp_drho , b , axis = mp_cri . axisM ) mp_D_X [ k ] = sl . irfftn ( Xf , mp_cri . Nv , mp_cri . axisN )
def prin ( * args , ** kwargs ) : r"""Like ` ` print ` ` , but a function . I . e . prints out all arguments as ` ` print ` ` would do . Specify output stream like this : : print ( ' ERROR ' , ` out = " sys . stderr " ` ` ) ."""
print >> kwargs . get ( 'out' , None ) , " " . join ( [ str ( arg ) for arg in args ] )
def ensure_specification_cols_are_in_dataframe ( specification , dataframe ) : """Checks whether each column in ` specification ` is in ` dataframe ` . Raises ValueError if any of the columns are not in the dataframe . Parameters specification : OrderedDict . Keys are a proper subset of the columns in ` dat...
# Make sure specification is an OrderedDict try : assert isinstance ( specification , OrderedDict ) except AssertionError : raise TypeError ( "`specification` must be an OrderedDict." ) # Make sure dataframe is a pandas dataframe assert isinstance ( dataframe , pd . DataFrame ) problem_cols = [ ] dataframe_cols...
def probe_response ( msg , arg ) : """Process responses from from the query sent by genl _ ctrl _ probe _ by _ name ( ) . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / genl / ctrl . c # L203 Process returned messages , filling out the missing information in the genl _ family structure ...
tb = dict ( ( i , None ) for i in range ( CTRL_ATTR_MAX + 1 ) ) nlh = nlmsg_hdr ( msg ) ret = arg if genlmsg_parse ( nlh , 0 , tb , CTRL_ATTR_MAX , ctrl_policy ) : return NL_SKIP if tb [ CTRL_ATTR_FAMILY_ID ] : genl_family_set_id ( ret , nla_get_u16 ( tb [ CTRL_ATTR_FAMILY_ID ] ) ) if tb [ CTRL_ATTR_MCAST_GROUP...
def parse_runway_config ( self ) : """Read and parse runway . yml ."""
if not os . path . isfile ( self . runway_config_path ) : LOGGER . error ( "Runway config file was not found (looking for " "%s)" , self . runway_config_path ) sys . exit ( 1 ) with open ( self . runway_config_path ) as data_file : return yaml . safe_load ( data_file )
def _validate_metadata ( metadata_props ) : '''Validate metadata properties and possibly show warnings or throw exceptions . : param metadata _ props : A dictionary of metadata properties , with property names and values ( see : func : ` ~ onnxmltools . utils . metadata _ props . add _ metadata _ props ` for exam...
if len ( CaseInsensitiveDict ( metadata_props ) ) != len ( metadata_props ) : raise RuntimeError ( 'Duplicate metadata props found' ) for key , value in metadata_props . items ( ) : valid_values = KNOWN_METADATA_PROPS . get ( key ) if valid_values and value . lower ( ) not in valid_values : warnings...
def set_data ( self , data = None , ** kwargs ) : '''Read data into memory , applying all actions in queue . Additionally , update queue and history .'''
if data is None : data = self . get_data ( ** kwargs ) setattr ( self , '_data' , data ) self . history += self . queue self . queue = [ ]
def rlmb_tiny_sv2p ( ) : """Tiny setting with a tiny sv2p model ."""
hparams = rlmb_ppo_tiny ( ) hparams . generative_model = "next_frame_sv2p" hparams . generative_model_params = "next_frame_sv2p_tiny" hparams . grayscale = False return hparams
def matrix_mult_opt_order ( M ) : """Matrix chain multiplication optimal order : param M : list of matrices : returns : matrices opt , arg , such that opt [ i ] [ j ] is the optimal number of operations to compute M [ i ] * . . . * M [ j ] when done in the order ( M [ i ] * . . . * M [ k ] ) * ( M [ k + 1 ]...
n = len ( M ) r = [ len ( Mi ) for Mi in M ] c = [ len ( Mi [ 0 ] ) for Mi in M ] opt = [ [ 0 for j in range ( n ) ] for i in range ( n ) ] arg = [ [ None for j in range ( n ) ] for i in range ( n ) ] for j_i in range ( 1 , n ) : # loop on i , j of increasing j - i = j _ i for i in range ( n - j_i ) : j = i...
def read_micromanager_metadata ( fh ) : """Read MicroManager non - TIFF settings from open file and return as dict . The settings can be used to read image data without parsing the TIFF file . Raise ValueError if the file does not contain valid MicroManager metadata ."""
fh . seek ( 0 ) try : byteorder = { b'II' : '<' , b'MM' : '>' } [ fh . read ( 2 ) ] except IndexError : raise ValueError ( 'not a MicroManager TIFF file' ) result = { } fh . seek ( 8 ) ( index_header , index_offset , display_header , display_offset , comments_header , comments_offset , summary_header , summary_...
def isPrefixOf ( self , other ) : """Indicate if this | ASN . 1 | object is a prefix of other | ASN . 1 | object . Parameters other : | ASN . 1 | object | ASN . 1 | object Returns : : class : ` bool ` : class : ` True ` if this | ASN . 1 | object is a parent ( e . g . prefix ) of the other | ASN . 1 | o...
l = len ( self ) if l <= len ( other ) : if self . _value [ : l ] == other [ : l ] : return True return False
def _must_not_custom_query ( issn ) : """Este metodo constroi a lista de filtros por título de periódico que será aplicada na pesquisa boleana como restrição " must _ not " . A lista de filtros é coletada do template de pesquisa customizada do periódico , quanto este template existir ."""
custom_queries = set ( [ utils . cleanup_string ( i ) for i in journal_titles . load ( issn ) . get ( 'must_not' , [ ] ) ] ) for item in custom_queries : query = { "match" : { "reference_source_cleaned" : item } } yield query
def generate_plaintext_random ( plain_vocab , distribution , train_samples , length ) : """Generates samples of text from the provided vocabulary . Args : plain _ vocab : vocabulary . distribution : distribution . train _ samples : samples for training . length : length . Returns : train _ indices ( n...
if distribution is not None : assert len ( distribution ) == len ( plain_vocab ) train_indices = np . random . choice ( range ( len ( plain_vocab ) ) , ( train_samples , length ) , p = distribution ) return train_indices
def importcmd ( self , image_path , input_source ) : '''import will import ( stdin ) to the image Parameters image _ path : path to image to import to . input _ source : input source or file import _ type : if not specified , imports whatever function is given'''
from spython . utils import check_install check_install ( ) cmd = [ 'singularity' , 'image.import' , image_path , input_source ] output = self . run_command ( cmd , sudo = False ) self . println ( output ) return image_path
def register_forward_hook ( self , hook ) : r"""Registers a forward hook on the block . The hook function is called immediately after : func : ` forward ` . It should not modify the input or output . Parameters hook : callable The forward hook function of form ` hook ( block , input , output ) - > None ` ...
handle = HookHandle ( ) handle . attach ( self . _forward_hooks , hook ) return handle
def _is_surrounded ( self , b ) : """Perform a wrapped LTE comparison only considering the SI bounds : param a : The first operand : param b : The second operand : return : True if a < = b , False otherwise"""
a = self if a . is_empty : return True if a . is_top and b . is_top : return True elif a . is_top : return False elif b . is_top : return True if b . _surrounds_member ( a . lower_bound ) and b . _surrounds_member ( a . upper_bound ) : if ( ( b . lower_bound == a . lower_bound and b . upper_bound ==...
def module_function ( string ) : """Load a function from a python module using a file name , function name specification of format : / path / to / x . py : function _ name [ : parameter ]"""
parts = string . split ( ':' , 2 ) if len ( parts ) < 2 : raise ValueError ( "Illegal specification. Should be module:function[:parameter]" ) module_path , function_name = parts [ : 2 ] # Import the module module_vars = { } exec ( compile ( open ( module_path ) . read ( ) , module_path , 'exec' ) , module_vars ) tr...
def returner ( ret ) : '''Return data to a influxdb data store'''
serv = _get_serv ( ret ) # strip the ' return ' key to avoid data duplication in the database json_return = salt . utils . json . dumps ( ret [ 'return' ] ) del ret [ 'return' ] json_full_ret = salt . utils . json . dumps ( ret ) # create legacy request in case an InfluxDB 0.8 . x version is used if "influxdb08" in ser...
def filter_seq ( seq ) : '''Examines unreserved sequences to see if they are prone to mutation . This currently ignores solely - power - of - 2 guides with b > 3'''
if seq . res : return None n = nt . Factors ( seq . factors ) guide , s , t = aq . canonical_form ( n ) seq . guide = guide # The target _ tau for the composite is at most the class minus extant prime factor count cls = aq . get_class ( guide = guide ) num_larges = seq . factors . count ( 'P' ) upper_bound_tau = cl...
def dict_merge ( dct , merge_dct ) : """Recursive dict merge . Inspired by : meth : ` ` dict . update ( ) ` ` , instead of updating only top - level keys , dict _ merge recurses down into dicts nested to an arbitrary depth , updating keys . The ` ` merge _ dct ` ` is merged into ` ` dct ` ` . : param dct : ...
for key in merge_dct . keys ( ) : if ( key in dct and isinstance ( dct [ key ] , dict ) and isinstance ( merge_dct [ key ] , collections . Mapping ) ) : dict_merge ( dct [ key ] , merge_dct [ key ] ) else : dct [ key ] = merge_dct [ key ]
def terminate ( self ) : """Delete all files created by this index , invalidating ` self ` . Use with care ."""
try : self . id2sims . terminate ( ) except : pass import glob for fname in glob . glob ( self . fname + '*' ) : try : os . remove ( fname ) logger . info ( "deleted %s" % fname ) except Exception , e : logger . warning ( "failed to delete %s: %s" % ( fname , e ) ) for val in sel...
def create_token_review ( self , body , ** kwargs ) : """create a TokenReview This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . create _ token _ review ( body , async _ req = True ) > > > result = thread . get...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . create_token_review_with_http_info ( body , ** kwargs ) else : ( data ) = self . create_token_review_with_http_info ( body , ** kwargs ) return data
def render_region_tools ( context , feincms_object , region , request = None ) : """{ % render _ region _ tools feincms _ page " main " request % } skip rendering in standalone mode"""
if context . get ( 'standalone' , False ) or not feincms_object : return { } edit = False if getattr ( settings , 'LEONARDO_USE_PAGE_ADMIN' , False ) : request = context . get ( 'request' , None ) frontend_edit = request . COOKIES . get ( 'frontend_editing' , False ) if frontend_edit : edit = Tr...