signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def copyto_emitter ( target , source , env ) : """changes the path of the source to be under the target ( which are assumed to be directories ."""
n_target = [ ] for t in target : n_target = n_target + [ t . File ( str ( s ) ) for s in source ] return ( n_target , source )
def individuals ( self , ind_ids = None ) : """Fetch all individuals from the database ."""
query = self . query ( Individual ) if ind_ids : query = query . filter ( Individual . ind_id . in_ ( ind_ids ) ) return query
def update ( self , * args ) : """Show / hide icon depending on whether there are devices ."""
if self . smart : self . _icon . show ( self . has_menu ( ) ) else : self . _icon . show ( True )
def bill ( request , abbr , session , bill_id ) : '''Context : - vote _ preview _ row _ template - abbr - metadata - bill - show _ all _ sponsors - sponsors - sources - nav _ active Templates : - billy / web / public / bill . html - billy / web / public / vote _ preview _ row . html'''
# get fixed version fixed_bill_id = fix_bill_id ( bill_id ) # redirect if URL ' s id isn ' t fixed id without spaces if fixed_bill_id . replace ( ' ' , '' ) != bill_id : return redirect ( 'bill' , abbr = abbr , session = session , bill_id = fixed_bill_id . replace ( ' ' , '' ) ) bill = db . bills . find_one ( { set...
def _series ( self , name , interval , config , buckets , ** kws ) : '''Fetch a series of buckets .'''
# make a copy of the buckets because we ' re going to mutate it buckets = list ( buckets ) rval = OrderedDict ( ) step = config [ 'step' ] resolution = config . get ( 'resolution' , step ) fetch = kws . get ( 'fetch' ) process_row = kws . get ( 'process_row' , self . _process_row ) query = { 'name' : name , 'interval' ...
def cmd_karma_bulk ( infile , jsonout , badonly , verbose ) : """Show which IP addresses are inside blacklists using the Karma online service . Example : $ cat / var / log / auth . log | habu . extract . ipv4 | habu . karma . bulk 172.217.162.4 spamhaus _ drop , alienvault _ spamming 23.52.213.96 CLEAN 19...
if verbose : logging . basicConfig ( level = logging . INFO , format = '%(message)s' ) data = infile . read ( ) result = { } for ip in data . split ( '\n' ) : if ip : logging . info ( 'Checking ' + ip ) response = karma ( ip ) if response : result [ ip ] = response el...
def long_encode ( input , errors = 'strict' ) : """Transliterate to 8 bit using as many letters as needed . For example , \u00e4 LATIN SMALL LETTER A WITH DIAERESIS ` ` ä ` ` will be replaced with ` ` ae ` ` ."""
if not isinstance ( input , text_type ) : input = text_type ( input , sys . getdefaultencoding ( ) , errors ) length = len ( input ) input = unicodedata . normalize ( 'NFKC' , input ) return input . translate ( long_table ) , length
def _generate_enumerated_subtypes_tag_mapping ( self , ns , data_type ) : """Generates attributes needed for serializing and deserializing structs with enumerated subtypes . These assignments are made after all the Python class definitions to ensure that all references exist ."""
assert data_type . has_enumerated_subtypes ( ) # Generate _ tag _ to _ subtype _ attribute : Map from string type tag to # the validator of the referenced subtype . Used on deserialization # to look up the subtype for a given tag . tag_to_subtype_items = [ ] for tags , subtype in data_type . get_all_subtypes_with_tags ...
def byteswap ( self , fmt = None , start = None , end = None , repeat = True ) : """Change the endianness in - place . Return number of repeats of fmt done . fmt - - A compact structure string , an integer number of bytes or an iterable of integers . Defaults to 0 , which byte reverses the whole bitstring . ...
start , end = self . _validate_slice ( start , end ) if fmt is None or fmt == 0 : # reverse all of the whole bytes . bytesizes = [ ( end - start ) // 8 ] elif isinstance ( fmt , numbers . Integral ) : if fmt < 0 : raise ValueError ( "Improper byte length {0}." . format ( fmt ) ) bytesizes = [ fmt ] ...
def query ( self , query , fetchall = False , ** params ) : """Executes the given SQL query against the Database . Parameters can , optionally , be provided . Returns a RecordCollection , which can be iterated over to get result rows as dictionaries ."""
with self . get_connection ( ) as conn : return conn . query ( query , fetchall , ** params )
def attach_internet_gateway ( self , internet_gateway_id , vpc_id ) : """Attach an internet gateway to a specific VPC . : type internet _ gateway _ id : str : param internet _ gateway _ id : The ID of the internet gateway to delete . : type vpc _ id : str : param vpc _ id : The ID of the VPC to attach to . ...
params = { 'InternetGatewayId' : internet_gateway_id , 'VpcId' : vpc_id } return self . get_status ( 'AttachInternetGateway' , params )
def RWSelection ( self , mating_pool_size ) : '''Make Selection of the mating pool with the roulette wheel algorithm'''
A = numpy . zeros ( self . length ) mating_pool = numpy . zeros ( mating_pool_size ) [ F , S , P ] = self . rankingEval ( ) P_Sorted = numpy . zeros ( self . length ) for i in range ( self . length ) : P_Sorted [ i ] = P [ S [ i ] ] for i in range ( self . length ) : A [ i ] = P_Sorted [ 0 : ( i + 1 ) ] . sum (...
def _load_response ( response ) : '''Load the response from json data , return the dictionary or raw text'''
try : data = salt . utils . json . loads ( response . text ) except ValueError : data = response . text ret = { 'code' : response . status_code , 'content' : data } return ret
def _save_states ( self , state , serialized_readers_entity ) : """Run transaction to save state . Args : state : a model . MapreduceState entity . serialized _ readers _ entity : a model . _ HugeTaskPayload entity containing json serialized input readers . Returns : False if a fatal error is encountere...
mr_id = state . key ( ) . id_or_name ( ) fresh_state = model . MapreduceState . get_by_job_id ( mr_id ) if not self . _check_mr_state ( fresh_state , mr_id ) : return False if fresh_state . active_shards != 0 : logging . warning ( "Mapreduce %s already has active shards. Looks like spurious task " "execution." ...
def _parse_usage ( tag , parser , parent ) : """Parses a < usage > tag and adds it the Executable parent instance . : arg parser : an instance of DocParser to create the DocElement with ."""
usage = DocElement ( tag , parser , parent ) parent . docstring . append ( usage )
def bridge_param ( _param , _method , * args , ** kwargs ) : """Used as a callback to keep the result from the previous callback and use that instead of the result of the given callback when chaining to the next callback in the fiber ."""
assert callable ( _method ) , "method %r is not callable" % ( _method , ) f = Fiber ( debug_depth = 1 , debug_call = _method ) f . add_callback ( drop_param , _method , * args , ** kwargs ) f . add_callback ( override_result , _param ) return f . succeed ( )
def _get_request ( self , request_url , request_method , ** params ) : """Return a Request object that has the GET parameters attached to the url or the POST data attached to the object ."""
if request_method == 'GET' : if params : request_url += '&%s' % urlencode ( params ) request = Request ( request_url ) elif request_method == 'POST' : request = Request ( request_url , urlencode ( params , doseq = 1 ) ) return request
def frequency_axis ( self ) : """Returns an array of frequencies in Hertz ranging from - sw / 2 to sw / 2. : return : an array of frequencies in Hertz ranging from - sw / 2 to sw / 2."""
return numpy . linspace ( - self . sw / 2 , self . sw / 2 , self . np , endpoint = False )
def doit ( self ) : """Do ( most of ) it function of the model class ."""
print ( ' . doit' ) lines = Lines ( ) lines . add ( 1 , 'cpdef inline void doit(self, int idx) %s:' % _nogil ) lines . add ( 2 , 'self.idx_sim = idx' ) if getattr ( self . model . sequences , 'inputs' , None ) is not None : lines . add ( 2 , 'self.load_data()' ) if self . model . INLET_METHODS : ...
def _sign_input ( cls , input_ , message , key_pairs ) : """Signs a single Input . Note : This method works only for the following Cryptoconditions currently : - Ed25519Fulfillment - ThresholdSha256. Args : input _ ( : class : ` ~ bigchaindb . common . transaction . Input ` ) The Input to be signed ...
if isinstance ( input_ . fulfillment , Ed25519Sha256 ) : return cls . _sign_simple_signature_fulfillment ( input_ , message , key_pairs ) elif isinstance ( input_ . fulfillment , ThresholdSha256 ) : return cls . _sign_threshold_signature_fulfillment ( input_ , message , key_pairs ) else : raise ValueError (...
def atmost ( cls , lits , bound = 1 , top_id = None , encoding = EncType . seqcounter ) : """This method can be used for creating a CNF encoding of an AtMostK constraint , i . e . of : math : ` \ sum _ { i = 1 } ^ { n } { x _ i } \ leq k ` . The method shares the arguments and the return type with method : me...
if encoding < 0 or encoding > 9 : raise ( NoSuchEncodingError ( encoding ) ) if not top_id : top_id = max ( map ( lambda x : abs ( x ) , lits ) ) # we are going to return this formula ret = CNFPlus ( ) # MiniCard ' s native representation is handled separately if encoding == 9 : ret . atmosts , ret . nv = [...
def connect_model ( self , model ) : """Link the Database to the Model instance . In case a new database is created from scratch , ` ` connect _ model ` ` creates Trace objects for all tallyable pymc objects defined in ` model ` . If the database is being loaded from an existing file , ` ` connect _ model `...
# Changed this to allow non - Model models . - AP # We could also remove it altogether . - DH if isinstance ( model , pymc . Model ) : self . model = model else : raise AttributeError ( 'Not a Model instance.' ) # Restore the state of the Model from an existing Database . # The ` load ` method will have already...
def get_online_symbol_data ( database_id ) : """Get from the server ."""
import pymysql import pymysql . cursors cfg = get_database_configuration ( ) mysql = cfg [ 'mysql_online' ] connection = pymysql . connect ( host = mysql [ 'host' ] , user = mysql [ 'user' ] , passwd = mysql [ 'passwd' ] , db = mysql [ 'db' ] , cursorclass = pymysql . cursors . DictCursor ) cursor = connection . cursor...
def rename_component ( self , old_component , new_component ) : """Change the label of a component attached to the Bundle : parameter str old _ component : the current name of the component ( must exist ) : parameter str new _ component : the desired new name of the component ( must not exist ) : return :...
# TODO : raise error if old _ component not found ? # even though _ rename _ tag will call _ check _ label again , we should # do it first so that we can raise any errors BEFORE we start messing # with the hierarchy self . _check_label ( new_component ) # changing hierarchy must be called first since it needs to access...
def user_login_failed ( self , sender , credentials : dict , request : AxesHttpRequest = None , ** kwargs ) : # pylint : disable = too - many - locals """When user login fails , save attempt record in cache and lock user out if necessary . : raises AxesSignalPermissionDenied : if user should be locked out ."""
if request is None : log . error ( 'AXES: AxesCacheHandler.user_login_failed does not function without a request.' ) return username = get_client_username ( request , credentials ) client_str = get_client_str ( username , request . axes_ip_address , request . axes_user_agent , request . axes_path_info ) if self...
def add ( self , cell , overwrite_duplicate = False ) : """Add one or more cells to the library . Parameters cell : ` ` Cell ` ` of list of ` ` Cell ` ` Cells to be included in the library . overwrite _ duplicate : bool If True an existing cell with the same name in the library will be overwritten . R...
if isinstance ( cell , Cell ) : if ( not overwrite_duplicate and cell . name in self . cell_dict and self . cell_dict [ cell . name ] is not cell ) : raise ValueError ( "[GDSPY] cell named {0} already present in " "library." . format ( cell . name ) ) self . cell_dict [ cell . name ] = cell else : f...
def add_rel ( self , rId , reltype , target , is_external = False ) : """Add a child ` ` < Relationship > ` ` element with attributes set according to parameter values ."""
target_mode = RTM . EXTERNAL if is_external else RTM . INTERNAL relationship = CT_Relationship . new ( rId , reltype , target , target_mode ) self . append ( relationship )
def load_table ( self , table_name ) : """Load a table . This will fail if the tables does not already exist in the database . If the table exists , its columns will be reflected and are available on the : py : class : ` Table < dataset . Table > ` object . Returns a : py : class : ` Table < dataset . Table...
table_name = normalize_table_name ( table_name ) with self . lock : if table_name not in self . _tables : self . _tables [ table_name ] = Table ( self , table_name ) return self . _tables . get ( table_name )
def _set_name ( self , version = AUTO ) : """Returns plugin name ."""
name = 'python' if version : if version is AUTO : version = sys . version_info [ 0 ] if version == 2 : version = '' name = '%s%s' % ( name , version ) self . name = name
def gather_facts_list ( self , file ) : """Return a list of facts ."""
facts = [ ] contents = utils . file_to_string ( os . path . join ( self . paths [ "role" ] , file ) ) contents = re . sub ( r"\s+" , "" , contents ) matches = self . regex_facts . findall ( contents ) for match in matches : facts . append ( match . split ( ":" ) [ 1 ] ) return facts
def interfaces ( ) : """Gets the network interfaces on this server . : returns : list of network interfaces"""
results = [ ] if not sys . platform . startswith ( "win" ) : net_if_addrs = psutil . net_if_addrs ( ) for interface in sorted ( net_if_addrs . keys ( ) ) : ip_address = "" mac_address = "" netmask = "" interface_type = "ethernet" for addr in net_if_addrs [ interface ] : #...
def validate_regions_schema ( self , data ) : """Performs field validation for regions . This should be a dict with region names as the key and RegionSchema as the value"""
region_schema = RegionSchema ( ) supplied_regions = data . get ( 'regions' , { } ) for region in supplied_regions . keys ( ) : result = region_schema . validate ( supplied_regions [ region ] ) if len ( result . keys ( ) ) > 0 : raise ValidationError ( result )
def parse_table ( document , tbl ) : "Parse table element ."
def _change ( rows , pos_x ) : if len ( rows ) == 1 : return rows count_x = 1 for x in rows [ - 1 ] : if count_x == pos_x : x . row_span += 1 count_x += x . grid_span return rows table = doc . Table ( ) tbl_pr = tbl . find ( _name ( '{{{w}}}tblPr' ) ) if tbl_pr is not...
def read_interactions ( path , comments = "#" , directed = False , delimiter = None , nodetype = None , timestamptype = None , encoding = 'utf-8' , keys = False ) : """Read a DyNetx graph from interaction list format . Parameters path : basestring The desired output filename delimiter : character Column d...
ids = None lines = ( line . decode ( encoding ) for line in path ) if keys : ids = read_ids ( path . name , delimiter = delimiter , timestamptype = timestamptype ) return parse_interactions ( lines , comments = comments , directed = directed , delimiter = delimiter , nodetype = nodetype , timestamptype = timestampt...
def split ( args ) : """% prog split barcodefile fastqfile1 . . Deconvolute fastq files into subsets of fastq reads , based on the barcodes in the barcodefile , which is a two - column file like : ID01AGTCCAG Input fastqfiles can be several files . Output files are ID01 . fastq , ID02 . fastq , one file p...
p = OptionParser ( split . __doc__ ) p . set_outdir ( outdir = "deconv" ) p . add_option ( "--nocheckprefix" , default = False , action = "store_true" , help = "Don't check shared prefix [default: %default]" ) p . add_option ( "--paired" , default = False , action = "store_true" , help = "Paired-end data [default: %def...
def get_all_keys ( self , headers = None , ** params ) : """A lower - level method for listing contents of a bucket . This closely models the actual S3 API and requires you to manually handle the paging of results . For a higher - level method that handles the details of paging for you , you can use the list ...
return self . _get_all ( [ ( 'Contents' , self . key_class ) , ( 'CommonPrefixes' , Prefix ) ] , '' , headers , ** params )
def to_bytes ( self , frame , state ) : """Convert a single frame into bytes that can be transmitted on the stream . : param frame : The frame to convert . Should be the same type of object returned by ` ` to _ frame ( ) ` ` . : param state : An instance of ` ` FramerState ` ` . This object may be used to...
# Generate and return the frame return ( self . begin + self . nop . join ( six . binary_type ( frame ) . split ( self . prefix ) ) + self . end )
def set_ortho_choice ( self , small_asset_data , large_asset_data , name = 'Choice' ) : """stub"""
o3d_asset_id = self . create_o3d_asset ( manip = None , small_ov_set = small_asset_data , large_ov_set = large_asset_data , display_name = name ) self . add_choice ( o3d_asset_id , name = name )
def is_on_curve ( self , point ) : """Checks whether a point is on the curve . Args : point ( AffinePoint ) : Point to be checked . Returns : bool : True if point is on the curve , False otherwise ."""
X , Y = point . X , point . Y return ( pow ( Y , 2 , self . P ) - pow ( X , 3 , self . P ) - self . a * X - self . b ) % self . P == 0
def save_save_state ( self , data_dict : Dict [ str , LinkItem ] ) : # TODO : add progressbar """Save meta data about the downloaded things and the plugin to file . : param data _ dict : data : type data _ dict : Dict [ link , ~ unidown . plugin . link _ item . LinkItem ]"""
json_data = json_format . MessageToJson ( self . _create_save_state ( data_dict ) . to_protobuf ( ) ) with self . _save_state_file . open ( mode = 'w' , encoding = "utf8" ) as writer : writer . write ( json_data )
async def debug ( self , conn_id , name , cmd_args ) : """Send a debug command to a device . See : meth : ` AbstractDeviceAdapter . debug ` ."""
progress_callback = functools . partial ( _on_progress , self , 'debug' , conn_id ) resp = await self . _execute ( self . _adapter . debug_sync , conn_id , name , cmd_args , progress_callback ) _raise_error ( conn_id , 'send_rpc' , resp ) return resp . get ( 'return_value' )
def FixedOffset ( offset , _tzinfos = { } ) : """return a fixed - offset timezone based off a number of minutes . > > > one = FixedOffset ( - 330) > > > one pytz . FixedOffset ( - 330) > > > one . utcoffset ( datetime . datetime . now ( ) ) datetime . timedelta ( - 1 , 66600) > > > one . dst ( datetime ...
if offset == 0 : return UTC info = _tzinfos . get ( offset ) if info is None : # We haven ' t seen this one before . we need to save it . # Use setdefault to avoid a race condition and make sure we have # only one info = _tzinfos . setdefault ( offset , _FixedOffset ( offset ) ) return info
def _read_dataframes_20M ( path ) : """reads in the movielens 20M"""
import pandas ratings = pandas . read_csv ( os . path . join ( path , "ratings.csv" ) ) movies = pandas . read_csv ( os . path . join ( path , "movies.csv" ) ) return ratings , movies
def nest ( self , verb ) : """Add a TwiML doc . Unlike ` append ( ) ` , this returns the created verb . : param verb : TwiML Document : returns : the TwiML verb"""
if not isinstance ( verb , TwiML ) and not isinstance ( verb , str ) : raise TwiMLException ( 'Only nesting of TwiML and strings are allowed' ) self . verbs . append ( verb ) return verb
def setClockShowDate ( kvalue , ** kwargs ) : '''Set whether the date is visible in the clock CLI Example : . . code - block : : bash salt ' * ' gnome . setClockShowDate < True | False > user = < username >'''
if kvalue is not True and kvalue is not False : return False _gsession = _GSettings ( user = kwargs . get ( 'user' ) , schema = 'org.gnome.desktop.interface' , key = 'clock-show-date' ) return _gsession . _set ( kvalue )
def fill_phenotype_calls ( self , phenotypes = None , inplace = False ) : """Set the phenotype _ calls according to the phenotype names"""
if phenotypes is None : phenotypes = list ( self [ 'phenotype_label' ] . unique ( ) ) def _get_calls ( label , phenos ) : d = dict ( [ ( x , 0 ) for x in phenos ] ) if label != label : return d # np . nan case d [ label ] = 1 return d if inplace : self [ 'phenotype_calls' ] = sel...
def get_barcode_read_id ( read , cell_barcode = False , sep = "_" ) : '''extract the umi + / - cell barcode from the read id using the specified separator'''
try : if cell_barcode : umi = read . qname . split ( sep ) [ - 1 ] . encode ( 'utf-8' ) cell = read . qname . split ( sep ) [ - 2 ] . encode ( 'utf-8' ) else : umi = read . qname . split ( sep ) [ - 1 ] . encode ( 'utf-8' ) cell = None return umi , cell except : raise Val...
def param_show ( self , param , l = False ) : """param . show [ - l ] [ param ] Display a list if run - time parameters and their values . If the - l option is specified , the list includes a brief explanation of each parameter . If a param is specified , display only the value and explanation for this parame...
cmd = 'param.show ' if l : cmd += '-l ' return self . fetch ( cmd + param )
def triangulate ( dataset ) : """Returns an all triangle mesh . More complex polygons will be broken down into triangles . Returns mesh : vtki . UnstructuredGrid Mesh containing only triangles ."""
alg = vtk . vtkDataSetTriangleFilter ( ) alg . SetInputData ( dataset ) alg . Update ( ) return _get_output ( alg )
def rmsd_eval ( cls , specification , sequences , parameters , reference_ampal , ** kwargs ) : """Creates optimizer with default build and RMSD eval . Notes Any keyword arguments will be propagated down to BaseOptimizer . RMSD eval is restricted to a single core only , due to restrictions on closure picklin...
eval_fn = make_rmsd_eval ( reference_ampal ) instance = cls ( specification , sequences , parameters , build_fn = default_build , eval_fn = eval_fn , mp_disabled = True , ** kwargs ) return instance
def get ( company = '' , company_uri = '' ) : """Performs a HTTP GET for a glassdoor page and returns json"""
if not company and not company_uri : raise Exception ( "glassdoor.gd.get(company='', company_uri=''): " " company or company_uri required" ) payload = { } if not company_uri : payload . update ( { 'clickSource' : 'searchBtn' , 'sc.keyword' : company } ) uri = '%s/%s' % ( GLASSDOOR_API , REVIEWS_URL ) else :...
def _fast_shake ( self , x , normals , values , error ) : '''Take an efficient ( not always robust ) step towards the constraints . Arguments : | ` ` x ` ` - - The unknowns . | ` ` normals ` ` - - A numpy array with the gradients of the active constraints . Each row is one gradient . | ` ` values ` ` - - ...
# filter out the degrees of freedom that do not feel the constraints . mask = ( normals != 0 ) . any ( axis = 0 ) > 0 normals = normals [ : , mask ] # Take a step to lower the constraint cost function . If the step is too # large , it is reduced iteratively towards a small steepest descent # step . This is very similar...
def environ_setting ( name , default = None , required = True ) : """Fetch setting from the environment . The bahavior of the setting if it is not in environment is as follows : 1 . If it is required and the default is None , raise Exception 2 . If it is requried and a default exists , return default 3 . If...
if name not in os . environ and default is None : message = "The {0} ENVVAR is not set." . format ( name ) if required : raise ImproperlyConfigured ( message ) else : warnings . warn ( ConfigurationMissing ( message ) ) return os . environ . get ( name , default )
def _iter_errors_custom ( instance , checks , options ) : """Perform additional validation not possible merely with JSON schemas . Args : instance : The STIX object to be validated . checks : A sequence of callables which do the checks . Each callable may be written to accept 1 arg , which is the object to ...
# Perform validation for v_function in checks : try : result = v_function ( instance ) except TypeError : result = v_function ( instance , options ) if isinstance ( result , Iterable ) : for x in result : yield x elif result is not None : yield result # Valida...
def make_form ( fields = None , layout = None , layout_class = None , base_class = None , get_form_field = None , name = None , rules = None , ** kwargs ) : """Make a from according dict data : { ' fields ' : [ { ' name ' : ' name ' , ' type ' : ' str ' , ' label ' : ' label , ' rules ' : { ' required ' : ...
from uliweb . utils . sorteddict import SortedDict get_form_field = get_form_field or ( lambda name , f : None ) # make fields props = SortedDict ( { } ) for f in fields or [ ] : if isinstance ( f , BaseField ) : props [ f . name ] = get_form_field ( f . name , f ) or f else : props [ f [ 'name'...
def write ( settings_path , settings_data , ** kwargs ) : """Write data to . env file"""
for key , value in settings_data . items ( ) : dotenv_cli . set_key ( str ( settings_path ) , key . upper ( ) , str ( value ) )
def run ( self , repo : str , branch : str , task : Task , git_repo : Repo , repo_path : Path ) -> Result : """Gets or builds an image for the repo , gets or starts a container for the image and runs the script . : param repo : Repository URL : param branch : Branch ane : param task : : class : ` Task ` to ru...
self . check_docker_access ( ) container_name = self . get_container_name ( repo , branch , git_repo ) container = self . container_running ( container_name ) if container is None : image = self . get_image_for_repo ( repo , branch , git_repo , repo_path ) container = self . start_container ( image , container_...
def doActionFor ( instance , action_id , idxs = None ) : """Tries to perform the transition to the instance . Object is reindexed after the transition takes place , but only if succeeds . If idxs is set , only these indexes will be reindexed . Otherwise , will try to use the indexes defined in ACTIONS _ TO _ ...
if not instance : return False , "" if isinstance ( instance , list ) : # TODO Workflow . Check if this is strictly necessary # This check is here because sometimes Plone creates a list # from submitted form elements . logger . warn ( "Got a list of obj in doActionFor!" ) if len ( instance ) > 1 : l...
def do_stored_procedure_check ( self , instance , proc ) : """Fetch the metrics from the stored proc"""
guardSql = instance . get ( 'proc_only_if' ) custom_tags = instance . get ( "tags" , [ ] ) if ( guardSql and self . proc_check_guard ( instance , guardSql ) ) or not guardSql : self . open_db_connections ( instance , self . DEFAULT_DB_KEY ) cursor = self . get_cursor ( instance , self . DEFAULT_DB_KEY ) try...
def itemChange ( self , change , value ) : """Overloads the base QGraphicsItem itemChange method to block user ability to move along the y - axis . : param change < int > : param value < variant > : return < variant >"""
# only operate when it is a visible , geometric change if not ( self . isVisible ( ) and change == self . ItemPositionChange ) : return super ( XGanttViewItem , self ) . itemChange ( change , value ) if self . isSyncing ( ) : return super ( XGanttViewItem , self ) . itemChange ( change , value ) scene = self . ...
def imshow ( arr , x = None , ax = None , vmin = None , vmax = None , percentile = True , strip = False , features = None , conf = 0.95 , sort_by = None , line_kwargs = None , fill_kwargs = None , imshow_kwargs = None , figsize = ( 5 , 12 ) , width_ratios = ( 4 , 1 ) , height_ratios = ( 4 , 1 ) , subplot_params = dict ...
if ax is None : fig = new_shell ( figsize = figsize , strip = strip , subplot_params = subplot_params , width_ratios = width_ratios , height_ratios = height_ratios ) if x is None : x = np . arange ( arr . shape [ 1 ] + 1 ) if percentile : if vmin is None : vmin = arr . min ( ) else : vmi...
def _request ( self , method , path , op , expected_status = httplib . OK , ** kwargs ) : """Make a WebHDFS request against the NameNodes This function handles NameNode failover and error checking . All kwargs are passed as query params to the WebHDFS server ."""
hosts , path = self . _parse_path ( path ) _transform_user_name_key ( kwargs ) kwargs . setdefault ( 'user.name' , self . user_name ) formatted_args = ' ' . join ( '{}={}' . format ( * t ) for t in kwargs . items ( ) ) _logger . info ( "%s %s %s %s" , op , path , formatted_args , ',' . join ( hosts ) ) kwargs [ 'op' ] ...
def single_or_default ( self , default , predicate = None ) : '''The only element ( which satisfies a condition ) or a default . If the predicate is omitted or is None this query returns the only element in the sequence ; otherwise , it returns the only element in the sequence for which the predicate evaluate...
if self . closed ( ) : raise ValueError ( "Attempt to call single_or_default() on a closed Queryable." ) return self . _single_or_default ( default ) if predicate is None else self . _single_or_default_predicate ( default , predicate )
def load_steps_impl ( self , registry , path , module_names = None ) : """Load the step implementations at the given path , with the given module names . If module _ names is None then the module ' steps ' is searched by default ."""
if not module_names : module_names = [ 'steps' ] path = os . path . abspath ( path ) for module_name in module_names : mod = self . modules . get ( ( path , module_name ) ) if mod is None : # log . debug ( " Looking for step def module ' % s ' in % s " % ( module _ name , path ) ) cwd = os . getcwd ...
def on_mouse_wheel ( self , event ) : '''handle mouse wheel zoom changes'''
rotation = event . GetWheelRotation ( ) / event . GetWheelDelta ( ) if rotation > 0 : zoom = 1.0 / ( 1.1 * rotation ) elif rotation < 0 : zoom = 1.1 * ( - rotation ) self . change_zoom ( zoom ) self . redraw_map ( )
def remove_directories ( self , directories ) : """Removes any ` directories ` from the set of plugin directories . ` directories ` may be a single object or an iterable . Recommend passing in all paths as absolute , but the method will attemmpt to convert all paths to absolute if they are not already based...
directories = util . to_absolute_paths ( directories ) self . plugin_directories = util . remove_from_set ( self . plugin_directories , directories )
def check_job_status ( self , key = JobDetails . topkey , fail_running = False , fail_pending = False , force_check = False ) : """Check the status of a particular job By default this checks the status of the top - level job , but can by made to drill into the sub - jobs . Parameters key : str Key associa...
if key in self . jobs : status = self . jobs [ key ] . status if status in [ JobStatus . unknown , JobStatus . ready , JobStatus . pending , JobStatus . running ] or force_check : status = self . _interface . check_job ( self . jobs [ key ] ) if status == JobStatus . running and fail_running : ...
def collinear ( args ) : """% prog collinear a . b . anchors Reduce synteny blocks to strictly collinear , use dynamic programming in a procedure similar to DAGchainer ."""
p = OptionParser ( collinear . __doc__ ) p . set_beds ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) anchorfile , = args qbed , sbed , qorder , sorder , is_self = check_beds ( anchorfile , p , opts ) af = AnchorFile ( anchorfile ) newanchorfile = anchorfile . ...
def _listify ( x ) : """Ensure x is iterable ; if not then enclose it in a list and return it ."""
if isinstance ( x , string_types ) : return [ x ] elif isinstance ( x , collections . Iterable ) : return x else : return [ x ]
def load_profile ( self , profile_name ) : """Load user profiles from file ."""
data = self . storage . get_user_profiles ( profile_name ) for x in data . get_user_views ( ) : self . _graph . add_edge ( int ( x [ 0 ] ) , int ( x [ 1 ] ) , { 'weight' : float ( x [ 2 ] ) } ) self . all_records [ int ( x [ 1 ] ) ] += 1 return self . _graph
def perform_content_negotiation ( self , request , force = False ) : """Determine which renderer and media type to use render the response ."""
renderers = self . get_renderers ( ) conneg = self . get_content_negotiator ( ) try : return conneg . select_renderer ( request , renderers , self . format_kwarg ) except Exception : if force : return ( renderers [ 0 ] , renderers [ 0 ] . media_type ) raise
def get_author_by_name ( self , name : str ) -> Optional [ Author ] : """Get an author by name , if it exists in the database ."""
return self . session . query ( Author ) . filter ( Author . has_name ( name ) ) . one_or_none ( )
def add_outer_solar_system ( sim ) : """Add the planet of the outer Solar System as a test problem . Data taken from NASA Horizons ."""
Gfac = 1. / 0.01720209895 # Gaussian constant if sim . G is not None : Gfac *= math . sqrt ( sim . G ) sim . add ( m = 1.00000597682 , x = - 4.06428567034226e-3 , y = - 6.08813756435987e-3 , z = - 1.66162304225834e-6 , vx = + 6.69048890636161e-6 * Gfac , vy = - 6.33922479583593e-6 * Gfac , vz = - 3.13202145590767e-...
def create_dataset ( self , dataset_id , friendly_name = None , description = None , access = None , location = None , project_id = None ) : """Create a new BigQuery dataset . Parameters dataset _ id : str Unique ` ` str ` ` identifying the dataset with the project ( the referenceID of the dataset , not the...
project_id = self . _get_project_id ( project_id ) try : datasets = self . bigquery . datasets ( ) dataset_data = self . dataset_resource ( dataset_id , project_id = project_id , friendly_name = friendly_name , description = description , access = access , location = location ) response = datasets . insert ...
def to_mask ( obj , m = None , indices = None ) : '''to _ mask ( obj , m ) yields the set of indices from the given vertex - set or itable object obj that correspond to the given mask m . to _ mask ( ( obj , m ) ) is equivalent to to _ mask ( obj , m ) . The mask m may take any of the following forms : * a ...
if not pimms . is_map ( obj ) and pimms . is_vector ( obj ) and len ( obj ) < 4 and m is None : if len ( obj ) == 1 : obj = obj [ 0 ] elif len ( obj ) == 2 : ( obj , m ) = obj else : ( obj , m , q ) = obj if indices is None : if pimms . is_map ( q ) : ...
def product_path ( cls , project , location , product ) : """Return a fully - qualified product string ."""
return google . api_core . path_template . expand ( "projects/{project}/locations/{location}/products/{product}" , project = project , location = location , product = product , )
def validate ( path , format = 'json' , approved_applications = None , determined = True , listed = True , expectation = PACKAGE_ANY , for_appversions = None , overrides = None , timeout = - 1 , compat_test = False , ** kw ) : """Perform validation in one easy step ! ` path ` : * Required * A file system path...
bundle = ErrorBundle ( listed = listed , determined = determined , overrides = overrides , for_appversions = for_appversions ) bundle . save_resource ( 'is_compat_test' , compat_test ) if approved_applications is None : approved_applications = os . path . join ( os . path . dirname ( __file__ ) , 'app_versions.json...
def recall_at_precision ( y_true , y_pred , precision ) : """Recall at a certain precision threshold Args : y _ true : true labels y _ pred : predicted labels precision : resired precision level at which where to compute the recall"""
y_true , y_pred = _mask_value_nan ( y_true , y_pred ) precision , recall , _ = skm . precision_recall_curve ( y_true , y_pred ) return recall [ np . searchsorted ( precision - precision , 0 ) ]
def extend_request_args ( self , args , item_cls , item_type , key , parameters , orig = False ) : """Add a set of parameters and their value to a set of request arguments . : param args : A dictionary : param item _ cls : The : py : class : ` oidcmsg . message . Message ` subclass that describes the item :...
try : item = self . get_item ( item_cls , item_type , key ) except KeyError : pass else : for parameter in parameters : if orig : try : args [ parameter ] = item [ parameter ] except KeyError : pass else : try : ...
def inject_context ( context ) : """Updates context . json with data from JSON - string given as param . : param context : : return :"""
context_path = tasks . get_context_path ( ) try : new_context = json . loads ( context ) except ValueError : print ( 'Couldn\'t load context parameter' ) return with open ( context_path ) as jsonfile : try : jsondata = json . loads ( jsonfile . read ( ) ) jsondata . update ( new_context ...
def populate ( self , max_wait = 2.0 , wait_for_complete = True , query_cl = None ) : """Retrieves the actual tracing details from Cassandra and populates the attributes of this instance . Because tracing details are stored asynchronously by Cassandra , this may need to retry the session detail fetch . If the...
attempt = 0 start = time . time ( ) while True : time_spent = time . time ( ) - start if max_wait is not None and time_spent >= max_wait : raise TraceUnavailable ( "Trace information was not available within %f seconds. Consider raising Session.max_trace_wait." % ( max_wait , ) ) log . debug ( "Atte...
def groupByKeyAndWindow ( self , windowDuration , slideDuration , numPartitions = None ) : """Return a new DStream by applying ` groupByKey ` over a sliding window . Similar to ` DStream . groupByKey ( ) ` , but applies it over a sliding window . @ param windowDuration : width of the window ; must be a multiple...
ls = self . mapValues ( lambda x : [ x ] ) grouped = ls . reduceByKeyAndWindow ( lambda a , b : a . extend ( b ) or a , lambda a , b : a [ len ( b ) : ] , windowDuration , slideDuration , numPartitions ) return grouped . mapValues ( ResultIterable )
def iter_ancestors ( self ) : """Iterates over the list of all ancestor nodes from current node to the current tree root ."""
node = self while node . up is not None : yield node . up node = node . up
def index ( self , attr ) : """Indexes the : class : ` . Paper ` \ s in this : class : ` . Corpus ` instance by the attribute ` ` attr ` ` . New indices are added to : attr : ` . indices ` \ . Parameters attr : str The name of a : class : ` . Paper ` attribute ."""
for i , paper in self . indexed_papers . iteritems ( ) : self . index_paper_by_attr ( paper , attr )
def process_request ( self , request ) : '''checks if the host domain is one of the site objects and sets request . site _ id'''
site_id = 0 domain = request . get_host ( ) . lower ( ) if hasattr ( settings , 'SITE_ID' ) : site_id = settings . SITE_ID try : site = Site . objects . get ( domain__iexact = domain ) site_id = site . id except Site . DoesNotExist : pass request . site_id = site_id
def _get_format ( self , token ) : """Returns a QTextCharFormat for token or None ."""
if token in self . _formats : return self . _formats [ token ] result = self . _get_format_from_style ( token , self . _style ) self . _formats [ token ] = result return result
async def handle_frame ( self , frame ) : """Handle incoming API frame , return True if this was the expected frame ."""
if isinstance ( frame , FrameCommandSendConfirmation ) and frame . session_id == self . session_id : if frame . status == CommandSendConfirmationStatus . ACCEPTED : self . success = True return not self . wait_for_completion if isinstance ( frame , FrameCommandRemainingTimeNotification ) and frame . ses...
def get_query_string ( environ ) : """Returns the ` QUERY _ STRING ` from the WSGI environment . This also takes care about the WSGI decoding dance on Python 3 environments as a native string . The string returned will be restricted to ASCII characters . . . versionadded : : 0.9 : param environ : the WSGI...
qs = wsgi_get_bytes ( environ . get ( "QUERY_STRING" , "" ) ) # QUERY _ STRING really should be ascii safe but some browsers # will send us some unicode stuff ( I am looking at you IE ) . # In that case we want to urllib quote it badly . return try_coerce_native ( url_quote ( qs , safe = ":&%=+$!*'()," ) )
def to_json ( self , labels = None ) : """Convert LogEvent object to valid JSON ."""
output = self . to_dict ( labels ) return json . dumps ( output , cls = DateTimeEncoder , ensure_ascii = False )
def list_notes ( self , page = 0 , since = None ) : """Get the notes of current object : param page : the page starting at 0 : type since : int : param since : get all notes since a datetime : type since : datetime . datetime : return : the notes : rtype : list"""
from highton . models . note import Note params = { 'n' : int ( page ) * self . NOTES_OFFSET } if since : params [ 'since' ] = since . strftime ( self . COLLECTION_DATETIME ) return fields . ListField ( name = self . ENDPOINT , init_class = Note ) . decode ( self . element_from_string ( self . _get_request ( endpoi...
def _validate ( self ) : """Validate the input data ."""
if self . data_format is FormatType . PYTHON : self . data = self . raw_data elif self . data_format is FormatType . JSON : self . _validate_json ( ) elif self . data_format is FormatType . YAML : self . _validate_yaml ( )
def build_body ( self , template_file = INDEX ) : """Params : template _ file ( text ) : Path to an index . html template Returns : body ( bytes ) : THe utf - 8 encoded document body"""
if self . params [ 'error' ] == 'access_denied' : message = docs . OAUTH_ACCESS_DENIED elif self . params [ 'error' ] is not None : message = docs . OAUTH_ERROR . format ( error = self . params [ 'error' ] ) elif self . params [ 'state' ] is None or self . params [ 'code' ] is None : message = docs . OAUTH_...
def pre_fork ( self , process_manager ) : '''Pre - fork we need to create the zmq router device : param func process _ manager : An instance of salt . utils . process . ProcessManager'''
salt . transport . mixins . auth . AESReqServerMixin . pre_fork ( self , process_manager ) process_manager . add_process ( self . zmq_device )
def get_grouped_indices ( self , voigt = False , ** kwargs ) : """Gets index sets for equivalent tensor values Args : voigt ( bool ) : whether to get grouped indices of voigt or full notation tensor , defaults to false * * kwargs : keyword args for np . isclose . Can take atol and rtol for absolute and ...
if voigt : array = self . voigt else : array = self indices = list ( itertools . product ( * [ range ( n ) for n in array . shape ] ) ) remaining = indices . copy ( ) # Start with everything near zero grouped = [ list ( zip ( * np . where ( np . isclose ( array , 0 , ** kwargs ) ) ) ) ] remaining = [ i for i in...
def create_self_signed ( cls , name , common_name , public_key_algorithm = 'rsa' , signature_algorithm = 'rsa_sha_512' , key_length = 4096 ) : """Create a self signed certificate . This is a convenience method that first calls : meth : ` ~ create _ csr ` , then calls : meth : ` ~ self _ sign ` on the returned T...
tls = TLSServerCredential . create_csr ( name = name , common_name = common_name , public_key_algorithm = public_key_algorithm , signature_algorithm = signature_algorithm , key_length = key_length ) try : tls . self_sign ( ) except ActionCommandFailed : tls . delete ( ) raise return tls
def _split_keys ( mapping , separator = '.' , colliding = None ) : """Recursively walks * mapping * to split keys that contain the separator into nested mappings . . . note : : Keys not of type ` str ` are not supported and will raise errors . : param mapping : the mapping to process : param separator : t...
result = { } for key , value in mapping . items ( ) : if isinstance ( value , Mapping ) : # recursively split key ( s ) in value value = _split_keys ( value , separator ) # reject non - str keys , avoid complicating access patterns if not isinstance ( key , str ) : raise ValueError ( 'non-st...
def apply_parameters ( self , parameters ) : """Recursively apply parameter replacement ( see recipe . py ) to the wrapped recipe , updating internal references afterwards . While this operation is useful for testing it should not be used in production . Replacing parameters means that the recipe changes as i...
self . recipe . apply_parameters ( parameters ) self . recipe_step = self . recipe [ self . recipe_pointer ]
def show_user ( self , login = None , envs = [ ] , query = '/users/' ) : """` login ` - Login or username of user Show user in specified environments"""
juicer . utils . Log . log_debug ( "Show User: %s" , login ) # keep track of which iteration of environment we ' re in count = 0 for env in self . args . envs : count += 1 juicer . utils . Log . log_info ( "%s:" , env ) if not juicer . utils . user_exists_p ( login , self . connectors [ env ] ) : ju...
def is_image ( name , exts = None ) : """return True if the name or path is endswith { jpg | png | gif | jpeg }"""
default = [ 'jpg' , 'png' , 'gif' , 'jpeg' ] if exts : default += exts flag = False for ext in default : if name . lower ( ) . endswith ( ext ) : flag = True break return flag
def readout ( self , * args , ** kwargs ) : '''Running the FIFO readout while executing other statements . Starting and stopping of the FIFO readout is synchronized between the threads .'''
timeout = kwargs . pop ( 'timeout' , 10.0 ) self . start_readout ( * args , ** kwargs ) try : yield finally : try : self . stop_readout ( timeout = timeout ) except Exception : # in case something fails , call this on last resort # if run was aborted , immediately stop readout if self . ...