signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _PrintProcessingTime ( self , processing_status ) : """Prints the processing time . Args : processing _ status ( ProcessingStatus ) : processing status ."""
if not processing_status : processing_time = '00:00:00' else : processing_time = time . time ( ) - processing_status . start_time time_struct = time . gmtime ( processing_time ) processing_time = time . strftime ( '%H:%M:%S' , time_struct ) self . _output_writer . Write ( 'Processing time\t\t: {0:s}\n' ...
def abort ( code , error = None , message = None ) : """Abort with suitable error response Args : code ( int ) : status code error ( str ) : error symbol or flask . Response message ( str ) : error message"""
if error is None : flask_abort ( code ) elif isinstance ( error , Response ) : error . status_code = code flask_abort ( code , response = error ) else : body = { "status" : code , "error" : error , "message" : message } flask_abort ( code , response = export ( body , code ) )
def update_item ( event , updated_attributes , calendar_item_update_operation_type ) : """Saves updates to an event in the store . Only request changes for attributes that have actually changed ."""
root = M . UpdateItem ( M . ItemChanges ( T . ItemChange ( T . ItemId ( Id = event . id , ChangeKey = event . change_key ) , T . Updates ( ) ) ) , ConflictResolution = u"AlwaysOverwrite" , MessageDisposition = u"SendAndSaveCopy" , SendMeetingInvitationsOrCancellations = calendar_item_update_operation_type ) update_node...
def cli ( env , context_id , friendly_name , remote_peer , preshared_key , phase1_auth , phase1_crypto , phase1_dh , phase1_key_ttl , phase2_auth , phase2_crypto , phase2_dh , phase2_forward_secrecy , phase2_key_ttl ) : """Update tunnel context properties . Updates are made atomically , so either all are accepted...
manager = SoftLayer . IPSECManager ( env . client ) succeeded = manager . update_tunnel_context ( context_id , friendly_name = friendly_name , remote_peer = remote_peer , preshared_key = preshared_key , phase1_auth = phase1_auth , phase1_crypto = phase1_crypto , phase1_dh = phase1_dh , phase1_key_ttl = phase1_key_ttl ,...
def number_of_permutations ( self ) : """Returns the number of permutations of this coordination geometry ."""
if self . permutations_safe_override : return factorial ( self . coordination ) elif self . permutations is None : return factorial ( self . coordination ) return len ( self . permutations )
def category ( soup ) : """Find the category from subject areas"""
category = [ ] tags = raw_parser . category ( soup ) for tag in tags : category . append ( node_text ( tag ) ) return category
def unrate_url ( obj ) : """Generates a link to " un - rate " the given object - this can be used as a form target or for POSTing via Ajax ."""
return reverse ( 'ratings_unrate_object' , args = ( ContentType . objects . get_for_model ( obj ) . pk , obj . pk , ) )
def copy_assets ( self , assets_path ) : """Banana banana"""
if not os . path . exists ( assets_path ) : os . mkdir ( assets_path ) extra_files = self . _get_extra_files ( ) for ex_files in Formatter . get_extra_files_signal ( self ) : extra_files . extend ( ex_files ) for src , dest in extra_files : dest = os . path . join ( assets_path , dest ) destdir = os . p...
def _auto_connect ( self ) : """Attempts to connect to the roaster every quarter of a second ."""
while not self . _teardown . value : try : self . _connect ( ) return True except exceptions . RoasterLookupError : time . sleep ( .25 ) return False
def _FormatServiceText ( self , service ) : """Produces a human readable multi - line string representing the service . Args : service ( WindowsService ) : service to format . Returns : str : human readable representation of a Windows Service ."""
string_segments = [ service . name , '\tImage Path = {0:s}' . format ( service . image_path ) , '\tService Type = {0:s}' . format ( service . HumanReadableType ( ) ) , '\tStart Type = {0:s}' . format ( service . HumanReadableStartType ( ) ) , '\tService Dll = {0:s}' . format ( service . service_dll ) , '\tObje...
def write_padding ( fp , size , divisor = 2 ) : """Writes padding bytes given the currently written size . : param fp : file - like object : param divisor : divisor of the byte alignment : return : written byte size"""
remainder = size % divisor if remainder : return write_bytes ( fp , struct . pack ( '%dx' % ( divisor - remainder ) ) ) return 0
def _update_event_type ( self_ , watcher , event , triggered ) : """Returns an updated Event object with the type field set appropriately ."""
if triggered : event_type = 'triggered' else : event_type = 'changed' if watcher . onlychanged else 'set' return Event ( what = event . what , name = event . name , obj = event . obj , cls = event . cls , old = event . old , new = event . new , type = event_type )
def exception ( self , timeout = None ) : """Similar to result ( ) , except returns the exception if any ."""
# Check exceptional case : return none if no error if not self . _poll ( timeout ) . HasField ( 'error' ) : return None # Return expected error return self . _operation . error
def get_contour ( mask ) : """Compute the image contour from a mask The contour is computed in a very inefficient way using scikit - image and a conversion of float coordinates to pixel coordinates . Parameters mask : binary ndarray of shape ( M , N ) or ( K , M , N ) The mask outlining the pixel position...
if isinstance ( mask , np . ndarray ) and len ( mask . shape ) == 2 : mask = [ mask ] ret_list = False else : ret_list = True contours = [ ] for mi in mask : c0 = find_contours ( mi . transpose ( ) , level = .9999 , positive_orientation = "low" , fully_connected = "high" ) [ 0 ] # round all coordina...
def existing_analysis ( using ) : """Get the existing analysis for the ` using ` Elasticsearch connection"""
es = connections . get_connection ( using ) index_name = settings . ELASTICSEARCH_CONNECTIONS [ using ] [ 'index_name' ] if es . indices . exists ( index = index_name ) : return stringer ( es . indices . get_settings ( index = index_name ) [ index_name ] [ 'settings' ] [ 'index' ] . get ( 'analysis' , { } ) ) retur...
def insert_image ( filename , extnum_filename , auximage , extnum_auximage ) : """Replace image in filename by another image ( same size ) in newimage . Parameters filename : str File name where the new image will be inserted . extnum _ filename : int Extension number in filename where the new image will ...
# read the new image with fits . open ( auximage ) as hdulist : newimage = hdulist [ extnum_auximage ] . data # open the destination image hdulist = fits . open ( filename , mode = 'update' ) oldimage_shape = hdulist [ extnum_filename ] . data . shape if oldimage_shape == newimage . shape : hdulist [ extnum_fil...
def correlation_plot ( self , data ) : """Create heatmap of Pearson ' s correlation coefficient . Parameters data : pd . DataFrame ( ) Data to display . Returns matplotlib . figure Heatmap ."""
# CHECK : Add saved filename in result . json fig = plt . figure ( Plot_Data . count ) corr = data . corr ( ) ax = sns . heatmap ( corr ) Plot_Data . count += 1 return fig
def submit_import ( cls , volume , location , project = None , name = None , overwrite = False , properties = None , parent = None , preserve_folder_structure = True , api = None ) : """Submits new import job . : param volume : Volume identifier . : param location : Volume location . : param project : Project...
data = { } volume = Transform . to_volume ( volume ) if project and parent : raise SbgError ( 'Project and parent identifiers are mutually exclusive' ) elif project : project = Transform . to_project ( project ) destination = { 'project' : project } elif parent : parent = Transform . to_file ( parent ) ...
def run ( self ) : """This AI simple moves the characters towards the opposite edges of the grid for 3 steps or until event halts the simulation"""
x , y = 1 , 0 # set the direction num_steps = 0 while self . s . get_state ( ) != 'Halted' : self . s . command ( { 'name' : 'walk' , 'type' : 'move' , 'direction' : [ x , y ] } , self . a1 ) self . s . command ( { 'name' : 'walk' , 'type' : 'run' , 'direction' : [ x , y + 1 ] } , self . a2 ) num_steps += 1...
def get_query_string ( request , new_params = None , remove = None ) : """Given the request , return the query string . Parameters can be added or removed as necessary . Code snippet taken from Django admin app ( views / main . py ) ( c ) Copyright Django Software Foundation and individual contributors . Re...
if new_params is None : new_params = { } if remove is None : remove = [ ] p = dict ( request . GET . items ( ) ) for r in remove : for k in p . keys ( ) : if k . startswith ( r ) : del p [ k ] for k , v in new_params . items ( ) : if v is None : if k in p : del p ...
def _send ( self ) : """Send all queued messages to the server ."""
data = self . output_buffer . view ( ) if not data : return if self . closed ( ) : raise self . Error ( "Failed to write to closed connection {!r}" . format ( self . server . address ) ) if self . defunct ( ) : raise self . Error ( "Failed to write to defunct connection {!r}" . format ( self . server . addr...
def expect ( self , expect , searchwindowsize = None , maxread = None , timeout = None , iteration_n = 1 ) : """Handle child expects , with EOF and TIMEOUT handled iteration _ n - Number of times this expect has been called for the send . If 1 , ( the default ) then it gets added to the pane of output ( if ap...
if isinstance ( expect , str ) : expect = [ expect ] if searchwindowsize != None : old_searchwindowsize = self . pexpect_child . searchwindowsize self . pexpect_child . searchwindowsize = searchwindowsize if maxread != None : old_maxread = self . pexpect_child . maxread self . pexpect_child . maxrea...
def hil_optical_flow_encode ( self , time_usec , sensor_id , integration_time_us , integrated_x , integrated_y , integrated_xgyro , integrated_ygyro , integrated_zgyro , temperature , quality , time_delta_distance_us , distance ) : '''Simulated optical flow from a flow sensor ( e . g . PX4FLOW or optical mouse se...
return MAVLink_hil_optical_flow_message ( time_usec , sensor_id , integration_time_us , integrated_x , integrated_y , integrated_xgyro , integrated_ygyro , integrated_zgyro , temperature , quality , time_delta_distance_us , distance )
def prefix ( cls , name ) : """Create a new TreeModel where class attribute names are prefixed with ` ` name ` `"""
attrs = dict ( [ ( name + attr , value ) for attr , value in cls . get_attrs ( ) ] ) return TreeModelMeta ( '_' . join ( [ name , cls . __name__ ] ) , ( TreeModel , ) , attrs )
def iter_forks ( self , number = - 1 , etag = None ) : """Iterator of forks of this gist . . . versionchanged : : 0.9 Added params ` ` number ` ` and ` ` etag ` ` . : param int number : ( optional ) , number of forks to iterate over . Default : - 1 will iterate over all forks of this gist . : param str et...
url = self . _build_url ( 'forks' , base_url = self . _api ) return self . _iter ( int ( number ) , url , Gist , etag = etag )
def sequence_equal ( self , second_iterable , equality_comparer = operator . eq ) : '''Determine whether two sequences are equal by elementwise comparison . Sequence equality is defined as the two sequences being equal length and corresponding elements being equal as determined by the equality comparer . No...
if self . closed ( ) : raise ValueError ( "Attempt to call to_tuple() on a closed Queryable." ) if not is_iterable ( second_iterable ) : raise TypeError ( "Cannot compute sequence_equal() with second_iterable of non-iterable {type}" . format ( type = str ( type ( second_iterable ) ) [ 7 : - 1 ] ) ) if not is_ca...
def handle_message ( self , message : BaseMessage , responder : Responder , create_task : True ) : """Public method to handle a message . It requires : - A message from the platform - A responder from the platform If ` create _ task ` is true , them the task will automatically be added to the loop . However...
coro = self . _handle_message ( message , responder ) if create_task : loop = asyncio . get_event_loop ( ) loop . create_task ( coro ) else : return coro
def start_trace ( full = False , frame = None , below = 0 , under = None , server = None , port = None ) : """Start tracing program at callee level breaking on exception / breakpoints"""
wdb = Wdb . get ( server = server , port = port ) if not wdb . stepping : wdb . start_trace ( full , frame or sys . _getframe ( ) . f_back , below , under ) return wdb
def prev ( self ) : """Return the previous window"""
prev_index = self . index - 1 prev_handle = self . _browser . driver . window_handles [ prev_index ] return Window ( self . _browser , prev_handle )
def parse ( to_parse , ignore_whitespace_text_nodes = True , adapter = None ) : """Parse an XML document into an * xml4h * - wrapped DOM representation using an underlying XML library implementation . : param to _ parse : an XML document file , document string , or the path to an XML file . If a string value ...
if adapter is None : adapter = best_adapter if isinstance ( to_parse , basestring ) and '<' in to_parse : return adapter . parse_string ( to_parse , ignore_whitespace_text_nodes ) else : return adapter . parse_file ( to_parse , ignore_whitespace_text_nodes )
def fix_local_scheme ( home_dir , symlink = True ) : """Platforms that use the " posix _ local " install scheme ( like Ubuntu with Python 2.7 ) need to be given an additional " local " location , sigh ."""
try : import sysconfig except ImportError : pass else : if sysconfig . _get_default_scheme ( ) == 'posix_local' : local_path = os . path . join ( home_dir , 'local' ) if not os . path . exists ( local_path ) : os . mkdir ( local_path ) for subdir_name in os . listdir ...
def sample_double_norm ( mean , std_upper , std_lower , size ) : """Note that this function requires Scipy ."""
from scipy . special import erfinv # There ' s probably a better way to do this . We first draw percentiles # uniformly between 0 and 1 . We want the peak of the distribution to occur # at ` mean ` . However , if we assign 50 % of the samples to the lower half # and 50 % to the upper half , the side with the smaller va...
def _validate_num_qubits ( state : np . ndarray ) -> int : """Validates that state ' s size is a power of 2 , returning number of qubits ."""
size = state . size if size & ( size - 1 ) : raise ValueError ( 'state.size ({}) is not a power of two.' . format ( size ) ) return size . bit_length ( ) - 1
def reload ( self , hardware_id , post_uri = None , ssh_keys = None ) : """Perform an OS reload of a server with its current configuration . : param integer hardware _ id : the instance ID to reload : param string post _ uri : The URI of the post - install script to run after reload : param list ssh _ keys ...
config = { } if post_uri : config [ 'customProvisionScriptUri' ] = post_uri if ssh_keys : config [ 'sshKeyIds' ] = [ key_id for key_id in ssh_keys ] return self . hardware . reloadOperatingSystem ( 'FORCE' , config , id = hardware_id )
def gaussian_points ( loc = ( 0 , 0 ) , scale = ( 10 , 10 ) , n = 100 ) : """Generates and returns ` n ` normally distributed points centered at ` loc ` with ` scale ` x and y directionality ."""
arr = np . random . normal ( loc , scale , ( n , 2 ) ) return gpd . GeoSeries ( [ shapely . geometry . Point ( x , y ) for ( x , y ) in arr ] )
def append_form ( self , obj : Union [ Sequence [ Tuple [ str , str ] ] , Mapping [ str , str ] ] , headers : Optional [ 'MultiMapping[str]' ] = None ) -> Payload : """Helper to append form urlencoded part ."""
assert isinstance ( obj , ( Sequence , Mapping ) ) if headers is None : headers = CIMultiDict ( ) if isinstance ( obj , Mapping ) : obj = list ( obj . items ( ) ) data = urlencode ( obj , doseq = True ) return self . append_payload ( StringPayload ( data , headers = headers , content_type = 'application/x-www-f...
def centerize ( src , dst_shape , margin_color = None ) : """Centerize image for specified image size @ param src : image to centerize @ param dst _ shape : image shape ( height , width ) or ( height , width , channel )"""
if src . shape [ : 2 ] == dst_shape [ : 2 ] : return src centerized = np . zeros ( dst_shape , dtype = src . dtype ) if margin_color : centerized [ : , : ] = margin_color pad_vertical , pad_horizontal = 0 , 0 h , w = src . shape [ : 2 ] dst_h , dst_w = dst_shape [ : 2 ] if h < dst_h : pad_vertical = ( dst_h...
def toy_poisson_rbf_1d_laplace ( optimize = True , plot = True ) : """Run a simple demonstration of a standard Gaussian process fitting it to data sampled from an RBF covariance ."""
optimizer = 'scg' x_len = 100 X = np . linspace ( 0 , 10 , x_len ) [ : , None ] f_true = np . random . multivariate_normal ( np . zeros ( x_len ) , GPy . kern . RBF ( 1 ) . K ( X ) ) Y = np . array ( [ np . random . poisson ( np . exp ( f ) ) for f in f_true ] ) [ : , None ] kern = GPy . kern . RBF ( 1 ) poisson_lik = ...
def choice_prompt ( prompt , choices = None , choice = None ) : '''Ask the user for a prompt , and only return when one of the requested options is provided . Parameters prompt : the prompt to ask the user choices : a list of choices that are valid , defaults to [ Y / N / y / n ]'''
if not choices : choices = [ "y" , "n" , "Y" , "N" ] print ( prompt ) get_input = getattr ( __builtins__ , 'raw_input' , input ) pretty_choices = '/' . join ( choices ) message = 'Please enter your choice [%s] : ' % ( pretty_choices ) while choice not in choices : choice = get_input ( message ) . strip ( ) ...
def _add_thread ( self , aThread ) : """Private method to add a thread object to the snapshot . @ type aThread : L { Thread } @ param aThread : Thread object ."""
# # if not isinstance ( aThread , Thread ) : # # if hasattr ( aThread , ' _ _ class _ _ ' ) : # # typename = aThread . _ _ class _ _ . _ _ name _ _ # # else : # # typename = str ( type ( aThread ) ) # # msg = " Expected Thread , got % s instead " % typename # # raise TypeError ( msg ) dwThreadId = aThread . dwThreadId ...
def http_basic_auth_get_user ( request ) : """Inspect the given request to find a logged user . If not found , the header HTTP _ AUTHORIZATION is read for ' Basic Auth ' login and password , and try to authenticate against default UserModel . Always return a User instance ( possibly anonymous , meaning authenti...
try : # If standard auth middleware already authenticated a user , use it if user_is_authenticated ( request . user ) : return request . user except AttributeError : pass # This was grabbed from https : / / www . djangosnippets . org / snippets / 243/ # Thanks to http : / / stackoverflow . com / a / 108...
def turn_off ( self ) -> "Signal" : """Turns off the signal . This may be invoked from any code ."""
if _logger is not None : self . _log ( INFO , "turn-off" ) self . _is_on = False return self
def transform_config ( transformer , data , data_type = 'S3Prefix' , content_type = None , compression_type = None , split_type = None , job_name = None ) : """Export Airflow transform config from a SageMaker transformer Args : transformer ( sagemaker . transformer . Transformer ) : The SageMaker transformer to...
if job_name is not None : transformer . _current_job_name = job_name else : base_name = transformer . base_transform_job_name transformer . _current_job_name = utils . name_from_base ( base_name ) if base_name is not None else transformer . model_name if transformer . output_path is None : transformer ....
def close ( self ) : """Closes the tunnel ."""
try : self . sock . shutdown ( socket . SHUT_RDWR ) self . sock . close ( ) except socket . error : pass
def model_fn ( features , labels , mode , params ) : """The model _ fn argument for creating an Estimator ."""
tf . logging . info ( "features = %s labels = %s mode = %s params=%s" % ( features , labels , mode , params ) ) global_step = tf . train . get_global_step ( ) graph = mtf . Graph ( ) mesh = mtf . Mesh ( graph , "my_mesh" ) logits , loss = mnist_model ( features , labels , mesh ) mesh_shape = mtf . convert_to_shape ( FL...
def zSetSurfaceData ( self , surfNum , radius = None , thick = None , material = None , semidia = None , conic = None , comment = None ) : """Sets surface data"""
if self . pMode == 0 : # Sequential mode surf = self . pLDE . GetSurfaceAt ( surfNum ) if radius is not None : surf . pRadius = radius if thick is not None : surf . pThickness = thick if material is not None : surf . pMaterial = material if semidia is not None : surf ...
def parse_json ( self , page ) : '''Returns json feed .'''
if not isinstance ( page , basestring ) : page = util . decode_page ( page ) self . doc = json . loads ( page ) results = self . doc . get ( self . result_name , [ ] ) if not results : self . check_status ( self . doc . get ( 'status' ) ) return None return results
def changePlanParticipation ( self , plan , take_part = True ) : """Changes participation in a plan : param plan : Plan to take part in or not : param take _ part : Whether to take part in the plan : raises : FBchatException if request failed"""
data = { "event_reminder_id" : plan . uid , "guest_state" : "GOING" if take_part else "DECLINED" , "acontext" : ACONTEXT , } j = self . _post ( self . req_url . PLAN_PARTICIPATION , data , fix_request = True , as_json = True )
def _build_full_list ( self ) : """Build a full list of pages . Examples : > > > _ SlicedPaginator ( 1 , 7 , 5 ) . _ build _ full _ list ( ) [1 , 2 , 3 , 4 , 5] > > > _ SlicedPaginator ( 6 , 7 , 5 ) . _ build _ full _ list ( ) [3 , 4 , 5 , 6 , 7] > > > _ SlicedPaginator ( 6 , 7 , 5 ) . _ build _ full _ ...
if self . npages <= self . maxpages_items : return range ( 1 , self . npages + 1 ) else : l = range ( self . curpage - self . max_prev_items , self . curpage + self . max_next_items + 1 ) while l and l [ 0 ] < 1 : l . append ( l [ - 1 ] + 1 ) del l [ 0 ] while l and l [ - 1 ] > self . np...
def read ( self , size = 1024 ) : """Read at most ` ` size ` ` bytes from the pty , return them as unicode . Can block if there is nothing to read . Raises : exc : ` EOFError ` if the terminal was closed . The size argument still refers to bytes , not unicode code points ."""
b = super ( PtyProcessUnicode , self ) . read ( size ) return self . decoder . decode ( b , final = False )
def item ( p_queue , queue_id , host = None ) : if host is not None : return os . path . join ( _path ( host , _c . FSQ_QUEUE , root = hosts ( p_queue ) ) , valid_name ( queue_id ) ) '''Construct a path to a queued item'''
return os . path . join ( _path ( p_queue , _c . FSQ_QUEUE ) , valid_name ( queue_id ) )
def is_valid_triangle ( x , y , z ) : """This function checks the validity of a triangle based on its angles . A triangle is valid if the sum of its three angles equals 180 degrees . Args : x , y , z : The angles of the triangle . Returns : A boolean value indicating if the triangle is valid or not . Ex...
return ( ( x + y ) + z ) == 180
def ias53 ( msg ) : """Indicated airspeed , DBS 5,3 message Args : msg ( String ) : 28 bytes hexadecimal message Returns : int : indicated arispeed in knots"""
d = hex2bin ( data ( msg ) ) if d [ 12 ] == '0' : return None ias = bin2int ( d [ 13 : 23 ] ) # knots return ias
def template ( tem , queue = False , ** kwargs ) : '''Execute the information stored in a template file on the minion . This function does not ask a master for a SLS file to render but instead directly processes the file at the provided path on the minion . CLI Example : . . code - block : : bash salt ' *...
if 'env' in kwargs : # " env " is not supported ; Use " saltenv " . kwargs . pop ( 'env' ) conflict = _check_queue ( queue , kwargs ) if conflict is not None : return conflict opts = salt . utils . state . get_sls_opts ( __opts__ , ** kwargs ) try : st_ = salt . state . HighState ( opts , context = __contex...
def load ( self , filename ) : """entry point load the pest control file . sniffs the first non - comment line to detect the version ( if present ) Parameters filename : str pst filename Raises lots of exceptions for incorrect format"""
assert os . path . exists ( filename ) , "couldn't find control file {0}" . format ( filename ) f = open ( filename , 'r' ) while True : line = f . readline ( ) if line == "" : raise Exception ( "Pst.load() error: EOF when trying to find first line - #sad" ) if line . strip ( ) . split ( ) [ 0 ] . l...
def load_iterable ( self , iterable , session = None ) : '''Load an ` ` iterable ` ` . By default it returns a generator of data loaded via the : meth : ` loads ` method . : param iterable : an iterable over data to load . : param session : Optional : class : ` stdnet . odm . Session ` . : return : an ite...
data = [ ] load = self . loads for v in iterable : data . append ( load ( v ) ) return data
def __yahoo_request ( query ) : """Request Yahoo Finance information . Request information from YQL . ` Check < http : / / goo . gl / 8AROUD > ` _ for more information on YQL ."""
query = quote ( query ) url = 'https://query.yahooapis.com/v1/public/yql?q=' + query + '&format=json&env=store://datatables.org/alltableswithkeys' response = urlopen ( url ) . read ( ) return json . loads ( response . decode ( 'utf-8' ) ) [ 'query' ] [ 'results' ]
async def _collect_sample ( self , url , url_pattern ) : """Sample collection is meant to be very tolerant to generic failures as failing to obtain the sample has important consequences on the results . - Multiple retries with longer delays - Larger than usual timeout"""
samples = [ ] urls = [ self . path_generator . generate_url ( url , url_pattern ) for _ in range ( self . confirmation_factor ) ] iterator = asyncio . as_completed ( [ self . _fetch_sample ( url ) for url in urls ] ) for promise in iterator : try : sig = await promise if sig : samples . ...
def _check_branch ( self , revision , branch ) : '''Used to find out if the revision is in the given branch . : param revision : Revision to check . : param branch : Branch to check revision on . : return : True / False - Found it / Didn ' t find it'''
# Get a changelog clog_url = self . hg_url / branch / 'json-log' / revision try : Log . note ( "Searching through changelog {{url}}" , url = clog_url ) clog_obj = http . get_json ( clog_url , retry = RETRY ) if isinstance ( clog_obj , ( text_type , str ) ) : Log . note ( "Revision {{cset}} does not ...
def get_features ( self , mapobject_type_name ) : '''Gets features for a given object type . Parameters mapobject _ type _ name : str type of the segmented objects Returns List [ Dict [ str , str ] ] information about each feature See also : func : ` tmserver . api . feature . get _ features ` : c...
logger . info ( 'get features of experiment "%s", object type "%s"' , self . experiment_name , mapobject_type_name ) mapobject_type_id = self . _get_mapobject_type_id ( mapobject_type_name ) url = self . _build_api_url ( '/experiments/{experiment_id}/mapobject_types/{mapobject_type_id}/features' . format ( experiment_i...
def commonancestors ( Class , * args ) : """Generator function to find common ancestors of a particular type for any two or more FoLiA element instances . The function produces all common ancestors of the type specified , starting from the closest one up to the most distant one . Parameters : Class : The type...
commonancestors = None # pylint : disable = redefined - outer - name for sibling in args : ancestors = list ( sibling . ancestors ( Class ) ) if commonancestors is None : commonancestors = copy ( ancestors ) else : removeancestors = [ ] for a in commonancestors : # pylint : disable =...
def create_project ( self , project_name , desc ) : """Send POST to / projects creating a new project with the specified name and desc . Raises DataServiceError on error . : param project _ name : str name of the project : param desc : str description of the project : return : requests . Response containing...
data = { "name" : project_name , "description" : desc } return self . _post ( "/projects" , data )
def resolve_python_path ( path ) : """Turns a python path like module . name . here : ClassName . SubClass into an object"""
# Get the module module_path , local_path = path . split ( ':' , 1 ) thing = importlib . import_module ( module_path ) # Traverse the local sections local_bits = local_path . split ( '.' ) for bit in local_bits : thing = getattr ( thing , bit ) return thing
def get_submissions ( student_item_dict , limit = None ) : """Retrieves the submissions for the specified student item , ordered by most recent submitted date . Returns the submissions relative to the specified student item . Exception thrown if no submission is found relative to this location . Args : st...
student_item_model = _get_or_create_student_item ( student_item_dict ) try : submission_models = Submission . objects . filter ( student_item = student_item_model ) except DatabaseError : error_message = ( u"Error getting submission request for student item {}" . format ( student_item_dict ) ) logger . exce...
def get_owned_filters ( self , server_id ) : """Return the indication filters in a WBEM server owned by this subscription manager . This function accesses only the local list of owned filters ; it does not contact the WBEM server . The local list of owned filters is discovered from the WBEM server when the ...
# Validate server _ id self . _get_server ( server_id ) return list ( self . _owned_filters [ server_id ] )
def MaxPooling ( inputs , pool_size , strides = None , padding = 'valid' , data_format = 'channels_last' ) : """Same as ` tf . layers . MaxPooling2D ` . Default strides is equal to pool _ size ."""
if strides is None : strides = pool_size layer = tf . layers . MaxPooling2D ( pool_size , strides , padding = padding , data_format = data_format ) ret = layer . apply ( inputs , scope = tf . get_variable_scope ( ) ) return tf . identity ( ret , name = 'output' )
def use_refresh_token ( self , refresh_token , scope = None ) : # type ( str , Optional [ List [ str ] ] ) - > Tuple [ se _ leg _ op . access _ token . AccessToken , Optional [ str ] ] """Creates a new access token , and refresh token , based on the supplied refresh token . : return : new access token and new ref...
if refresh_token not in self . refresh_tokens : raise InvalidRefreshToken ( '{} unknown' . format ( refresh_token ) ) refresh_token_info = self . refresh_tokens [ refresh_token ] if 'exp' in refresh_token_info and refresh_token_info [ 'exp' ] < int ( time . time ( ) ) : raise InvalidRefreshToken ( '{} has expir...
def get ( self , measurementId ) : """Analyses the measurement with the given parameters : param measurementId : : return :"""
logger . info ( 'Loading raw data for ' + measurementId ) measurement = self . _measurementController . getMeasurement ( measurementId , MeasurementStatus . COMPLETE ) if measurement is not None : if measurement . inflate ( ) : data = { name : { 'raw' : { 'x' : self . _jsonify ( data . raw ( 'x' ) ) , 'y' :...
def write ( self , oprot ) : '''Write this object to the given output protocol and return self . : type oprot : thryft . protocol . _ output _ protocol . _ OutputProtocol : rtype : pastpy . gen . database . impl . online . online _ database _ configuration . OnlineDatabaseConfiguration'''
oprot . write_struct_begin ( 'OnlineDatabaseConfiguration' ) oprot . write_field_begin ( name = 'collection_name' , type = 11 , id = None ) oprot . write_string ( self . collection_name ) oprot . write_field_end ( ) if self . download_dir_path is not None : oprot . write_field_begin ( name = 'download_dir_path' , t...
def imdb ( limit = None , shuffle = True ) : """Downloads ( and caches ) IMDB Moview Reviews . 25k training data , 25k test data Args : limit : get only first N items for each class Returns : [ X _ train , y _ train , X _ test , y _ test ]"""
movie_review_url = 'http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz' # download and extract , thus remove the suffix ' . tar . gz ' path = keras . utils . get_file ( 'aclImdb.tar.gz' , movie_review_url , extract = True ) [ : - 7 ] X_train , y_train = read_pos_neg_data ( path , 'train' , limit ) X_test , ...
def bitwise_xor ( self , t ) : """Operation xor : param t : The other operand ."""
# Using same variables as in paper s = self new_interval = ( s . bitwise_not ( ) . bitwise_or ( t ) ) . bitwise_not ( ) . bitwise_or ( s . bitwise_or ( t . bitwise_not ( ) ) . bitwise_not ( ) ) return new_interval . normalize ( )
def convert_string_to_list ( input_string : str ) -> list : """Transform a string into a list , split by spaces . Examples : convert _ string _ to _ list ( ' python programming ' ) - > [ ' python ' , ' programming ' ] convert _ string _ to _ list ( ' lists tuples strings ' ) - > [ ' lists ' , ' tuples ' , ' s...
return input_string . split ( ' ' )
def images_to_matrix ( image_list , mask = None , sigma = None , epsilon = 0.5 ) : """Read images into rows of a matrix , given a mask - much faster for large datasets as it is based on C + + implementations . ANTsR function : ` imagesToMatrix ` Arguments image _ list : list of ANTsImage types images to c...
def listfunc ( x ) : if np . sum ( np . array ( x . shape ) - np . array ( mask . shape ) ) != 0 : x = reg . resample_image_to_target ( x , mask , 2 ) return x [ mask ] if mask is None : mask = utils . get_mask ( image_list [ 0 ] ) num_images = len ( image_list ) mask_arr = mask . numpy ( ) >= epsil...
def port_remove_nio_binding ( self , port_number ) : """Removes a port NIO binding . : param port _ number : port number : returns : NIO instance"""
if not self . _ethernet_adapter . port_exists ( port_number ) : raise VPCSError ( "Port {port_number} doesn't exist in adapter {adapter}" . format ( adapter = self . _ethernet_adapter , port_number = port_number ) ) if self . is_running ( ) : yield from self . _ubridge_send ( "bridge delete {name}" . format ( n...
def transform ( self , textual ) : """Transform an object from textual form to ` PyObject `"""
if textual is None : return None type = textual [ 0 ] try : method = getattr ( self , type + '_to_pyobject' ) return method ( textual ) except AttributeError : return None
def get_proficiency_mdata ( ) : """Return default mdata map for Proficiency"""
return { 'completion' : { 'element_label' : { 'text' : 'completion' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TYPE ) , 'scriptTypeId' : str ( DEFAULT_SCRIPT_TYPE ) , 'formatTypeId' : str ( DEFAULT_FORMAT_TYPE ) , } , 'instructions' : { 'text' : 'enter a decimal value.' , 'languageTypeId' : str ( DEFAULT_LANGUAGE_TYPE...
def main ( data_directory : int , dataset : str = None , filter_by : str = None , verbose : bool = False ) -> None : """Parameters data _ directory : str , required . The path to the data directory of https : / / github . com / jkkummerfeld / text2sql - data which has been preprocessed using scripts / reforma...
directory_dict = { path : files for path , names , files in os . walk ( data_directory ) if files } for directory , data_files in directory_dict . items ( ) : if "query_split" in directory or ( dataset is not None and dataset not in directory ) : continue print ( f"Parsing dataset at {directory}" ) ...
def _removeBackrefs ( senderkey ) : """Remove all back - references to this senderkey"""
try : signals = connections [ senderkey ] except KeyError : signals = None else : items = signals . items ( ) def allReceivers ( ) : for signal , set in items : for item in set : yield item for receiver in allReceivers ( ) : _killBackref ( receiver , sende...
def process_calibration ( self , save = False ) : """processes the data gathered in a calibration run ( does not work if multiple calibrations ) , returns resultant dB"""
if not self . save_data : raise Exception ( "Runner must be set to save when run, to be able to process" ) vfunc = np . vectorize ( calc_db , self . mphonesens , self . mphonedb ) if USE_FFT : peaks = np . mean ( abs ( self . datafile . get_data ( self . current_dataset_name + '/fft_peaks' ) ) , axis = 1 ) else...
def swap ( self , old_chunks , new_chunk ) : """Swaps old consecutive chunks with new chunk . Args : old _ chunks ( : obj : ` budou . chunk . ChunkList ` ) : List of consecutive Chunks to be removed . new _ chunk ( : obj : ` budou . chunk . Chunk ` ) : A Chunk to be inserted ."""
indexes = [ self . index ( chunk ) for chunk in old_chunks ] del self [ indexes [ 0 ] : indexes [ - 1 ] + 1 ] self . insert ( indexes [ 0 ] , new_chunk )
def irfftn ( a , s = None , axes = None , norm = None ) : """Compute the inverse of the N - dimensional FFT of real input . This function computes the inverse of the N - dimensional discrete Fourier Transform for real input over any number of axes in an M - dimensional array by means of the Fast Fourier Trans...
output = mkl_fft . irfftn_numpy ( a , s , axes ) if _unitary ( norm ) : output *= sqrt ( _tot_size ( output , axes ) ) return output
def get_num_names_in_namespace ( self , namespace_id ) : """Get the number of names in a namespace"""
cur = self . db . cursor ( ) return namedb_get_num_names_in_namespace ( cur , namespace_id , self . lastblock )
def import_ed25519_publickey_from_file ( filepath ) : """< Purpose > Load the ED25519 public key object ( conformant to ' securesystemslib . formats . KEY _ SCHEMA ' ) stored in ' filepath ' . Return ' filepath ' in securesystemslib . formats . ED25519KEY _ SCHEMA format . If the key object in ' filepath ' ...
# Does ' filepath ' have the correct format ? # Ensure the arguments have the appropriate number of objects and object # types , and that all dict keys are properly named . # Raise ' securesystemslib . exceptions . FormatError ' if there is a mismatch . securesystemslib . formats . PATH_SCHEMA . check_match ( filepath ...
def _format_mongodb_uri ( parsed_uri ) : """Painstakingly reconstruct a MongoDB URI parsed using pymongo . uri _ parser . parse _ uri . : param parsed _ uri : Result of pymongo . uri _ parser . parse _ uri : type parsed _ uri : dict : return : New URI : rtype : str | unicode"""
user_pass = '' if parsed_uri . get ( 'username' ) and parsed_uri . get ( 'password' ) : user_pass = '{username!s}:{password!s}@' . format ( ** parsed_uri ) _nodes = [ ] for host , port in parsed_uri . get ( 'nodelist' ) : if ':' in host and not host . endswith ( ']' ) : # IPv6 address without brackets h...
def parse_tagged_reference_line ( line_marker , line , identified_dois , identified_urls ) : """Given a single tagged reference line , convert it to its MARC - XML representation . Try to find all tags and extract their contents and their types into corresponding dictionary elements . Append each dictionary tag...
count_misc = count_title = count_reportnum = count_url = count_doi = count_auth_group = 0 processed_line = line cur_misc_txt = u"" tag_match = re_tagged_citation . search ( processed_line ) # contains a list of dictionary entries of previously cited items citation_elements = [ ] # the last tag element found when workin...
def _plot_posterior_op ( values , var_name , selection , ax , bw , linewidth , bins , kind , point_estimate , round_to , credible_interval , ref_val , rope , ax_labelsize , xt_labelsize , ** kwargs ) : # noqa : D202 """Artist to draw posterior ."""
def format_as_percent ( x , round_to = 0 ) : return "{0:.{1:d}f}%" . format ( 100 * x , round_to ) def display_ref_val ( ) : if ref_val is None : return elif isinstance ( ref_val , dict ) : val = None for sel in ref_val . get ( var_name , [ ] ) : if all ( k in selection a...
def implied_loop_expr ( expr , start , end , delta ) : """given the parameters of an implied loop - - namely , the start and end values together with the delta per iteration - - implied _ loop _ expr ( ) returns a list of values of the lambda expression expr applied to successive values of the implied loop ."...
if delta > 0 : stop = end + 1 else : stop = end - 1 result_list = [ expr ( x ) for x in range ( start , stop , delta ) ] # return the flattened list of results return list ( itertools . chain ( result_list ) )
def stop_codon_spliced_offsets ( self ) : """Offsets from start of spliced mRNA transcript of nucleotides in stop codon ."""
offsets = [ self . spliced_offset ( position ) for position in self . stop_codon_positions ] return self . _contiguous_offsets ( offsets )
def word ( self ) : """Property of the DigitWord returning ( or setting ) the DigitWord as a list of integers ( or string representations ) of DigitModel . The property is called during instantiation as the property validates the value passed and ensures that all digits are valid ."""
if self . wordtype == DigitWord . DIGIT : return self . _word else : # Strip out ' 0x ' from the string representation . Note , this could be replaced with the # following code : str ( hex ( a ) ) [ 2 : ] but is more obvious in the code below . return [ str ( hex ( a ) ) . replace ( '0x' , '' ) for a in self . ...
def _check_valid ( key , val , valid ) : """Helper to check valid options"""
if val not in valid : raise ValueError ( '%s must be one of %s, not "%s"' % ( key , valid , val ) )
def build_absolute_uri ( request , relative_url ) : """Ensure absolute _ uri are relative to WEBROOT ."""
webroot = getattr ( settings , 'WEBROOT' , '' ) if webroot . endswith ( "/" ) and relative_url . startswith ( "/" ) : webroot = webroot [ : - 1 ] return request . build_absolute_uri ( webroot + relative_url )
def runGetVariantAnnotationSet ( self , id_ ) : """Runs a getVariantSet request for the specified ID ."""
compoundId = datamodel . VariantAnnotationSetCompoundId . parse ( id_ ) dataset = self . getDataRepository ( ) . getDataset ( compoundId . dataset_id ) variantSet = dataset . getVariantSet ( compoundId . variant_set_id ) variantAnnotationSet = variantSet . getVariantAnnotationSet ( id_ ) return self . runGetRequest ( v...
def choice ( opts , default = 1 , text = 'Please make a choice.' ) : """Prompt the user to select an option @ param opts : List of tuples containing options in ( key , value ) format - value is optional @ type opts : list of tuple @ param text : Prompt text @ type text : str"""
opts_len = len ( opts ) opts_enum = enumerate ( opts , 1 ) opts = list ( opts ) for key , opt in opts_enum : click . echo ( '[{k}] {o}' . format ( k = key , o = opt [ 1 ] if isinstance ( opt , tuple ) else opt ) ) click . echo ( '-' * 12 ) opt = click . prompt ( text , default , type = click . IntRange ( 1 , opts_l...
def pick_monomials_up_to_degree ( monomials , degree ) : """Collect monomials up to a given degree ."""
ordered_monomials = [ ] if degree >= 0 : ordered_monomials . append ( S . One ) for deg in range ( 1 , degree + 1 ) : ordered_monomials . extend ( pick_monomials_of_degree ( monomials , deg ) ) return ordered_monomials
def _name_in_services ( name , services ) : '''Checks to see if the given service is in the given services . : param str name : Service label , file name , or full path : param dict services : The currently available services . : return : The service information for the service , otherwise an empty dictiona...
if name in services : # Match on label return services [ name ] for service in six . itervalues ( services ) : if service [ 'file_path' ] . lower ( ) == name : # Match on full path return service basename , ext = os . path . splitext ( service [ 'file_name' ] ) if basename . lower ( ) == name : ...
def create_for_receipt ( self , receipt , ** kwargs ) : """Creates a ReceiptPDF object for a given receipt . Does not actually generate the related PDF file . All attributes will be completed with the information for the relevant ` ` TaxPayerProfile ` ` instance . : param Receipt receipt : The receipt for t...
try : profile = TaxPayerProfile . objects . get ( taxpayer__points_of_sales__receipts = receipt , ) except TaxPayerProfile . DoesNotExist : raise exceptions . DjangoAfipException ( 'Cannot generate a PDF for taxpayer with no profile' , ) pdf = ReceiptPDF . objects . create ( receipt = receipt , issuing_name = p...
def _init_w_transforms ( data , features , random_states , comm = MPI . COMM_SELF ) : """Initialize the mappings ( Wi ) for the SRM with random orthogonal matrices . Parameters data : list of 2D arrays , element i has shape = [ voxels _ i , samples ] Each element in the list contains the fMRI data of one subj...
w = [ ] subjects = len ( data ) voxels = np . empty ( subjects , dtype = int ) # Set Wi to a random orthogonal voxels by features matrix for subject in range ( subjects ) : if data [ subject ] is not None : voxels [ subject ] = data [ subject ] . shape [ 0 ] rnd_matrix = random_states [ subject ] . ...
def get_qemu_info ( path , backing_chain = False , fail_on_error = True ) : """Get info on a given qemu disk Args : path ( str ) : Path to the required disk backing _ chain ( boo ) : if true , include also info about the image predecessors . Return : object : if backing _ chain = = True then a list of d...
cmd = [ 'qemu-img' , 'info' , '--output=json' , path ] if backing_chain : cmd . insert ( - 1 , '--backing-chain' ) result = run_command_with_validation ( cmd , fail_on_error , msg = 'Failed to get info for {}' . format ( path ) ) return json . loads ( result . out )
def _connectWithContextFactory ( ctxFactory , workbench ) : """Connect using the given context factory . Notifications go to the given workbench ."""
endpoint = SSL4ClientEndpoint ( reactor , "localhost" , 4430 , ctxFactory ) splash = _Splash ( u"Connecting" , u"Connecting..." ) workbench . display ( splash ) d = endpoint . connect ( Factory ( workbench ) ) @ d . addBoth def closeSplash ( returnValue ) : workbench . undisplay ( ) return returnValue @ d . add...
def morph ( clm1 , clm2 , t , lmax ) : """Interpolate linearly the two sets of sph harm . coeeficients ."""
clm = ( 1 - t ) * clm1 + t * clm2 grid_reco = clm . expand ( lmax = lmax ) # cut " high frequency " components agrid_reco = grid_reco . to_array ( ) pts = [ ] for i , longs in enumerate ( agrid_reco ) : ilat = grid_reco . lats ( ) [ i ] for j , value in enumerate ( longs ) : ilong = grid_reco . lons ( )...