signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def transform ( self , X , y ) : # pylint : disable = anomalous - backslash - in - string """Additional transformations on ` ` X ` ` and ` ` y ` ` . By default , they are cast to PyTorch : class : ` ~ torch . Tensor ` \ s . Override this if you want a different behavior . Note : If you use this in conjuction ...
# pytorch DataLoader cannot deal with None so we use 0 as a # placeholder value . We only return a Tensor with one value # ( as opposed to ` ` batchsz ` ` values ) since the pytorch # DataLoader calls _ _ getitem _ _ for each row in the batch # anyway , which results in a dummy ` ` y ` ` value for each row in # the bat...
def identity ( requestContext , name , step = 60 ) : """Identity function : Returns datapoints where the value equals the timestamp of the datapoint . Useful when you have another series where the value is a timestamp , and you want to compare it to the time of the datapoint , to render an age Example : : ...
start = int ( epoch ( requestContext [ "startTime" ] ) ) end = int ( epoch ( requestContext [ "endTime" ] ) ) values = range ( start , end , step ) series = TimeSeries ( name , start , end , step , values ) series . pathExpression = 'identity("%s")' % name return [ series ]
def get_page_dpi ( pageinfo , options ) : "Get the DPI when nonsquare DPI is tolerable"
xres = max ( pageinfo . xres or VECTOR_PAGE_DPI , options . oversample or 0 , VECTOR_PAGE_DPI if pageinfo . has_vector else 0 , ) yres = max ( pageinfo . yres or VECTOR_PAGE_DPI , options . oversample or 0 , VECTOR_PAGE_DPI if pageinfo . has_vector else 0 , ) return ( float ( xres ) , float ( yres ) )
def populate_template_combobox ( self , path , unwanted_templates = None ) : """Helper method for populating template combobox . : param unwanted _ templates : List of templates that isn ' t an option . : type unwanted _ templates : list . . versionadded : 4.3.0"""
templates_dir = QtCore . QDir ( path ) templates_dir . setFilter ( QtCore . QDir . Files | QtCore . QDir . NoSymLinks | QtCore . QDir . NoDotAndDotDot ) templates_dir . setNameFilters ( [ '*.qpt' , '*.QPT' ] ) report_files = templates_dir . entryList ( ) if not unwanted_templates : unwanted_templates = [ ] for unwa...
def fetch_node_status ( member ) : """This function perform http get request on member . api _ url and fetches its status : returns : ` _ MemberStatus ` object"""
try : response = requests . get ( member . api_url , timeout = 2 , verify = False ) logger . info ( 'Got response from %s %s: %s' , member . name , member . api_url , response . content ) return _MemberStatus . from_api_response ( member , response . json ( ) ) except Exception as e : logger . warning (...
def check_attributes ( self , opts = None ) : """check for attributes and moves them into the dictionary"""
if opts is None : opts = self if 1 < 3 : # the problem with merge is that ` ` opts [ ' ftarget ' ] = new _ value ` ` # would be overwritten by the old ` ` opts . ftarget ` ` . # The solution here is to empty opts . _ _ dict _ _ after the merge if hasattr ( opts , '__dict__' ) : for key in list ( opts . ...
def _EccZmaxRperiRap ( self , * args , ** kwargs ) : """NAME : EccZmaxRperiRap ( _ EccZmaxRperiRap ) PURPOSE : evaluate the eccentricity , maximum height above the plane , peri - and apocenter in the Staeckel approximation INPUT : Either : a ) R , vR , vT , z , vz [ , phi ] : 1 ) floats : phase - spac...
delta = kwargs . get ( 'delta' , self . _delta ) umin , umax , vmin = self . _uminumaxvmin ( * args , ** kwargs ) rperi = bovy_coords . uv_to_Rz ( umin , nu . pi / 2. , delta = delta ) [ 0 ] rap_tmp , zmax = bovy_coords . uv_to_Rz ( umax , vmin , delta = delta ) rap = nu . sqrt ( rap_tmp ** 2. + zmax ** 2. ) e = ( rap ...
def movnam_hdu ( self , extname , hdutype = ANY_HDU , extver = 0 ) : """Move to the indicated HDU by name In general , it is not necessary to use this method explicitly . returns the one - offset extension number"""
extname = mks ( extname ) hdu = self . _FITS . movnam_hdu ( hdutype , extname , extver ) return hdu
def resample ( self , N ) : """Returns a bootstrap resampling of provided samples . Parameters N : int Number of samples ."""
inds = rand . randint ( len ( self . samples ) , size = N ) return self . samples [ inds ]
def rvalue ( ddtt ) : """R value ( W / K ) of a construction or material . thickness ( m ) / conductivity ( W / m - K )"""
object_type = ddtt . obj [ 0 ] if object_type == 'Construction' : rvalue = INSIDE_FILM_R + OUTSIDE_FILM_R layers = ddtt . obj [ 2 : ] field_idd = ddtt . getfieldidd ( 'Outside_Layer' ) validobjects = field_idd [ 'validobjects' ] for layer in layers : found = False for key in validobj...
def run_without_time_limit ( self , cmd ) : """Runs docker command without time limit . Args : cmd : list with the command line arguments which are passed to docker binary Returns : how long it took to run submission in seconds Raises : WorkerError : if error occurred during execution of the submissio...
cmd = [ DOCKER_BINARY , 'run' , DOCKER_NVIDIA_RUNTIME ] + cmd logging . info ( 'Docker command: %s' , ' ' . join ( cmd ) ) start_time = time . time ( ) retval = subprocess . call ( cmd ) elapsed_time_sec = int ( time . time ( ) - start_time ) logging . info ( 'Elapsed time of attack: %d' , elapsed_time_sec ) logging . ...
def reroute ( self , body = None , params = None ) : """Explicitly execute a cluster reroute allocation command including specific commands . ` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / cluster - reroute . html > ` _ : arg body : The definition of ` commands ` to perfo...
return self . transport . perform_request ( 'POST' , '/_cluster/reroute' , params = params , body = body )
def build_target_areas ( entry ) : """Cleanup the raw target areas description string"""
target_areas = [ ] areas = str ( entry [ 'cap:areaDesc' ] ) . split ( ';' ) for area in areas : target_areas . append ( area . strip ( ) ) return target_areas
def decrement ( self , key , cache = None , amount = 1 ) : """A convenience function for passing negative values to increment . Keyword arguments : key - - the key the item is stored under . Required . cache - - the cache the item belongs to . Defaults to None , which uses self . name . If no name is set , ...
amount = amount * - 1 return self . increment ( key = key , cache = cache , amount = amount )
def _parse_args ( ) : """Parse sys . argv arguments"""
token_file = os . path . expanduser ( '~/.nikeplus_access_token' ) parser = argparse . ArgumentParser ( description = 'Export NikePlus data to CSV' ) parser . add_argument ( '-t' , '--token' , required = False , default = None , help = ( 'Access token for API, can also store in file %s' ' to avoid passing via command l...
def set_widgets ( self ) : """Set widgets on the Hazard Layer From Browser tab ."""
self . tvBrowserHazard_selection_changed ( ) # Set icon hazard = self . parent . step_fc_functions1 . selected_value ( layer_purpose_hazard [ 'key' ] ) icon_path = get_image_path ( hazard ) self . lblIconIFCWHazardFromBrowser . setPixmap ( QPixmap ( icon_path ) )
def load_toml_rest_api_config ( filename ) : """Returns a RestApiConfig created by loading a TOML file from the filesystem ."""
if not os . path . exists ( filename ) : LOGGER . info ( "Skipping rest api loading from non-existent config file: %s" , filename ) return RestApiConfig ( ) LOGGER . info ( "Loading rest api information from config: %s" , filename ) try : with open ( filename ) as fd : raw_config = fd . read ( ) exc...
def get_linkrect_idx ( self , pos ) : """Determine if cursor is inside one of the link hot spots ."""
for i , r in enumerate ( self . link_rects ) : if r . Contains ( pos ) : return i return - 1
def perform ( self , command , params = None , ** kwargs ) : """Execute a command . Arguments can be supplied either as a dictionary or as keyword arguments . Examples : stc . perform ( ' LoadFromXml ' , { ' filename ' : ' config . xml ' } ) stc . perform ( ' LoadFromXml ' , filename = ' config . xml ' ) ...
self . _check_session ( ) if not params : params = { } if kwargs : params . update ( kwargs ) params [ 'command' ] = command status , data = self . _rest . post_request ( 'perform' , None , params ) return data
def get_area_dates ( bbox , date_interval , maxcc = None ) : """Get list of times of existing images from specified area and time range : param bbox : bounding box of requested area : type bbox : geometry . BBox : param date _ interval : a pair of time strings in ISO8601 format : type date _ interval : tupl...
area_info = get_area_info ( bbox , date_interval , maxcc = maxcc ) return sorted ( { datetime . datetime . strptime ( tile_info [ 'properties' ] [ 'startDate' ] . strip ( 'Z' ) , '%Y-%m-%dT%H:%M:%S' ) for tile_info in area_info } )
def drop_zero_priors ( self ) : '''Returns PriorFactory'''
self . term_doc_mat = self . term_doc_mat . remove_terms ( self . priors [ self . priors == 0 ] . index ) self . _reindex_priors ( ) return self
def query_alternative_short_name ( ) : """Returns list of alternative short name by query query parameters tags : - Query functions parameters : - name : name in : query type : string required : false description : Alternative short name default : CVAP - name : entry _ name in : query type :...
args = get_args ( request_args = request . args , allowed_str_args = [ 'name' , 'entry_name' ] , allowed_int_args = [ 'limit' ] ) return jsonify ( query . alternative_short_name ( ** args ) )
def get_asset_temporal_assignment_session_for_repository ( self , repository_id , proxy ) : """Gets the session for assigning temporal coverage of an asset for the given repository . arg : repository _ id ( osid . id . Id ) : the Id of the repository arg proxy ( osid . proxy . Proxy ) : a proxy return : ( o...
if not repository_id : raise NullArgument ( ) if not self . supports_asset_temporal_assignment ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( 'import error' ) proxy = self . _convert_proxy ( proxy ) try : session = sessions . AssetTemporalAssi...
async def _pixy_data ( self , data ) : """This is a private message handler method . It handles pixy data messages . : param data : pixy data : returns : None - but update is saved in the digital pins structure"""
if len ( self . digital_pins ) < PrivateConstants . PIN_PIXY_MOSI : # Pixy data sent before board finished pin discovery . # print ( " Pixy data sent before board finished pin discovery . " ) return # strip off sysex start and end data = data [ 1 : - 1 ] num_blocks = data [ 0 ] # First byte is the number of blocks ...
def reverse_lookup ( self , value , condition = is_active ) : '''take a field _ name _ id and return the label'''
label = get_value_label ( value , self . _picklist , condition = condition ) return label
def get_attributes ( self , template_pack = TEMPLATE_PACK ) : """Used by crispy _ forms _ tags to get helper attributes"""
items = { 'form_method' : self . form_method . strip ( ) , 'form_tag' : self . form_tag , 'form_style' : self . form_style . strip ( ) , 'form_show_errors' : self . form_show_errors , 'help_text_inline' : self . help_text_inline , 'error_text_inline' : self . error_text_inline , 'html5_required' : self . html5_required...
def create_section ( self , attribute , name = None ) : '''create a section based on key , value recipe pairs , This is used for files or label Parameters attribute : the name of the data section , either labels or files name : the name to write to the recipe file ( e . g . , % name ) . if not defined , t...
# Default section name is the same as attribute if name is None : name = attribute # Put a space between sections section = [ '\n' ] # Only continue if we have the section and it ' s not empty try : section = getattr ( self , attribute ) except AttributeError : bot . debug ( 'Recipe does not have section fo...
def prepare ( self ) : '''Run the preparation sequence required to start a salt - api daemon . If sub - classed , don ' t * * ever * * forget to run : super ( YourSubClass , self ) . prepare ( )'''
super ( SaltAPI , self ) . prepare ( ) try : if self . config [ 'verify_env' ] : logfile = self . config [ 'log_file' ] if logfile is not None and not logfile . startswith ( ( 'tcp://' , 'udp://' , 'file://' ) ) : # Logfile is not using Syslog , verify with salt . utils . files . set_uma...
def _execute_simple_query ( self , query ) : """Send the query to the server using the simple query protocol . Return True if this query contained no SQL ( e . g . the string " - - comment " )"""
self . _logger . info ( u'Execute simple query: [{}]' . format ( query ) ) # All of the statements in the query are sent here in a single message self . connection . write ( messages . Query ( query ) ) # The first response could be a number of things : # ErrorResponse : Something went wrong on the server . # EmptyQuer...
def find_packages_requirements_dists ( pkg_names , working_set = None ) : """Return the entire list of dependency requirements , reversed from the bottom ."""
working_set = working_set or default_working_set requirements = [ r for r in ( Requirement . parse ( req ) for req in pkg_names ) if working_set . find ( r ) ] return list ( reversed ( working_set . resolve ( requirements ) ) )
def _create_cached_db ( db_path , tables , version = 1 ) : """Either create or retrieve sqlite database . Parameters db _ path : str Path to sqlite3 database file tables : dict Dictionary mapping table names to datacache . DatabaseTable objects version : int , optional Version acceptable as cached dat...
require_string ( db_path , "db_path" ) require_iterable_of ( tables , DatabaseTable ) require_integer ( version , "version" ) # if the database file doesn ' t already exist and we encounter an error # later , delete the file before raising an exception delete_on_error = not exists ( db_path ) # if the database already ...
def _find_observable_paths ( extra_files = None ) : """Finds all paths that should be observed ."""
rv = set ( os . path . dirname ( os . path . abspath ( x ) ) if os . path . isfile ( x ) else os . path . abspath ( x ) for x in sys . path ) for filename in extra_files or ( ) : rv . add ( os . path . dirname ( os . path . abspath ( filename ) ) ) for module in list ( sys . modules . values ( ) ) : fn = getatt...
def _prepare_plot ( self , origin = ( 0 , 0 ) , indices = None , ax = None , fill = False , ** kwargs ) : """Prepare to plot the aperture ( s ) on a matplotlib ` ~ matplotlib . axes . Axes ` instance . Parameters origin : array _ like , optional The ` ` ( x , y ) ` ` position of the origin of the displayed ...
import matplotlib . pyplot as plt if ax is None : ax = plt . gca ( ) # This is necessary because the ` matplotlib . patches . Patch ` default # is ` ` fill = True ` ` . Here we make the default ` ` fill = False ` ` . kwargs [ 'fill' ] = fill plot_positions = copy . deepcopy ( self . positions ) if indices is not No...
def parse_yaml ( self , y ) : '''Parse a YAML specification of a condition into this object .'''
self . sequence = int ( y [ 'sequence' ] ) self . target_component = TargetExecutionContext ( ) . parse_yaml ( y [ 'targetComponent' ] ) if RTS_EXT_NS_YAML + 'properties' in y : for p in y . get ( RTS_EXT_NS_YAML + 'properties' ) : if 'value' in p : value = p [ 'value' ] else : ...
def _track ( self , state , live_defs , statements ) : """Given all live definitions prior to this program point , track the changes , and return a new list of live definitions . We scan through the action list of the new state to track the changes . : param state : The input state at that program point . : p...
# Make a copy of live _ defs self . _live_defs = live_defs . copy ( ) action_list = list ( state . history . recent_actions ) # Since all temporary variables are local , we simply track them in a dict self . _temp_variables = { } self . _temp_register_symbols = { } # All dependence edges are added to the graph either a...
def combo_serve ( request , path , client ) : """Handles generating a ' combo ' file for the given path . This is similar to what happens when we upload to S3 . Processors are applied , and we get the value that we would if we were serving from S3 . This is a good way to make sure combo files work as intended...
joinfile = path sourcefiles = msettings [ 'JOINED' ] [ path ] # Generate the combo file as a string . combo_data , dirname = combine_files ( joinfile , sourcefiles , client ) if path . endswith ( '.css' ) : mime_type = 'text/css' elif joinfile . endswith ( '.js' ) : mime_type = 'application/javascript' return H...
def get_format ( self ) : """Returns a RangeFormat instance with the format of this range"""
url = self . build_url ( self . _endpoints . get ( 'get_format' ) ) response = self . session . get ( url ) if not response : return None return self . range_format_constructor ( parent = self , ** { self . _cloud_data_key : response . json ( ) } )
def candles ( self , instrument , ** kwargs ) : """Fetch candlestick data for an instrument . Args : instrument : Name of the Instrument price : The Price component ( s ) to get candlestick data for . Can contain any combination of the characters " M " ( midpoint candles ) " B " ( bid candles ) and " ...
request = Request ( 'GET' , '/v3/instruments/{instrument}/candles' ) request . set_path_param ( 'instrument' , instrument ) request . set_param ( 'price' , kwargs . get ( 'price' ) ) request . set_param ( 'granularity' , kwargs . get ( 'granularity' ) ) request . set_param ( 'count' , kwargs . get ( 'count' ) ) request...
def _make_pretty_arguments ( arguments ) : """Makes the arguments description pretty and returns a formatted string if ` arguments ` starts with the argument prefix . Otherwise , returns None . Expected input : Arguments : * arg0 - . . . * arg0 - . . . Expected output : * * Arguments : * * * arg0 - ...
if arguments . startswith ( "\n Arguments:" ) : arguments = "\n" . join ( map ( lambda u : u [ 6 : ] , arguments . strip ( ) . split ( "\n" ) [ 1 : ] ) ) return "**Arguments:**\n\n%s\n\n" % arguments
def update_notification_command ( self , notif , contact , macromodulations , timeperiods , host_ref = None ) : """Update the notification command by resolving Macros And because we are just launching the notification , we can say that this contact has been notified : param notif : notification to send : ty...
cls = self . __class__ macrosolver = MacroResolver ( ) data = self . get_data_for_notifications ( contact , notif , host_ref ) notif . command = macrosolver . resolve_command ( notif . command_call , data , macromodulations , timeperiods ) if cls . enable_environment_macros or notif . enable_environment_macros : no...
def _deblend_source ( data , segment_img , npixels , nlevels = 32 , contrast = 0.001 , mode = 'exponential' , connectivity = 8 ) : """Deblend a single labeled source . Parameters data : array _ like The 2D array of the image . The should be a cutout for a single source . ` ` data ` ` should already be smoot...
from scipy import ndimage from skimage . morphology import watershed if nlevels < 1 : raise ValueError ( 'nlevels must be >= 1, got "{0}"' . format ( nlevels ) ) if contrast < 0 or contrast > 1 : raise ValueError ( 'contrast must be >= 0 or <= 1, got ' '"{0}"' . format ( contrast ) ) if connectivity == 4 : ...
def flatten_models ( models ) : "Create 1d - array containing all disctinct models from ` ` models ` ` ."
if isinstance ( models , MultiFitterModel ) : ans = [ models ] else : tasklist = MultiFitter . _compile_models ( models ) ans = MultiFitter . _flatten_models ( tasklist ) return ans
def __parse_validators ( self ) : """Parse the validator in the options to validators ."""
self . _validators = [ ] validators_json = self . _options . get ( 'validators' ) for validator_json in validators_json : self . _validators . append ( PropertyValidator . parse ( json = validator_json ) )
def get_standard ( self ) : """get list of allowed parameters"""
try : res = urlopen ( PARSELY_PAGE_SCHEMA ) except : return [ ] text = res . read ( ) if isinstance ( text , bytes ) : text = text . decode ( 'utf-8' ) tree = etree . parse ( StringIO ( text ) ) stdref = tree . xpath ( "//div/@about" ) return [ a . split ( ':' ) [ 1 ] for a in stdref ]
def _to_DOM ( self ) : """Dumps object data to a fully traversable DOM representation of the object . : returns : a ` ` xml . etree . Element ` ` object"""
last_weather = None if ( self . _last_weather and isinstance ( self . _last_weather , weather . Weather ) ) : last_weather = self . _last_weather . _to_DOM ( ) root_node = ET . Element ( 'station' ) station_name_node = ET . SubElement ( root_node , 'name' ) station_name_node . text = str ( self . _name ) station_id...
def need ( self , folder , page = None , perpage = None ) : """Returns lists of files which are needed by this device in order for it to become in sync . Args : folder ( str ) : page ( int ) : If defined applies pagination accross the collection of results . perpage ( int ) : If defined applies paginati...
assert isinstance ( page , int ) or page is None assert isinstance ( perpage , int ) or perpage is None return self . get ( 'need' , params = { 'folder' : folder , 'page' : page , 'perpage' : perpage } )
def calibration_template ( self ) : """Gets the template documentation for the both the tone curve calibration and noise calibration : returns : dict - - all information necessary to recreate calibration objects"""
temp = { } temp [ 'tone_doc' ] = self . tone_calibrator . stimulus . templateDoc ( ) comp_doc = [ ] for calstim in self . bs_calibrator . get_stims ( ) : comp_doc . append ( calstim . stateDict ( ) ) temp [ 'noise_doc' ] = comp_doc return temp
def _emiss_ee ( self , Eph ) : """Electron - electron bremsstrahlung emissivity per unit photon energy"""
if self . weight_ee == 0.0 : return np . zeros_like ( Eph ) gam = np . vstack ( self . _gam ) # compute integral with electron distribution emiss = c . cgs * trapz_loglog ( np . vstack ( self . _nelec ) * self . _sigma_ee ( gam , Eph ) , self . _gam , axis = 0 , ) return emiss
def add_done_callback ( self , func ) : """Add callback function to be run once the long running operation has completed - regardless of the status of the operation . : param callable func : Callback function that takes at least one argument , a completed LongRunningOperation . : raises : ValueError if the ...
if self . _done is None or self . _done . is_set ( ) : raise ValueError ( "Process is complete." ) self . _callbacks . append ( func )
def remove_label ( self , name ) : """Removes label ` ` name ` ` from this issue . : param str name : ( required ) , name of the label to remove : returns : bool"""
url = self . _build_url ( 'labels' , name , base_url = self . _api ) # Docs say it should be a list of strings returned , practice says it # is just a 204/404 response . I ' m tenatively changing this until I # hear back from Support . return self . _boolean ( self . _delete ( url ) , 204 , 404 )
async def get_state_json ( self , rr_state_builder : Callable [ [ 'Verifier' , str , int ] , Awaitable [ Tuple [ str , int ] ] ] , fro : int , to : int ) -> ( str , int ) : """Get rev reg state json , and its timestamp on the distributed ledger , from cached rev reg state frames list or distributed ledger , upd...
LOGGER . debug ( 'RevoCacheEntry.get_state_json >>> rr_state_builder: %s, fro: %s, to: %s' , rr_state_builder . __name__ , fro , to ) rv = await self . _get_update ( rr_state_builder , fro , to , False ) LOGGER . debug ( 'RevoCacheEntry.get_state_json <<< %s' , rv ) return rv
def handle ( self , message ) : '''Attempts to send a message to the specified destination in Slack . Extends Legobot . Lego . handle ( ) Args : message ( Legobot . Message ) : message w / metadata to send .'''
logger . debug ( message ) if Utilities . isNotEmpty ( message [ 'metadata' ] [ 'opts' ] ) : target = message [ 'metadata' ] [ 'opts' ] [ 'target' ] thread = message [ 'metadata' ] [ 'opts' ] . get ( 'thread' ) # pattern = re . compile ( ' @ ( [ a - zA - Z0-9 . _ - ] + ) ' ) pattern = re . compile ( '^@...
def trigger ( self ) : '''Trigger the target ( e . g . the victim application ) to start communication with the fuzzer .'''
assert ( self . controller ) self . _trigger ( ) self . logger . debug ( 'Waiting for mutation response. (timeout = %d)' % self . mutation_server_timeout ) res = self . response_sent_event . wait ( self . mutation_server_timeout ) if not res : # mark the controller ' s report as failed since we did not get a response f...
def list_observatories ( self ) : """Get the IDs of all observatories with have stored observations on this server . : return : a sequence of strings containing observatories IDs"""
response = requests . get ( self . base_url + '/obstories' ) . text return safe_load ( response )
def CreateNetworkConnectivity ( in_drainage_line , river_id , next_down_id , out_connectivity_file , file_geodatabase = None ) : """Creates Network Connectivity input CSV file for RAPID based on the Drainage Line shapefile with river ID and next downstream ID fields . Parameters in _ drainage _ line : str ...
ogr_drainage_line_shapefile_lyr , ogr_drainage_line_shapefile = open_shapefile ( in_drainage_line , file_geodatabase ) stream_id_array = [ ] next_down_id_array = [ ] for drainage_line_feature in ogr_drainage_line_shapefile_lyr : stream_id_array . append ( drainage_line_feature . GetField ( river_id ) ) next_dow...
def sine_wave ( frequency ) : """Emit a sine wave at the given frequency ."""
xs = tf . reshape ( tf . range ( _samples ( ) , dtype = tf . float32 ) , [ 1 , _samples ( ) , 1 ] ) ts = xs / FLAGS . sample_rate return tf . sin ( 2 * math . pi * frequency * ts )
def _log_statistics ( self ) : """Log statistics about the number of rows and number of rows per second ."""
rows_per_second_trans = self . _count_total / ( self . _time1 - self . _time0 ) rows_per_second_load = self . _count_transform / ( self . _time2 - self . _time1 ) rows_per_second_overall = self . _count_total / ( self . _time3 - self . _time0 ) self . _log ( 'Number of rows processed : {0:d}' . format ( self...
def blackbody ( self , T ) : """Calculate the contribution of a blackbody through this filter . * T * is the blackbody temperature in Kelvin . Returns a band - averaged spectrum in f _ λ units . We use the composite Simpson ' s rule to integrate over the points at which the filter response is sampled . Note...
from scipy . integrate import simps d = self . _ensure_data ( ) # factor of pi is going from specific intensity ( sr ^ - 1 ) to unidirectional # inner factor of 1e - 8 is Å to cm # outer factor of 1e - 8 is f _ λ in cm ^ - 1 to f _ λ in Å ^ - 1 from . cgs import blambda numer_samples = d . resp * np . pi * blambda ( ...
def notice ( self , target , msg ) : """Sends a NOTICE to an user or channel . : param target : user or channel to send to . : type target : str : param msg : message to send . : type msg : basestring"""
self . cmd ( u'NOTICE' , u'{0} :{1}' . format ( target , msg ) )
def activations ( self ) : """Loads sampled activations , which requires network access ."""
if self . _activations is None : self . _activations = _get_aligned_activations ( self ) return self . _activations
def plate_enlargement_factor_analytical ( amplitude , wavelength ) : r'''Calculates the enhancement factor of the sinusoidal waves of the plate heat exchanger . This is the multiplier for the flat plate area to obtain the actual area available for heat transfer . Obtained from the following integral : . . m...
b = 2. * amplitude return 2. * float ( ellipe ( - b * b * pi * pi / ( wavelength * wavelength ) ) ) / pi
def _FormatPropertyName ( self , property_name ) : """Formats a camel case property name as snake case . Args : property _ name ( str ) : property name in camel case . Returns : str : property name in snake case ."""
# TODO : Add Unicode support . fix_key = re . sub ( r'(.)([A-Z][a-z]+)' , r'\1_\2' , property_name ) return re . sub ( r'([a-z0-9])([A-Z])' , r'\1_\2' , fix_key ) . lower ( )
def knit ( self , input_file , opts_chunk = 'eval=FALSE' ) : """Use Knitr to convert the r - markdown input _ file into markdown , returning a file object ."""
# use temporary files at both ends to allow stdin / stdout tmp_in = tempfile . NamedTemporaryFile ( mode = 'w+' ) tmp_out = tempfile . NamedTemporaryFile ( mode = 'w+' ) tmp_in . file . write ( input_file . read ( ) ) tmp_in . file . flush ( ) tmp_in . file . seek ( 0 ) self . _knit ( tmp_in . name , tmp_out . name , o...
def bogus_kmers ( self , count = 200 ) : """m . bogus _ kmers ( count = 200 ) - - Generate a faked multiple sequence alignment that will reproduce the probability matrix ."""
POW = math . pow # Build p - value inspired matrix # Make totals cummulative : # A : 0.1 C : 0.4 T : 0.2 G : 0.3 # - > A : 0.0 C : 0.1 T : 0.5 G : 0.7 0.0 # Take bg into account : # We want to pick P ' for each letter such that : # P ' / 0.25 = P / Q # so P ' = 0.25 * P / Q m = [ ] for i in range ( self . width ) : ...
def sendgmail ( self , subject , recipients , plaintext , htmltext = None , cc = None , debug = False , useMIMEMultipart = True , gmail_account = 'kortemmelab@gmail.com' , pw_filepath = None ) : '''For this function to work , the password for the gmail user must be colocated with this file or passed in .'''
smtpserver = smtplib . SMTP ( "smtp.gmail.com" , 587 ) smtpserver . ehlo ( ) smtpserver . starttls ( ) smtpserver . ehlo gmail_account = 'kortemmelab@gmail.com' if pw_filepath : smtpserver . login ( gmail_account , read_file ( pw_filepath ) ) else : smtpserver . login ( gmail_account , read_file ( 'pw' ) ) for ...
def get_multi ( self , keys , get_cas = False ) : """Get multiple keys from server . : param keys : A list of keys to from server . : type keys : list : param get _ cas : If get _ cas is true , each value is ( data , cas ) , with each result ' s CAS value . : type get _ cas : boolean : return : A dict wit...
d = { } if keys : for server in self . servers : results = server . get_multi ( keys ) if not get_cas : # Remove CAS data for key , ( value , cas ) in results . items ( ) : results [ key ] = value d . update ( results ) keys = [ _ for _ in keys if _ not in...
def _encodeHeader ( headerValue ) : """Encodes a header value . Returns ASCII if possible , else returns an UTF - 8 encoded e - mail header ."""
try : return headerValue . encode ( 'ascii' , 'strict' ) except UnicodeError : encoded = headerValue . encode ( "utf-8" ) return header . Header ( encoded , "UTF-8" ) . encode ( )
def find_field_name ( field , model = DEFAULT_MODEL , app = DEFAULT_APP , fuzziness = .5 ) : """> > > find _ field _ name ( ' date _ time ' , model = ' WikiItem ' ) ' date ' > > > find _ field _ name ( ' $ # ! @ ' , model = ' WikiItem ' ) > > > find _ field _ name ( ' date ' , model = ' WikiItem ' ) ' end _...
return find_field_names ( field , model , app , score_cutoff = int ( ( 1 - fuzziness ) * 100 ) , pad_with_none = True ) [ 0 ]
def container ( self ) : """Rarely used attribute that returns the ` ` ListContainer ` ` or ` ` DictContainer ` ` that contains the element ( or returns None if no such container exist ) : rtype : ` ` ListContainer ` ` | ` ` DictContainer ` ` | ` ` None ` `"""
if self . parent is None : return None elif self . location is None : return self . parent . content else : container = getattr ( self . parent , self . location ) if isinstance ( container , ( ListContainer , DictContainer ) ) : return container else : assert self is container
def simple_host_process ( argslist ) : """Call vamp - simple - host"""
vamp_host = 'vamp-simple-host' command = [ vamp_host ] command . extend ( argslist ) # try ? stdout = subprocess . check_output ( command , stderr = subprocess . STDOUT ) . splitlines ( ) return stdout
def GetNearestStops ( self , lat , lon , n = 1 ) : """Return the n nearest stops to lat , lon"""
dist_stop_list = [ ] for s in self . stops . values ( ) : # TODO : Use util . ApproximateDistanceBetweenStops ? dist = ( s . stop_lat - lat ) ** 2 + ( s . stop_lon - lon ) ** 2 if len ( dist_stop_list ) < n : bisect . insort ( dist_stop_list , ( dist , s ) ) elif dist < dist_stop_list [ - 1 ] [ 0 ] ...
def remove_class ( self , cssclass ) : """Removes the given class from this element ."""
if not self . has_class ( cssclass ) : return self return self . toggle_class ( cssclass )
def in_path ( self , new_path , old_path = None ) : """Temporarily enters a path ."""
self . path = new_path try : yield finally : self . path = old_path
def _plugin_targets ( self , compiler ) : """Returns a map from plugin name to the targets that build that plugin ."""
if compiler == 'javac' : plugin_cls = JavacPlugin elif compiler == 'scalac' : plugin_cls = ScalacPlugin else : raise TaskError ( 'Unknown JVM compiler: {}' . format ( compiler ) ) plugin_tgts = self . context . targets ( predicate = lambda t : isinstance ( t , plugin_cls ) ) return { t . plugin : t . closur...
def get_vlan ( self , vlan_id ) : """Returns information about a single VLAN . : param int id : The unique identifier for the VLAN : returns : A dictionary containing a large amount of information about the specified VLAN ."""
return self . vlan . getObject ( id = vlan_id , mask = DEFAULT_GET_VLAN_MASK )
def get_path ( self , prefix = None , filename = None ) : """Compose data location path ."""
prefix = prefix or settings . FLOW_EXECUTOR [ 'DATA_DIR' ] path = os . path . join ( prefix , self . subpath ) if filename : path = os . path . join ( path , filename ) return path
def replaceSelected ( self ) : """Replace the currently selected string with the new one . The method return * * False * * if another match to the right of the cursor exists , and * * True * * if not ( ie . when the end of the document was reached ) ."""
SCI = self . qteWidget # Restore the original styling . self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleOrig ) # Select the region spanned by the string to replace . start , stop = self . matchList [ self . selMatchIdx ] line1 , col1 = SCI . lineIndexFromPosition ( start ) line2 , col2 = SCI . lineIndexFromPos...
def schema ( name , dct , * , strict = False ) : """Create a compound tag schema . This function is a short convenience function that makes it easy to subclass the base ` CompoundSchema ` class . The ` name ` argument is the name of the class and ` dct ` should be a dictionnary containing the actual schema ...
return type ( name , ( CompoundSchema , ) , { '__slots__' : ( ) , 'schema' : dct , 'strict' : strict } )
def verification_cancel ( self , verification_id , reason = None ) : """Cancels a started verification . Uses PUT to / verifications / < verification _ id > interface : Args : * * verification _ id * : ( str ) Verification ID : Kwargs : * * reason * : ( str ) Reason for cancelling the verification : Retur...
data = { "cancel" : True , "cancel_reason" : reason } response = self . _put ( url . verifications_id . format ( id = verification_id ) , body = data ) self . _check_response ( response , 202 )
def get_duration ( self ) : """Get game duration ."""
postgame = self . get_postgame ( ) if postgame : return postgame . duration_int * 1000 duration = self . _header . initial . restore_time try : while self . _handle . tell ( ) < self . size : operation = mgz . body . operation . parse_stream ( self . _handle ) if operation . type == 'sync' : ...
def add_provide ( self , provide ) : """Add a provide object if it does not already exist"""
for p in self . provides : if p . value == provide . value : return self . provides . append ( provide )
def get_event_log ( self , object_id ) : """Get the specified event log ."""
content = self . _fetch ( "/event_log/%s" % object_id , method = "GET" ) return FastlyEventLog ( self , content )
def explain_prediction_linear_regressor ( reg , doc , vec = None , top = None , top_targets = None , target_names = None , targets = None , feature_names = None , feature_re = None , feature_filter = None , vectorized = False ) : """Explain prediction of a linear regressor . See : func : ` eli5 . explain _ predic...
if isinstance ( reg , ( SVR , NuSVR ) ) and reg . kernel != 'linear' : return explain_prediction_sklearn_not_supported ( reg , doc ) vec , feature_names = handle_vec ( reg , doc , vec , vectorized , feature_names ) X = get_X ( doc , vec = vec , vectorized = vectorized , to_dense = True ) score , = reg . predict ( X...
def publish ( endpoint , purge_files , rebuild_manifest , skip_upload ) : """Publish the site"""
print ( "Publishing site to %s ..." % endpoint . upper ( ) ) yass = Yass ( CWD ) target = endpoint . lower ( ) sitename = yass . sitename if not sitename : raise ValueError ( "Missing site name" ) endpoint = yass . config . get ( "hosting.%s" % target ) if not endpoint : raise ValueError ( "%s endpoint is missi...
def handle_error ( r , expected_code ) : """Helper function to match reponse of a request to the expected status code : param r : This field is the response of request . : param expected _ code : This field is the expected status code for the function ."""
code = r . status_code if code != expected_code : info = 'API response status code {}' . format ( code ) try : if 'detail' in r . json ( ) : info = info + ": {}" . format ( r . json ( ) [ 'detail' ] ) elif 'metadata' in r . json ( ) : info = info + ": {}" . format ( r . j...
def numeric_string_sorter ( numeric_strings ) : """Sorts a list of numeric strings in ascending numerical order . This function takes a list of numeric strings , converts the strings into integers , sorts the integers in ascending order and then return the sorted list . Args : numeric _ strings ( list ) : s...
converted_numbers = [ int ( num ) for num in numeric_strings ] sorted_list = sorted ( converted_numbers ) return sorted_list
def create_group ( self , name ) : """Create a group by given group parameter : param name : str : return : New group params"""
url = 'rest/api/2/group' data = { 'name' : name } return self . post ( url , data = data )
def add_text_memo ( self , memo_text ) : """Set the memo for the transaction to a new : class : ` TextMemo < stellar _ base . memo . TextMemo > ` . : param memo _ text : The text for the memo to add . : type memo _ text : str , bytes : return : This builder instance ."""
memo_text = memo . TextMemo ( memo_text ) return self . add_memo ( memo_text )
def import_users ( self ) : """save users to local DB"""
self . message ( 'saving users into local DB' ) saved_users = self . saved_admins # loop over all extracted unique email addresses for email in self . email_set : owner = self . users_dict [ email ] . get ( 'owner' ) # if owner is not specified , build username from email if owner . strip ( ) == '' : ...
def load ( cls , path ) : """Loads an instance of the class from a file . Parameters path : str Path to an HDF5 file . Examples This is an abstract data type , but let us say that ` ` Foo ` ` inherits from ` ` Saveable ` ` . To construct an object of this class from a file , we do : > > > foo = Foo ...
if path is None : return cls . load_from_dict ( { } ) else : d = io . load ( path ) return cls . load_from_dict ( d )
def output ( self , _filename ) : """_ filename is not used Args : _ filename ( string )"""
txt = '' for c in self . contracts : txt += "\nContract %s\n" % c . name table = PrettyTable ( [ 'Variable' , 'Dependencies' ] ) for v in c . state_variables : table . add_row ( [ v . name , _get ( v , c ) ] ) txt += str ( table ) txt += "\n" for f in c . functions_and_modifiers_not_inhe...
def start_segment_address ( cs , ip ) : """Return Start Segment Address Record . @ param cs 16 - bit value for CS register . @ param ip 16 - bit value for IP register . @ return String representation of Intel Hex SSA record ."""
b = [ 4 , 0 , 0 , 0x03 , ( cs >> 8 ) & 0x0FF , cs & 0x0FF , ( ip >> 8 ) & 0x0FF , ip & 0x0FF ] return Record . _from_bytes ( b )
def _write_subset_index_file ( options , core_results ) : """Write table giving index of subsets , giving number and subset string"""
f_path = os . path . join ( options [ 'run_dir' ] , '_subset_index.csv' ) subset_strs = zip ( * core_results ) [ 0 ] index = np . arange ( len ( subset_strs ) ) + 1 df = pd . DataFrame ( { 'subsets' : subset_strs } , index = index ) df . to_csv ( f_path )
def setLanguage ( self , language ) : """Sets the language for this code . : param language | < str >"""
cls = XCodeHighlighter . byName ( language ) if cls : self . _highlighter = cls ( self . document ( ) )
def watch_process ( self , process ) : """Manages the status of a single process"""
status = process [ "psutil" ] . status ( ) # TODO : how to avoid zombies ? # print process [ " pid " ] , status if process . get ( "terminate" ) : if status in ( "zombie" , "dead" ) : process [ "dead" ] = True elif process . get ( "terminate_at" ) : if time . time ( ) > ( process [ "terminate_at...
def find_packages_parents_requirements_dists ( pkg_names , working_set = None ) : """Leverages the ` find _ packages _ requirements _ dists ` but strip out the distributions that matches pkg _ names ."""
dists = [ ] # opting for a naive implementation targets = set ( pkg_names ) for dist in find_packages_requirements_dists ( pkg_names , working_set ) : if dist . project_name in targets : continue dists . append ( dist ) return dists
def hide_virtual_ip_holder_chassis_virtual_ipv6 ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) hide_virtual_ip_holder = ET . SubElement ( config , "hide-virtual-ip-holder" , xmlns = "urn:brocade.com:mgmt:brocade-chassis" ) chassis = ET . SubElement ( hide_virtual_ip_holder , "chassis" ) virtual_ipv6 = ET . SubElement ( chassis , "virtual-ipv6" ) virtual_ipv6 . text = kwargs . p...
def commit ( self , comment = "" , delay_factor = 1 ) : """Commit the candidate configuration . Commit the entered configuration . Raise an error and return the failure if the commit fails . default : command _ string = commit comment : command _ string = commit comment < comment >"""
delay_factor = self . select_delay_factor ( delay_factor ) error_marker = "Failed to generate committed config" command_string = "commit" if comment : command_string += ' comment "{}"' . format ( comment ) output = self . config_mode ( ) output += self . send_command_expect ( command_string , strip_prompt = False ,...
def prior_GP_var_half_cauchy ( y_invK_y , n_y , tau_range ) : """Imposing a half - Cauchy prior onto the standard deviation ( tau ) of the Gaussian Process which is in turn a prior imposed over a function y = f ( x ) . The scale parameter of the half - Cauchy prior is tau _ range . The function returns the ...
tau2 = ( y_invK_y - n_y * tau_range ** 2 + np . sqrt ( n_y ** 2 * tau_range ** 4 + ( 2 * n_y + 8 ) * tau_range ** 2 * y_invK_y + y_invK_y ** 2 ) ) / 2 / ( n_y + 2 ) log_ptau = scipy . stats . halfcauchy . logpdf ( tau2 ** 0.5 , scale = tau_range ) return tau2 , log_ptau
def start ( self ) : """Start the server ( s ) necessary to receive information from devices ."""
if self . _with_discovery : # Start the server to listen to new devices self . upnp . server . set_spawn ( 2 ) self . upnp . server . start ( ) if self . _with_subscribers : # Start the server to listen to events self . registry . server . set_spawn ( 2 ) self . registry . server . start ( )