output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
create a list of dictionaries containing all the rows in the catalogue
Can you generate a brief explanation for the following Python 3 code def _create_dictionary_of_veron( self): """create a list of dictionaries containing all the rows in the veron catalogue **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the veron c...
You are a Python code generator, capable of creating scripts from specifications.
This is the main function used by the cl_utils. py script.
Make a summary of the following Python 3 code def main(arguments=None): # setup the command-line util settings su = tools( arguments=arguments, docString=__doc__, logLevel="WARNING", options_first=False, projectName="sherlock" ) arguments, settings, log, dbConn =...
As a Python code translator, you convert algorithms and pseudocode into Python.
def display(self, display_before=False): """shows the effect of this filter""" try: copy = self.image.copy() except AttributeError: raise Exception("You need to set the Filter.image attribute for displaying") copy = BrightnessProcessor(brightness=0.6).process(copy...
Can you implement a function in Python 3 that displays the effect of this filter
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_mip_analysis(mip_config_raw: dict, qcmetrics_raw: dict, sampleinfo_raw: dict) -> dict: """Parse the output analysis files from MIP for adding info to trend database Args: mip_config_raw (dict): raw YAML input from MIP analysis config file qcmetrics_raw (dict): raw YAML input from ...
Implement a Python 3 function for parsing the output analysis files from MIP for adding info to trend database
You are a Python code architect, reviewing and designing scalable and efficient code
def clean(self): """*clean up and run some maintance tasks on the crossmatch catalogue helper tables* .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update ...
Implement a Python 3 function for cleaning up and run some maintenance tasks on the crossmatch catalogue helper tables and views
You are a Python code architect, reviewing and designing scalable and efficient code
update row counts in tcs catalogue tables info
How would you explain what the following Python 3 function does def _updated_row_counts_in_tcs_helper_catalogue_tables_info( self): """ updated row counts in tcs catalogue tables .. todo :: - update key arguments values and definitions with defaults - update return ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _update_tcs_helper_catalogue_tables_info_with_new_tables( self): """update tcs helper catalogue tables info with new tables .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage e...
How would you implement a function in Python 3 that updates tcs helper catalogue tables info with new tables
As a Python code translator, you convert algorithms and pseudocode into Python.
def _clean_up_columns( self): """clean up columns .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check subli...
Implement a function in Python 3 to clean up the columns of the tcs_helper_catalogue_tables_info table_name and views_name.
You are a Python code architect, reviewing and designing scalable and efficient code
update tcs helper catalogue tables info with new tables
Can you generate a brief explanation for the following Python 3 code def _update_tcs_helper_catalogue_views_info_with_new_views( self): """ update tcs helper catalogue tables info with new tables .. todo :: - update key arguments values and definitions with defaults ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Restart listener after configuration update.
Given the following Python 3 function, write the documentation def restart_listener(self, topics): '''Restart listener after configuration update. ''' if self.listener is not None: if self.listener.running: self.stop() self.__init__(topics=topics)
You are a Python code architect, reviewing and designing scalable and efficient code
def stop(self): '''Stop listener.''' self.logger.debug("Stopping listener.") self.listener.stop() if self.thread is not None: self.thread.join() self.thread = None self.logger.debug("Listener stopped.")
Can you write a function in Python 3 where it stops the listener thread.
As a python code expert, you are capable of creating scripts from specifications.
Create a subscriber instance using specified addresses and message types.
Can you tell what is the following Python 3 function doing def create_subscriber(self): '''Create a subscriber instance using specified addresses and message types. ''' if self.subscriber is None: if self.topics: self.subscriber = NSSubscriber(self.services, s...
As a python code expert, you are capable of creating scripts from specifications.
Stop subscriber and delete the instance
Make a summary of the following Python 3 code def stop(self): '''Stop subscriber and delete the instance ''' self.running = False time.sleep(1) if self.subscriber is not None: self.subscriber.stop() self.subscriber = None
As a Python code analyst, you investigate and solve complex coding mysteries
def get_current_semver(data): """Given a dictionary of all version data available, determine the current version""" # get the not-none values from data known = { key: data.get(alias) for key, alias in config._forward_aliases.items() if data.get(alias) is not None } # prefer ...
Can you write a function in Python 3 where it gives a dictionary of all version data available determine the current version
As a python code expert, you are capable of creating scripts from specifications.
def make_new_semver(current_semver, all_triggers, **overrides): """Defines how to increment semver based on which significant figure is triggered""" new_semver = {} bumped = False for sig_fig in SemVerSigFig: # iterate sig figs in order of significance value = getattr(current_semver, sig_fig) ...
Write a Python 3 script for defining how to increment semver based on which significant figure is triggered
As a Python code translator, you convert algorithms and pseudocode into Python.
def loads(data): """Parser entry point. Parses the output of a traceroute execution""" data += "\n_EOS_" # Append EOS token. Helps to match last RE_HOP # Get headers match_dest = RE_HEADER.search(data) dest_name = match_dest.group(1) dest_ip = match_dest.group(2) # The Traceroute is the ro...
Write a Python 3 script for parsing the output of a traceroute execution into a tree structure.
You are a Python code analyst, evaluating scripts for potential improvements.
def add_probe(self, probe): """Adds a Probe instance to this hop's results.""" if self.probes: probe_last = self.probes[-1] if not probe.ip: probe.ip = probe_last.ip probe.name = probe_last.name self.probes.append(probe)
Write a Python 3 function for adding a Probe instance to this hop s results.
You are a Python code analyst, evaluating scripts for potential improvements.
def synchronized(func, *args, **kwargs): """Function decorator to make function synchronized on ``self._lock``. If the first argument to the function (hopefully self) does not have a _lock attribute, then this decorator does nothing. """ if not (args and hasattr(args[0], '_lock')): return f...
How would you code a function in Python 3 to function decorator to make function synchronized on self. _lock.
You are a Python code generator, capable of creating scripts from specifications.
Normalizes a value to a job id.
Given the following Python 3 function, write the documentation def normalize_job_id(job_id): if not isinstance(job_id, uuid.UUID): job_id = uuid.UUID(job_id) return job_id
As a Python code composer, you craft elegant and concise scripts.
def now(self): """ Return a :py:class:`datetime.datetime` instance representing the current time. :rtype: :py:class:`datetime.datetime` """ if self.use_utc: return datetime.datetime.utcnow() else: return datetime.datetime.now()
Can you implement a function in Python 3 that returns a : py : class : datetime. datetime instance representing the current time.
As a Python code analyst, you investigate and solve complex coding mysteries
def start(self): """ Start the JobManager thread. """ if self._thread_running.is_set(): raise RuntimeError('the JobManager has already been started') self._thread.start() self._thread_running.wait() return
Write a Python 3 function that can start the JobManager thread.
As a Python code composer, you craft elegant and concise scripts.
def stop(self): """ Stop the JobManager thread. """ self.logger.debug('stopping the job manager') self._thread_running.clear() self._thread_shutdown.wait() self._job_lock.acquire() self.logger.debug('waiting on ' + str(len(self._jobs)) + ' job threads') for job_desc in self._jobs.values(): if job_d...
How would you implement a function in Python 3 that stops the JobManager thread.
As a python code expert, you are capable of creating scripts from specifications.
def job_run(self, callback, parameters=None): """ Add a job and run it once immediately. :param function callback: The function to run asynchronously. :param parameters: The parameters to be provided to the callback. :type parameters: list, tuple :return: The job id. :rtype: :py:class:`uuid.UUID` """ ...
Write a Python 3 script for adding a job and run it once immediately.
You are a Python code analyst, evaluating scripts for potential improvements.
def job_add(self, callback, parameters=None, hours=0, minutes=0, seconds=0, tolerate_exceptions=True, expiration=None): """ Add a job to the job manager. :param function callback: The function to run asynchronously. :param parameters: The parameters to be provided to the callback. :type parameters: list, tup...
Write a Python 3 function for adding a job to the job manager.
As a Python code composer, you craft elegant and concise scripts.
def job_count_enabled(self): """ Return the number of enabled jobs. :return: The number of jobs that are enabled. :rtype: int """ enabled = 0 for job_desc in self._jobs.values(): if job_desc['enabled']: enabled += 1 return enabled
Write a Python 3 function for returning the number of enabled jobs.
You are a Python code architect, reviewing and designing scalable and efficient code
Enable a job. :param job_id: Job identifier to enable. :type job_id: :py:class:`uuid.UUID`
Given the following Python 3 function, write the documentation def job_enable(self, job_id): job_id = normalize_job_id(job_id) with self._job_lock: job_desc = self._jobs[job_id] job_desc['enabled'] = True
You are a Python code analyst, evaluating scripts for potential improvements.
Disable a job. Disabled jobs will not be executed. :param job_id: Job identifier to disable. :type job_id: :py:class:`uuid.UUID`
Make a summary of the following Python 3 code def job_disable(self, job_id): job_id = normalize_job_id(job_id) with self._job_lock: job_desc = self._jobs[job_id] job_desc['enabled'] = False
You are a Python code architect, reviewing and designing scalable and efficient code
def job_delete(self, job_id, wait=True): """ Delete a job. :param job_id: Job identifier to delete. :type job_id: :py:class:`uuid.UUID` :param bool wait: If the job is currently running, wait for it to complete before deleting it. """ job_id = normalize_job_id(job_id) self.logger.info('deleting job wit...
Can you create a Python 3 function that deletes a job. :param job_id: Job identifier to delete. :type job_id: :py:class:`uuid.UUID` :param bool wait: If the job is currently running, wait for it to complete before deleting it.
As a python code expert, you are capable of creating scripts from specifications.
def job_is_enabled(self, job_id): """ Check if a job is enabled. :param job_id: Job identifier to check the status of. :type job_id: :py:class:`uuid.UUID` :rtype: bool """ job_id = normalize_job_id(job_id) job_desc = self._jobs[job_id] return job_desc['enabled']
How would you code a function in Python 3 to check if a job is enabled.
You are a Python code generator, capable of creating scripts from specifications.
def job_is_running(self, job_id): """ Check if a job is currently running. False is returned if the job does not exist. :param job_id: Job identifier to check the status of. :type job_id: :py:class:`uuid.UUID` :rtype: bool """ job_id = normalize_job_id(job_id) if job_id not in self._jobs: return F...
Can you write a function in Python 3 where it checks if a job is currently running. False is returned if the job does not exist.
You are a Python code analyst, evaluating scripts for potential improvements.
An argparse type representing binary data encoded in base64.
How would you explain what the following Python 3 function does def bin_b64_type(arg): try: arg = base64.standard_b64decode(arg) except (binascii.Error, TypeError): raise argparse.ArgumentTypeError("{0} is invalid base64 data".format(repr(arg))) return arg
As a Python code composer, you craft elegant and concise scripts.
An argparse type representing binary data encoded in hex.
Can you generate a brief explanation for the following Python 3 code def bin_hex_type(arg): if re.match(r'^[a-f0-9]{2}(:[a-f0-9]{2})+$', arg, re.I): arg = arg.replace(':', '') elif re.match(r'^(\\x[a-f0-9]{2})+$', arg, re.I): arg = arg.replace('\\x', '') try: arg = binascii.a2b_hex(arg) except (binascii.Error...
As a Python code composer, you craft elegant and concise scripts.
An argparse type representing a valid directory.
Can you tell what is the following Python 3 function doing def dir_type(arg): if not os.path.isdir(arg): raise argparse.ArgumentTypeError("{0} is not a valid directory".format(repr(arg))) return arg
As a Python code composer, you craft elegant and concise scripts.
An argparse type representing an email address.
Can you tell what is the following Python 3 function doing def email_type(arg): if not is_valid_email_address(arg): raise argparse.ArgumentTypeError("{0} is not a valid email address".format(repr(arg))) return arg
As a Python code analyst, you investigate and solve complex coding mysteries
An argparse type representing a logging level.
Can you generate a brief explanation for the following Python 3 code def log_level_type(arg): if not arg.upper() in ('NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'): raise argparse.ArgumentTypeError("{0} is not a valid log level".format(repr(arg))) return getattr(logging, arg.upper())
As a Python code composer, you craft elegant and concise scripts.
An argparse type representing a tcp or udp port number.
Make a summary of the following Python 3 code def port_type(arg): error_msg = "{0} is not a valid port".format(repr(arg)) try: arg = ast.literal_eval(arg) except ValueError: raise argparse.ArgumentTypeError(error_msg) if arg < 0 or arg > 65535: raise argparse.ArgumentTypeError(error_msg) return arg
You are a Python code generator, capable of creating scripts from specifications.
An argparse type representing a timespan such as 6h for 6 hours.
Make a summary of the following Python 3 code def timespan_type(arg): try: arg = parse_timespan(arg) except ValueError: raise argparse.ArgumentTypeError("{0} is not a valid time span".format(repr(arg))) return arg
You are a Python code generator, capable of creating scripts from specifications.
search the transient sources for the specified transient sources and return the list of transient sources that match the criteria
Can you tell what is the following Python 3 function doing def search(self): self.log.debug('starting the ``search`` method') # ACCOUNT FOR TYPE OF SEARCH sqlWhere = False magnitudeLimitFilter = self.magnitudeLimitFilter disCols = ["zColName", "distanceColName...
As a Python code translator, you convert algorithms and pseudocode into Python.
def angular_crossmatch_against_catalogue( self, objectList, searchPara={}, search_name="", brightnessFilter=False, physicalSearch=False, classificationType=False ): """*perform an angular separation crossmatch against a given catalogue in the database ...
How would you code a function in Python 3 to perform an angular crossmatch against a given catalogue
As a Python code analyst, you investigate and solve complex coding mysteries
This method is used to annotate each crossmatch with physical parameters.
How would you explain what the following Python 3 function does def _annotate_crossmatch_with_value_added_parameters( self, crossmatchDict, catalogueName, searchPara, search_name): """*annotate each crossmatch with physical parameters such are distance...
As a python code expert, you are capable of creating scripts from specifications.
def _bright_star_match( self, matchedObjects, catalogueName, magnitudeLimitFilter, lowerMagnitudeLimit): """*perform a bright star match on the crossmatch results if required by the catalogue search* **Key Arguments:** - ``matchedO...
How would you implement a function in Python 3 that performs a bright star match on the matched objects
As a Python code analyst, you investigate and solve complex coding mysteries
def _galaxy_association_cuts( self, matchedObjects, catalogueName, magnitudeLimitFilter, upperMagnitudeLimit, lowerMagnitudeLimit): """*perform a bright star match on the crossmatch results if required by the catalogue search* **Ke...
Write a Python 3 script for performing a bright star match on the matched objects and return a list of galaxies that match the given values.
You are a Python code architect, reviewing and designing scalable and efficient code
def physical_separation_crossmatch_against_catalogue( self, objectList, searchPara, search_name, brightnessFilter=False, classificationType=False ): """*perform an physical separation crossmatch against a given catalogue in the database* This search i...
Write a Python 3 script for performing an physical separation crossmatch against a given catalogue
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_own_ip(): """Get the host's ip number. """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.connect(("8.8.8.8", 80)) except socket.gaierror: ip_ = "127.0.0.1" else: ip_ = sock.getsockname()[0] finally: sock.close() return ip_
Can you implement a function in Python 3 that gets the host s ip number.
You are a Python code generator, capable of creating scripts from specifications.
def send(self, msg): """Send the given message. """ with self._pub_lock: self.publish.send_string(msg) return self
Write a Python 3 script for sending a message to the related user.
As a python code expert, you are capable of creating scripts from specifications.
Send a heartbeat... but only if min_interval * seconds have passed since last beat.
Explain what the following Python 3 code does def heartbeat(self, min_interval=0): if not self._heartbeat: self._heartbeat = _PublisherHeartbeat(self) self._heartbeat(min_interval)
You are a Python code analyst, evaluating scripts for potential improvements.
Simple light curve function.
Here you have a function in Python 3, explain what it does def light_curve(self, t, texp=0.0, tol=1e-8, maxdepth=4): t = np.atleast_1d(t) return CythonSolver().simple_light_curve(self._get_params(), t, texp, tol, maxdepth)
You are a Python code generator, capable of creating scripts from specifications.
Calculates the gradient of the light curve at a list of times using the current object s model.
Can you generate a brief explanation for the following Python 3 code def light_curve_gradient(self, t, texp=0.0, tol=1e-8, maxdepth=4): t = np.atleast_1d(t) f, df = CythonSolver().simple_gradient(self._get_params(), t, texp, tol, maxdepth) return f...
You are a Python code generator, capable of creating scripts from specifications.
Configure the default stream handler for logging messages to the console.
Explain what the following Python 3 code does def configure_stream_logger(logger='', level=None, formatter='%(levelname)-8s %(message)s'): level = level or logging.WARNING if isinstance(level, str): level = getattr(logging, level, None) if level is None: raise ValueError('invalid log level: ' + level) root_lo...
As a Python code translator, you convert algorithms and pseudocode into Python.
def download(url, filename=None): """ Download a file from a url and save it to disk. :param str url: The URL to fetch the file from. :param str filename: The destination file to write the data to. """ # requirements os, shutil, urllib.parse, urllib.request if not filename: url_parts = urllib.parse.urlparse(u...
How would you implement a function in Python 3 that downloads a file from a url and save it to disk.
You are a Python code architect, reviewing and designing scalable and efficient code
def format_bytes_size(val): """ Take a number of bytes and convert it to a human readable number. :param int val: The number of bytes to format. :return: The size in a human readable format. :rtype: str """ if not val: return '0 bytes' for sz_name in ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']: if val < ...
How would you implement a function in Python 3 that takes a number of bytes and convert it to a human readable number.
As a Python code analyst, you investigate and solve complex coding mysteries
Search a file and return a list of all the lines that match a regular expression.
Can you generate the documentation for the following Python 3 function def grep(expression, file, flags=0, invert=False): # requirements = re if isinstance(file, str): file = open(file) lines = [] for line in file: if bool(re.search(expression, line, flags=flags)) ^ invert: lines.append(line) return lines
You are a Python code analyst, evaluating scripts for potential improvements.
def open_uri(uri): """ Open a URI in a platform intelligent way. On Windows this will use 'cmd.exe /c start' and on Linux this will use gvfs-open or xdg-open depending on which is available. If no suitable application can be found to open the URI, a RuntimeError will be raised. .. versionadded:: 1.3.0 :param s...
Create a Python 3 function to open a URI in a platform intelligent way.
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_case_snake_to_camel(snake, upper_first=True): """ Convert a string from snake_case to CamelCase. :param str snake: The snake_case string to convert. :param bool upper_first: Whether or not to capitalize the first character of the string. :return: The CamelCase version of string. :rtype: str """ sna...
Can you write a function in Python 3 where it converts a string from snake_case to CamelCase.
You are a Python code architect, reviewing and designing scalable and efficient code
parse_server - Convert a server string to a tuple suitable for passing to connect for the connection.
Here you have a function in Python 3, explain what it does def parse_server(server, default_port): server = server.rsplit(':', 1) host = server[0] if host.startswith('[') and host.endswith(']'): host = host[1:-1] if len(server) == 1: return (host, default_port) port = server[1] if not port: port = default_p...
As a python code expert, you are capable of creating scripts from specifications.
parse_timespan - Convert a string timespan definition to seconds.
Given the following Python 3 function, write the documentation def parse_timespan(timedef): if isinstance(timedef, int): return timedef converter_order = ('w', 'd', 'h', 'm', 's') converters = { 'w': 604800, 'd': 86400, 'h': 3600, 'm': 60, 's': 1 } timedef = timedef.lower() if timedef.isdigit(): ret...
As a python code expert, you are capable of creating scripts from specifications.
def parse_to_slug(words, maxlen=24): """ Parse a string into a slug format suitable for use in URLs and other character restricted applications. Only utf-8 strings are supported at this time. :param str words: The words to parse. :param int maxlen: The maximum length of the slug. :return: The parsed words as a ...
Create a Python 3 function for parsing a string into a slug format suitable for use in URLs and other characters restricted applications.
You are a Python code architect, reviewing and designing scalable and efficient code
def random_string_alphanumeric(size): """ Generate a random string of *size* length consisting of mixed case letters and numbers. This function is not meant for cryptographic purposes. :param int size: The length of the string to return. :return: A string consisting of random characters. :rtype: str """ # requ...
Implement a function in Python 3 to generate a random string of *size* length consisting of mixed case letters and numbers. This function is not meant for cryptographic purposes. :param int size: The length of the string to return. :return: A string consisting of random characters. :rtype: str
As a Python code translator, you convert algorithms and pseudocode into Python.
def random_string_lower_numeric(size): """ Generate a random string of *size* length consisting of lowercase letters and numbers. This function is not meant for cryptographic purposes. :param int size: The length of the string to return. :return: A string consisting of random characters. :rtype: str """ # requ...
Create a Python 3 function to generate a random string of *size* length consisting of lowercase letters and numbers. This function is not meant for cryptographic purposes. :param int size: The length of the string to return. :return: A string consisting of random characters. :rtype: str
As a python code expert, you are capable of creating scripts from specifications.
def selection_collision(selections, poolsize): """ Calculate the probability that two random values selected from an arbitrary sized pool of unique values will be equal. This is commonly known as the "Birthday Problem". :param int selections: The number of random selections. :param int poolsize: The number of un...
Can you implement a function in Python 3 that calculates the probability that two random values selected from an arbitrary random value pool of unique values will be equal. This is commonly known as the Birthday Problem.
You are a Python code generator, capable of creating scripts from specifications.
def unique(seq, key=None): """ Create a unique list or tuple from a provided list or tuple and preserve the order. :param seq: The list or tuple to preserve unique items from. :type seq: list, tuple :param key: If key is provided it will be called during the comparison process. :type key: function, None """ ...
Can you implement a function in Python 3 that creates a list or tuple from a provided list or tuple and preserve the order of the unique items in the list or tuple.
As a python code expert, you are capable of creating scripts from specifications.
Make a randomly selected choice from the provided choices.
Explain what the following Python 3 code does def weighted_choice(choices, weight): # requirements = random weights = [] # get weight values for each of the choices for choice in choices: choice_weight = weight(choice) if not (isinstance(choice_weight, int) and choice_weight > 0): raise TypeError('weight res...
As a python code expert, you are capable of creating scripts from specifications.
def xfrange(start, stop=None, step=1): """ Iterate through an arithmetic progression. :param start: Starting number. :type start: float, int, long :param stop: Stopping number. :type stop: float, int, long :param step: Stepping size. :type step: float, int, long """ if stop is None: stop = start start = ...
Write a Python 3 script to iterate through an arithmetic progression.
You are a Python code architect, reviewing and designing scalable and efficient code
def cache_clean(self): """ Remove expired items from the cache. """ now = time.time() keys_for_removal = collections.deque() for key, (_, expiration) in self.__cache.items(): if expiration < now: keys_for_removal.append(key) for key in keys_for_removal: del self.__cache[key]
Write a Python 3 function for removing expired items from the cache.
As a Python code composer, you craft elegant and concise scripts.
Set an option to an arbitrary value.
Can you tell what is the following Python 3 function doing def set(self, option, value): self.config_parser.set(self.section_name, option, value)
You are a Python code generator, capable of creating scripts from specifications.
def reformat_exception(cls, message, err, *format_args, **format_kwds): """ Reformats an exception by adding a message to it and reporting the original exception name and message """ final_message = message.format(*format_args, **format_kwds) final_message = "{} -- {}: {}...
Can you write a function in Python 3 where it reformats an exception by adding a message to it and reporting the original exception name and the exception message.
You are a Python code analyst, evaluating scripts for potential improvements.
def handle_errors( cls, message, *format_args, re_raise=True, exception_class=Exception, do_finally=None, do_except=None, do_else=None, **format_kwds ): """ provides a context manager that will intercept exceptions and repackage them as Buzz in...
Create a Python 3 function for handling errors in the exception and re - packaged exceptions.
As a Python code translator, you convert algorithms and pseudocode into Python.
Raise an exception if expr is False
Can you tell what is the following Python 3 function doing def require_condition(cls, expr, message, *format_args, **format_kwds): if not expr: raise cls(message, *format_args, **format_kwds)
You are a Python code generator, capable of creating scripts from specifications.
Activates a user by supplying a valid activation key.
Make a summary of the following Python 3 code def activate_user(self, username, activation_key): if SHA1_RE.search(activation_key): try: user = self.get(activation_key=activation_key) except self.model.DoesNotExist: return False if not user.act...
As a Python code translator, you convert algorithms and pseudocode into Python.
def delete_expired_users(self): """ Checks for expired users and delete's the ``User`` associated with it. Skips if the user ``is_staff``. :return: A list containing the deleted users. """ deleted_users = [] for user in self.filter(is_staff=False, is_active=Fals...
How would you code a function in Python 3 to check for expired users and delete s the User associated with it. Skips the user is_staff
As a Python code composer, you craft elegant and concise scripts.
def confirm_email(self, username, confirmation_key): """ Confirm an email address by checking a ``confirmation_key``. A valid ``confirmation_key`` will set the newly wanted email address as the current email address. Returns the user after success or ``False`` when the confirmat...
Can you create a Python 3 function that confirms an email address by checking a confirmation key.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns all the visible profiles for this user.
Can you generate the documentation for the following Python 3 function def get_visible_profiles(self, user=None): profiles = self.select_related().all() filter_kwargs = {'is_active': True} profiles = profiles.filter(**filter_kwargs) if user and isinstance(user, AnonymousUser): ...
You are a Python code analyst, evaluating scripts for potential improvements.
def visit_html(self, node): """ Generate html elements and schematic json """ parentClsNode = node.parent.parent assert parentClsNode.attributes['objtype'] == 'class' assert parentClsNode.attributes['domain'] == 'py' sign = node.parent.parent.children[0] a...
Write a Python 3 script for generating html elements and schematic json elements and schematic json elements
As a Python code analyst, you investigate and solve complex coding mysteries
Run the main script.
How would you explain what the following Python 3 function does def run(self): has_npm = npm_installation_check() if has_npm: run_npm_install() else: print("Warning: npm not installed using prebuilded js files!", file=sys.stderr) """ Down...
As a python code expert, you are capable of creating scripts from specifications.
def density(self): """Stellar density in CGS units """ r = self.radius * _Rsun m = self.mass * _Msun return 0.75 * m / (np.pi * r * r * r)
Write a Python 3 function for returning the stellar density in CGS units
You are a Python code architect, reviewing and designing scalable and efficient code
def duration(self): """ The approximate duration of the transit :math:`T_\mathrm{tot}` from Equation (14) in Winn (2010). """ self._check_ps() rstar = self.system.central.radius k = self.r/rstar dur = self.period / np.pi arg = rstar/self.a * np.s...
Can you write a function in Python 3 where it returns the approximate duration of the transit : math : T__0 in the Windows 2000.
You are a Python code generator, capable of creating scripts from specifications.
Adds a body to the system.
Can you generate the documentation for the following Python 3 function def add_body(self, body): body.system = self self.bodies.append(body) self.unfrozen = np.concatenate(( self.unfrozen[:-2], np.zeros(7, dtype=bool), self.unfrozen[-2:] ))
You are a Python code analyst, evaluating scripts for potential improvements.
Return the light curve evaluated at a list of times using the current object s model.
Given the following Python 3 function, write the documentation def light_curve(self, t, texp=0.0, tol=1e-8, maxdepth=4, use_batman=False): t = np.atleast_1d(t) if len(self.bodies) == 0: return self.central.flux + np.zeros_like(t) return CythonSolver().kepler_light_curve(len(self.bod...
You are a Python code generator, capable of creating scripts from specifications.
def light_curve_gradient(self, t, texp=0.0, tol=1e-8, maxdepth=4): """ Get the light curve evaluated at a list of times using the current model. :param t: The times where the light curve should be evaluated (in days). :param tol: The stopping criterion f...
Can you implement a function in Python 3 that computes the gradient of the light curve at a list of times using the current object.
You are a Python code analyst, evaluating scripts for potential improvements.
Tag the current repository and commits changes to news files
Here you have a function in Python 3, explain what it does def main(): # see: # https://packaging.python.org/tutorials/distributing-packages/#uploading-your-project-to-pypi twine_repo = os.getenv('TWINE_REPOSITORY_URL') or os.getenv('TWINE_REPOSITORY') print('tagging and releasing to %s as %s' % ( ...
You are a Python code analyst, evaluating scripts for potential improvements.
Provide the context to use.
Can you tell what is the following Python 3 function doing def get_context(): pid = os.getpid() if pid not in context: context[pid] = zmq.Context() logger.debug('renewed context for PID %d', pid) return context[pid]
As a Python code translator, you convert algorithms and pseudocode into Python.
def strp_isoformat(strg): """Decode an ISO formatted string to a datetime object. Allow a time-string without microseconds. We handle input like: 2011-11-14T12:51:25.123456 """ if isinstance(strg, datetime): return strg if len(strg) < 19 or len(strg) > 26: if len(strg) > 30: ...
Can you write a function in Python 3 where it decodes an ISO formatted string to a datetime object.
You are a Python code generator, capable of creating scripts from specifications.
Delete an analysis log from the database.
Can you generate the documentation for the following Python 3 function def delete(context, force, yes, analysis_id): analysis_obj = context.obj['store'].analysis(analysis_id) if analysis_obj is None: print(click.style('analysis log not found', fg='red')) context.abort() print(click.style(f"...
As a Python code analyst, you investigate and solve complex coding mysteries
Adds data in the list of dictionaries into the database table.
How would you explain what the following Python 3 function does def add_data_to_database_table( self, dictList, createStatement=False): """*Import data in the list of dictionaries in the requested database table* Also adds HTMIDs and updates the sherlock-catalogue da...
You are a Python code analyst, evaluating scripts for potential improvements.
def _add_htmids_to_database_table( self): """*Add HTMIDs to database table once all the data has been imported (HTM Levels 10,13,16)* **Usage:** .. code-block:: python self._add_htmids_to_database_table() """ self.log.debug('starting the ``add_...
How would you code a function in Python 3 to add HTMIDs to the database table if all the data has been imported.
As a python code expert, you are capable of creating scripts from specifications.
Update the sherlock catalogues database helper table with the time - stamp of when this catlogue was last updated
Here you have a function in Python 3, explain what it does def _update_database_helper_table( self): """*Update the sherlock catalogues database helper table with the time-stamp of when this catlogue was last updated* **Usage:** .. code-block:: python self._up...
You are a Python code architect, reviewing and designing scalable and efficient code
def resolve_links(self): """Attempt to resolve all internal links (locally). In case the linked resources are found either as members of the array or within the `includes` element, those will be replaced and reference the actual resources. No network calls will be performed. ...
Implement a Python 3 function for attempting to resolve all internal links in the resources.
You are a Python code architect, reviewing and designing scalable and efficient code
def authenticate(self, request, identification, password=None, check_password=True): """ Authenticates a user through the combination email/username with password. :param identification: A string containing the username or email of the user that is ...
Write a Python 3 script to authenticate a user through the combination email and username with the given password.
You are a Python code architect, reviewing and designing scalable and efficient code
def find_analysis(self, family, started_at, status): """Find a single analysis.""" query = self.Analysis.query.filter_by( family=family, started_at=started_at, status=status, ) return query.first()
Write a Python 3 function for finding a single analysis.
You are a Python code analyst, evaluating scripts for potential improvements.
Fetch analyses form the database.
How would you explain what the following Python 3 function does def analyses(self, *, family: str=None, query: str=None, status: str=None, deleted: bool=None, temp: bool=False, before: dt.datetime=None, is_visible: bool=None): """Fetch analyses form the database.""" analysis_query = sel...
As a Python code composer, you craft elegant and concise scripts.
Get a single analysis.
Can you generate the documentation for the following Python 3 function def analysis(self, analysis_id: int) -> models.Analysis: return self.Analysis.query.get(analysis_id)
As a Python code composer, you craft elegant and concise scripts.
def track_update(self): """Update the lastest updated date in the database.""" metadata = self.info() metadata.updated_at = dt.datetime.now() self.commit()
Create a Python 3 function to update the last updated date in the database.
As a Python code analyst, you investigate and solve complex coding mysteries
Check if an analysis is currently running for a family.
Make a summary of the following Python 3 code def is_running(self, family: str) -> bool: latest_analysis = self.analyses(family=family).first() return latest_analysis and latest_analysis.status in TEMP_STATUSES
As a Python code composer, you craft elegant and concise scripts.
Add a pending entry for an analysis.
Make a summary of the following Python 3 code def add_pending(self, family: str, email: str=None) -> models.Analysis: started_at = dt.datetime.now() new_log = self.Analysis(family=family, status='pending', started_at=started_at) new_log.user = self.user(email) if email else None self.add...
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_user(self, name: str, email: str) -> models.User: """Add a new user to the database.""" new_user = self.User(name=name, email=email) self.add_commit(new_user) return new_user
Write a Python 3 function for adding a new user to the database.
As a Python code translator, you convert algorithms and pseudocode into Python.
def user(self, email: str) -> models.User: """Fetch a user from the database.""" return self.User.query.filter_by(email=email).first()
Create a Python 3 function to fetch a user from the database.
As a python code expert, you are capable of creating scripts from specifications.
Aggregate the number of failed jobs per category.
Can you generate a brief explanation for the following Python 3 code def aggregate_failed(self) -> List: categories = self.session.query( self.Job.name.label('name'), sqa.func.count(self.Job.id).label('count') ).filter(self.Job.status != 'cancelled').group_by(self.Job.name).all()...
As a Python code translator, you convert algorithms and pseudocode into Python.
def ingest(self): """*Perform conesearches of the online NED database and import the results into a the sherlock-database* The code: 1. uses the list of transient coordinates and queries NED for the results within the given search radius 2. Creates the `tcs_cat_ned_stream` tabl...
Write a Python 3 function that can ingest the NED object with the NED data from the online NED database and store the results in the sherlock - database table.
You are a Python code generator, capable of creating scripts from specifications.
Create a list of dictionaries containing all the object ids in the ned stream
Given the following Python 3 function, write the documentation def _create_dictionary_of_ned( self): """*Create a list of dictionaries containing all the object ids (NED names) in the ned stream* **Return:** - ``dictList`` - a list of dictionaries containing all the object ids (...
As a Python code analyst, you investigate and solve complex coding mysteries
def _update_ned_query_history( self): """*Update the database helper table to give details of the ned cone searches performed* *Usage:* .. code-block:: python stream._update_ned_query_history() """ self.log.debug('starting the ``_update_ned_quer...
How would you implement a function in Python 3 that updates the database helper table to give details of the ned cone searches performed
As a Python code analyst, you investigate and solve complex coding mysteries