output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Receive a message from all the subscribers.
Can you generate the documentation for the following Python 3 function def recv(self, timeout=None): if timeout: timeout *= 1000. for sub in list(self.subscribers) + self._hooks: self.poller.register(sub, POLLIN) self._loop = True try: while self._loo...
You are a Python code generator, capable of creating scripts from specifications.
def close(self): """Close the subscriber: stop it and close the local subscribers. """ self.stop() for sub in list(self.subscribers) + self._hooks: try: sub.setsockopt(LINGER, 1) sub.close() except ZMQError: pass
Can you create a Python 3 function that closes the subscriber and close the local subscribers.
As a Python code analyst, you investigate and solve complex coding mysteries
def _magickfy_topics(topics): """Add the magick to the topics if missing. """ # If topic does not start with messages._MAGICK (pytroll:/), it will be # prepended. if topics is None: return None if isinstance(topics, six.string_types): topics = [top...
Write a Python 3 script for adding the magick to the topics if missing.
As a Python code composer, you craft elegant and concise scripts.
handle the message *msg*.
Explain what the following Python 3 code does def handle_msg(self, msg): addr_ = msg.data["URI"] status = msg.data.get('status', True) if status: service = msg.data.get('service') for service in self.services: if not service or service in service: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def classify(self): """ *classify the transients selected from the transient selection query in the settings file or passed in via the CL or other code* **Return:** - ``crossmatches`` -- list of dictionaries of crossmatched associated sources - ``classifications`` -- the...
Write a Python 3 script to classify the transients in the database
As a Python code composer, you craft elegant and concise scripts.
use the transient query to generate a list of transients to corssmatch and classify
Given the following Python 3 function, write the documentation def _get_transient_metadata_from_database_list( self): """use the transient query in the settings file to generate a list of transients to corssmatch and classify **Return:** - ``transientsMetadataList`` .....
You are a Python code analyst, evaluating scripts for potential improvements.
def _update_ned_stream( self, transientsMetadataList ): """ update the NED stream within the catalogues database at the locations of the transients **Key Arguments:** - ``transientsMetadataList`` -- the list of transient metadata lifted from the database. .. tod...
Implement a Python 3 function for updating the NED stream for the given transient metadata
As a Python code translator, you convert algorithms and pseudocode into Python.
remove previous NED queries for the given transient locations
Make a summary of the following Python 3 code def _remove_previous_ned_queries( self, coordinateList): """iterate through the transient locations to see if we have recent local NED coverage of that area already **Key Arguments:** - ``coordinateList`` -- set of coordi...
As a Python code analyst, you investigate and solve complex coding mysteries
def _crossmatch_transients_against_catalogues( self, transientsMetadataListIndex, colMaps): """run the transients through the crossmatch algorithm in the settings file **Key Arguments:** - ``transientsMetadataListIndex`` -- the list of transient metadata...
Create a Python 3 function to run the transients through the crossmatch algorithm in the settings file and return the list of dictionaries of the associated sources that are crossmatched from the database
As a python code expert, you are capable of creating scripts from specifications.
update the transient database with the given crossmatches classifications transientsMetadataList and colMaps
Here you have a function in Python 3, explain what it does def _update_transient_database( self, crossmatches, classifications, transientsMetadataList, colMaps): """ update transient database with classifications and crossmatch results **Key A...
You are a Python code generator, capable of creating scripts from specifications.
rank the classifications returned from the catalogue crossmatcher
Given the following Python 3 function, write the documentation def _rank_classifications( self, crossmatchArray, colMaps): """*rank the classifications returned from the catalogue crossmatcher, annotate the results with a classification rank-number (most likely = 1) and a ran...
You are a Python code architect, reviewing and designing scalable and efficient code
Prints the classification and crossmatch results for a single transient object to stdout.
Given the following Python 3 function, write the documentation def _print_results_to_stdout( self, classifications, crossmatches): """*print the classification and crossmatch results for a single transient object to stdout* **Key Arguments:** - ``crossmat...
You are a Python code generator, capable of creating scripts from specifications.
consolidate the coordinate list against itself with the parameters of the NED search queries to minimise duplicated NED queries
How would you explain what the following Python 3 function does def _consolidate_coordinateList( self, coordinateList): """*match the coordinate list against itself with the parameters of the NED search queries to minimise duplicated NED queries* **Key Arguments:** -...
As a Python code composer, you craft elegant and concise scripts.
def classification_annotations( self): """*add a detialed classification annotation to each classification in the sherlock_classifications table* **Key Arguments:** # - **Return:** - None **Usage:** .. todo:: - add usag...
Implement a Python 3 function for adding a detialed classification annotation to each crossmatch in the sherlock_classifications table
As a Python code analyst, you investigate and solve complex coding mysteries
def update_classification_annotations_and_summaries( self, updatePeakMagnitudes=True): """*update classification annotations and summaries* **Key Arguments:** - ``updatePeakMagnitudes`` -- update the peak magnitudes in the annotations to give absolute magnitudes. Def...
Implement a Python 3 function for updating the classification annotations and summaries of the given object
You are a Python code architect, reviewing and designing scalable and efficient code
*update peak magnitudes* **Key Arguments:** # - **Return:** - None **Usage:** .. todo:: - add usage info - create a sublime snippet for usage - write a command-line tool for this method - upd...
Can you tell what is the following Python 3 function doing def update_peak_magnitudes( self): """*update peak magnitudes* **Key Arguments:** # - **Return:** - None **Usage:** .. todo:: - add usage info -...
You are a Python code analyst, evaluating scripts for potential improvements.
create the sherlock helper tables if they don t yet exist
Can you generate the documentation for the following Python 3 function def _create_tables_if_not_exist( self): """*create the sherlock helper tables if they don't yet exist* **Key Arguments:** # - **Return:** - None **Usage:** .. todo::...
As a python code expert, you are capable of creating scripts from specifications.
Delete an analysis log from the database.
Here you have a function in Python 3, explain what it does def check(context: click.Context, family: str): analysis_obj = context.obj['store'].analyses(family=family).first() if analysis_obj is None: LOG.error('no analysis found') context.abort() config_path = Path(analysis_obj.config_path)...
You are a Python code analyst, evaluating scripts for potential improvements.
Name a FASTQ file following MIP conventions.
Explain what the following Python 3 code does def name_file(lane: int, flowcell: str, sample: str, read: int, undetermined: bool=False, date: dt.datetime=None, index: str=None) -> str: """Name a FASTQ file following MIP conventions.""" flowcell = f"{flowcell}-undetermined" if undetermi...
You are a Python code analyst, evaluating scripts for potential improvements.
Link FASTQ files for a sample.
How would you explain what the following Python 3 function does def link(self, family: str, sample: str, analysis_type: str, files: List[str]): root_dir = Path(self.families_dir) / family / analysis_type / sample / 'fastq' root_dir.mkdir(parents=True, exist_ok=True) for fastq_data in files: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def getpackagepath(): """ *Get the root path for this python package - used in unit testing code* """ moduleDirectory = os.path.dirname(__file__) packagePath = os.path.dirname(__file__) + "/../" return packagePath
Implement a Python 3 function for getting the path to the python package
As a Python code translator, you convert algorithms and pseudocode into Python.
Open a UDP socket bind it to a port and select a multicast group.
Can you tell what is the following Python 3 function doing def mcast_receiver(port, mcgroup=MC_GROUP): if _is_broadcast_group(mcgroup): group = None else: group = mcgroup # Create a socket sock = socket(AF_INET, SOCK_DGRAM) # Allow multiple copies of this program on one machine ...
As a python code expert, you are capable of creating scripts from specifications.
def _delete_temp_logs(self, family_name: str): """Delete temporary logs for the current family.""" for temp_log in self.store.analyses(family=family_name, temp=True): log.debug(f"delete temporary log: {temp_log.id} - {temp_log.status}") temp_log.delete()
Write a Python 3 function for deleting temporary logs for the current family.
As a Python code composer, you craft elegant and concise scripts.
Parse information about a run.
Can you generate the documentation for the following Python 3 function def parse(cls, config_data: dict, sampleinfo_data: dict, sacct_jobs: List[dict], jobs: int) -> dict: """Parse information about a run.""" analysis_types = [sample['type'] for sample in config_data['samples']] ru...
You are a Python code architect, reviewing and designing scalable and efficient code
def _parse_sacct(sacct_jobs: List[dict], jobs_count: int=None): """Parse out info from Sacct log.""" failed_jobs = sacct_api.filter_jobs(sacct_jobs, failed=True) completed_jobs = [job for job in sacct_jobs if job['is_completed']] last_job_end = completed_jobs[-1]['end'] if len(completed_...
Write a Python 3 script for parsing out info from Sacct log.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _get_analysis_type(analysis_types: List[str]) -> str: """Determine the overall analysis type.""" types_set = set(analysis_types) return types_set.pop() if len(types_set) == 1 else 'wgs'
Implement a Python 3 function for determining the overall analysis type.
As a Python code composer, you craft elegant and concise scripts.
Build a new Analysis object.
Can you generate a brief explanation for the following Python 3 code def build(self, run_data: dict) -> models.Analysis: existing_run = self.store.find_analysis(family=run_data['family'], started_at=run_data['started_at'], ...
You are a Python code analyst, evaluating scripts for potential improvements.
get the default value
Here you have a function in Python 3, explain what it does def get_default_value(self): default = self.default_value if isinstance(default, collections.Callable): default = default() return default
As a Python code analyst, you investigate and solve complex coding mysteries
Initialize the Execution Context for a Compiled construct.
Can you generate a brief explanation for the following Python 3 code def _init_compiled(cls, dialect, connection, dbapi_connection, compiled, parameters): """Initialize execution context for a Compiled construct.""" self = cls.__new__(cls) self.root_connection = connectio...
As a Python code composer, you craft elegant and concise scripts.
Utility function to return a list of sentences.
Can you generate a brief explanation for the following Python 3 code def split_sentences(text): sentence_delimiters = re.compile(u'[.!?,;:\t\\\\"\\(\\)\\\'\u2019\u2013]|\\s\\-\\s') sentences = sentence_delimiters.split(text) return sentences
You are a Python code analyst, evaluating scripts for potential improvements.
Get the url patterns that route each action to a view.
Given the following Python 3 function, write the documentation def _get_action_urls(self): actions = {} model_name = self.model._meta.model_name # e.g.: polls_poll base_url_name = '%s_%s' % (self.model._meta.app_label, model_name) # e.g.: polls_poll_actions model_actions...
You are a Python code architect, reviewing and designing scalable and efficient code
Represents the tool as a dict with extra meta.
How would you explain what the following Python 3 function does def _get_tool_dict(self, tool_name): tool = getattr(self, tool_name) standard_attrs, custom_attrs = self._get_button_attrs(tool) return dict( name=tool_name, label=getattr(tool, 'label', tool_name), ...
You are a Python code generator, capable of creating scripts from specifications.
def _get_button_attrs(self, tool): """ Get the HTML attributes associated with a tool. There are some standard attributes (class and title) that the template will always want. Any number of additional attributes can be specified and passed on. This is kinda awkward and due for a...
Write a Python 3 function for getting the HTML attributes associated with a tool.
You are a Python code analyst, evaluating scripts for potential improvements.
def question_mark(self, request, obj): """Add a question mark.""" obj.question = obj.question + '?' obj.save()
How would you code a function in Python 3 to add a question mark.
You are a Python code analyst, evaluating scripts for potential improvements.
Builds an html link.
Can you generate the documentation for the following Python 3 function def build_link(href, text, cls=None, icon_class=None, **attrs): return build_html_element(tag='a', text=text, href=href, cls=cls, ...
You are a Python code generator, capable of creating scripts from specifications.
def build_html_element(tag, text=None, icon_class=None, cls=None, **kwargs): """Builds an html element. :param tag: the html tag to build ('a', 'div', 'img', etc) :param icon_class: the class to apply to an icon element. This only applies to elements that allow a closing tag. :param cls: the c...
How would you implement a function in Python 3 that builds an html element.
As a Python code analyst, you investigate and solve complex coding mysteries
Serialize a migration session state to yaml using nicer formatting
Can you tell what is the following Python 3 function doing def dump_migration_session_state(raw): class BlockStyle(str): pass class SessionDumper(yaml.SafeDumper): pass def str_block_formatter(dumper, data): return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|') SessionDumper....
As a Python code analyst, you investigate and solve complex coding mysteries
Adds migrations to be applied.
How would you explain what the following Python 3 function does def add_migrations(self, migrations): if self.__closed: raise MigrationSessionError("Can't change applied session") self._to_apply.extend(migrations)
You are a Python code analyst, evaluating scripts for potential improvements.
Return a list of unapplied migrations in the form [ migration1 migration2... ]
Can you tell what is the following Python 3 function doing def _get_unapplied_migrations(self, loader): unapplied = [] graph = loader.graph plan = [] seen = set() # Generate the plan, in the order that migrations have been/should be applied. for target in graph.leaf_node...
As a Python code analyst, you investigate and solve complex coding mysteries
Extract the most recent migrations from the relevant apps and return a dictionary of app names to migration state.
Can you generate the documentation for the following Python 3 function def _get_current_migration_state(self, loader, apps): # Only care about applied migrations for the passed-in apps. apps = set(apps) relevant_applied = [migration for migration in loader.applied_migrations if migration[0] in a...
You are a Python code analyst, evaluating scripts for potential improvements.
def list_migrations(self): """ Returns a tuple of unapplied, current "Unapplied" is a list of unapplied migrations. "Current" is a list of the current migration states for apps with unapplied migrations. Both are tuples of the form (app, migration_name). """ con...
How would you implement a function in Python 3 that returns a tuple of unapplied current
As a Python code translator, you convert algorithms and pseudocode into Python.
Parse the output of manage. py migrate and return a list of tuples.
Given the following Python 3 function, write the documentation def _parse_migrate_output(self, output): failed = None succeeded = [] # Mark migrations: # - before exception migration as success # - exception migration as failed for line in output.split('\n'): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Applies a migration to the state.
Given the following Python 3 function, write the documentation def __apply(self, migration=None, run_all=False): out = StringIO() trace = None migrate_kwargs = { 'interactive': False, 'stdout': out, 'database': self._database_name, } if migrat...
You are a Python code architect, reviewing and designing scalable and efficient code
def apply(self): """ Applies all migrations that have been added. Note that some migrations depend on others, so you might end up running more than one. """ if self.__closed: raise MigrationSessionError("Can't apply applied session") try: w...
Write a Python 3 function for applying all migrations that have been added to the session.
As a Python code analyst, you investigate and solve complex coding mysteries
Applies all Django model migrations at once recording the result.
Make a summary of the following Python 3 code def apply_all(self): if self.__closed: raise MigrationSessionError("Can't apply applied session") if self._to_apply: raise MigrationSessionError("Can't apply_all with migrations added to session") try: self.__appl...
As a Python code composer, you craft elegant and concise scripts.
def send_email_from_template(to_email, from_email, subject, markdown_template=None, text_template=None, html_template=None, fail_silently=False, context=None, **kwargs): """Send an email from a templa...
Write a Python 3 script for sending an email from a template.
As a Python code analyst, you investigate and solve complex coding mysteries
def send_emails_from_template(to_emails, from_email, subject, markdown_template=None, text_template=None, html_template=None, fail_silently=False, context=None, attachments=None, **kwargs): """Send many emails from single temp...
Can you write a function in Python 3 where it sends many emails from a single template.
You are a Python code analyst, evaluating scripts for potential improvements.
def all_models(self, alphabet: _Alphabet) -> Set[PLInterpretation]: """Find all the possible interpretations given a set of symbols""" all_possible_interpretations = alphabet.powerset().symbols all_models = set() for i in all_possible_interpretations: # compute current Inter...
Write a Python 3 script for finding all the possible interpretations given a set of symbols
As a Python code translator, you convert algorithms and pseudocode into Python.
Find models of minimal size.
Make a summary of the following Python 3 code def minimal_models(self, alphabet: _Alphabet) -> Set[PLInterpretation]: models = self.all_models(alphabet) minimal_models = set() for m in models: min_m = m for m1 in models: if min_m.true_propositions.issuper...
As a Python code analyst, you investigate and solve complex coding mysteries
Make sure token is added.
Can you generate the documentation for the following Python 3 function def save(self, *args, **kwargs): self.save_prep(instance_or_instances=self) return super(AbstractTokenModel, self).save(*args, **kwargs)
As a Python code analyst, you investigate and solve complex coding mysteries
Preprocess the object before the object is saved.
Given the following Python 3 function, write the documentation def save_prep(cls, instance_or_instances): instances = make_obj_list(instance_or_instances) tokens = set(cls.objects.get_available_tokens( count=len(instances), token_length=cls.token_length )) for i...
You are a Python code generator, capable of creating scripts from specifications.
recursively find commutative binary operator among child formulas and pop up them at the same level
Given the following Python 3 function, write the documentation def _popup(self): res = () for child in self.formulas: if type(child) == type(self): superchilds = child.formulas res += superchilds else: res += (child, ) retur...
As a python code expert, you are capable of creating scripts from specifications.
def get_content_object_url(self): """Gets the absolute url for the content object.""" if (self.content_object and hasattr(self.content_object, 'get_absolute_url')): return self.content_object.get_absolute_url() return None
How would you code a function in Python 3 to get the absolute url for the content object.
As a Python code analyst, you investigate and solve complex coding mysteries
t_ATOM is a bit of a hack to handle reserved words
Can you generate a brief explanation for the following Python 3 code def t_ATOM(self, t): r'[a-zA-Z_][a-zA-Z_0-9]*' t.type = LDLfLexer.reserved.get(t.value, 'ATOM') # Check for reserved words return t
As a Python code composer, you craft elegant and concise scripts.
def get_redirect_url(current_url, config, https=None): """ priorities are (primary domain and aliases are treated the same): exact redirect match > exact alias match > pattern redirect match > pattern alias match :param current_url: the url that is being called :param config: redirect configurat...
Can you create a Python 3 function that returns the url that should be used to redirect to the current url.
You are a Python code architect, reviewing and designing scalable and efficient code
Invoke the callback on the given context.
Explain what the following Python 3 code does def invoke(self, ctx): if self.callback is not None: loop = asyncio.get_event_loop() return loop.run_until_complete(self.async_invoke(ctx))
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the help option object.
How would you explain what the following Python 3 function does def get_help_option(self, ctx): help_options = self.get_help_option_names(ctx) if not help_options or not self.add_help_option: return def show_help(ctx, param, value): import abot.bot if value a...
As a Python code composer, you craft elegant and concise scripts.
Gets the class for the widget.
Can you tell what is the following Python 3 function doing def get_widget_css_class(self, attrs): size_class = 'size-{0}'.format(self.num_inputs) if 'class' in attrs: attrs['class'] += ' {0}'.format(size_class) else: attrs['class'] = size_class
As a Python code translator, you convert algorithms and pseudocode into Python.
formula : ATOM | TRUE | FALSE
Here you have a function in Python 3, explain what it does def p_formula_atom(self, p): if p[1]==Symbols.TRUE.value: p[0] = PLTrue() elif p[1]==Symbols.FALSE.value: p[0] = PLFalse() else: p[0] = PLAtomic(Symbol(p[1]))
You are a Python code generator, capable of creating scripts from specifications.
Gets a single object based on kwargs or None if one is not found.
How would you explain what the following Python 3 function does def get_or_none(self, prefetch_related=None, select_related=False, **kwargs): """Gets a single object based on kwargs or None if one is not found. :param prefetch_related: list or tuple of fields to prefetch for an ...
You are a Python code analyst, evaluating scripts for potential improvements.
r Gets a single instance r raises a 404 is one isn t found.
Can you generate the documentation for the following Python 3 function def get_by_id_or_404(self, id, **kwargs): obj = self.get_by_id(id=id, **kwargs) if obj: return obj raise Http404
As a python code expert, you are capable of creating scripts from specifications.
def bulk_create(self, objs, *args, **kwargs): """Insert many object at once.""" if hasattr(self.model, 'save_prep'): # Method from AbstractBaseModel. If the model class doesn't # subclass AbstractBaseModel, then don't call this. self.model.save_prep(instance_or_instan...
Write a Python 3 script to insert many object at once.
As a Python code composer, you craft elegant and concise scripts.
def delete_by_ids(self, ids): """Delete objects by ids. :param ids: list of objects ids to delete. :return: True if objects were deleted. Otherwise, return False if no objects were found or the delete was not successful. """ try: self.filter(id__in=i...
Write a Python 3 function that can delete objects by ids.
You are a Python code architect, reviewing and designing scalable and efficient code
def is_slug_available(self, slug, **kwargs): """Checks to see if a slug is available. If the slug is already being used this method returns False. Otherwise, return True. """ try: self.get(slug=slug, **kwargs) return False except self.model.DoesNotExist: ...
How would you code a function in Python 3 to check to see if a slug is available.
As a Python code composer, you craft elegant and concise scripts.
Gets the next available slug.
Here you have a function in Python 3, explain what it does def get_next_slug(self, slug, **kwargs): original_slug = slug = slugify(slug) count = 0 while not self.is_slug_available(slug=slug, **kwargs): count += 1 slug = '{0}-{1}'.format(original_slug, count) ret...
You are a Python code generator, capable of creating scripts from specifications.
def get_next_token(self, length=15, **kwargs): """Gets the next available token. :param length: length of the token :param kwargs: additional filter criteria to check for when looking for a unique token. """ return self.get_available_tokens(count=1, ...
Write a Python 3 function for getting the next available token.
As a Python code translator, you convert algorithms and pseudocode into Python.
Gets a list of available tokens.
Make a summary of the following Python 3 code def get_available_tokens(self, count=10, token_length=15, **kwargs): # This is the number of extra tokens to try and retrieve so calls to # the db can be limited token_buffer = int(math.ceil(count * .05)) if token_buffer < 5: tok...
As a python code expert, you are capable of creating scripts from specifications.
Create a generic object.
Given the following Python 3 function, write the documentation def create_generic(self, content_object=None, **kwargs): if content_object: kwargs['content_type'] = ContentType.objects.get_for_model( content_object ) kwargs['object_id'] = content_object.id ...
As a Python code composer, you craft elegant and concise scripts.
def filter_generic(self, content_object=None, **kwargs): """Filter by a generic object. :param content_object: the content object to filter on. """ if content_object: kwargs['content_type'] = ContentType.objects.get_for_model( content_object ) ...
Can you write a function in Python 3 where it filters by a generic object.
You are a Python code generator, capable of creating scripts from specifications.
def get_or_create_generic(self, content_object=None, **kwargs): """Gets or creates a generic object. This is a wrapper for get_or_create(...) when you need to get or create a generic object. :param obj: the object to get or create :param kwargs: any other kwargs that the model accepts....
Write a Python 3 function for getting or creates a generic object.
As a Python code composer, you craft elegant and concise scripts.
def get_by_model(self, model): """Gets all object by a specific model.""" content_type = ContentType.objects.get_for_model(model) return self.filter(content_type=content_type)
Implement a Python 3 function for getting all object by a specific model.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the attribute of the object.
Here you have a function in Python 3, explain what it does def attr(obj, attr): if not obj or not hasattr(obj, attr): return '' return getattr(obj, attr, '')
As a Python code translator, you convert algorithms and pseudocode into Python.
def make_iterable(obj): """Make an object iterable. >>> make_iterable(obj='hello') ('hello',) >>> make_iterable(obj=None) () """ if not obj: return tuple() if isinstance(obj, (list, tuple, set)): return obj return (obj,)
Can you create a Python 3 function that makes an object iterable.
You are a Python code generator, capable of creating scripts from specifications.
Add the data to the form args so you can validate the form s data on a get request.
Here you have a function in Python 3, explain what it does def get_form_kwargs(self): kwargs = super(ApiFormView, self).get_form_kwargs() kwargs['data'] = kwargs.get('initial') return kwargs
You are a Python code analyst, evaluating scripts for potential improvements.
This will return the request with form errors as well as any additional context.
Can you generate the documentation for the following Python 3 function def form_invalid(self, form, context=None, **kwargs): if not context: context = {} context['errors'] = form.errors return super(ApiFormView, self).render_to_response(context=context, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Checks whether the value is a valid rgb or rgba color string.
Make a summary of the following Python 3 code def is_valid_rgb_color(value): if not value: return False regex = re.compile(RGB_COLOR_REGEX) return bool(regex.match(value))
As a Python code translator, you convert algorithms and pseudocode into Python.
def validate_password_strength(value): """Validates that a password is as least 7 characters long and has at least 1 digit and 1 letter. """ min_length = 7 if len(value) < min_length: raise ValidationError(_('Password must be at least {0} characters ' 'long.'...
How would you implement a function in Python 3 that validates that a password is at least 7 characters long and has at least 1 digit and 1 letter.
As a Python code translator, you convert algorithms and pseudocode into Python.
Class decorator for creating a class with a metaclass.
How would you explain what the following Python 3 function does def add_metaclass(metaclass): def wrapper(cls): orig_vars = cls.__dict__.copy() orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapp...
As a Python code translator, you convert algorithms and pseudocode into Python.
Validates that the input can be converted to a list of decimals.
How would you explain what the following Python 3 function does def clean(self, value): if not value: return None # if any value exists, then add "0" as a placeholder to the remaining # values. if isinstance(value, list) and any(value): for i, item in enumerate(v...
You are a Python code architect, reviewing and designing scalable and efficient code
Validates that the input can be converted to a list of decimals.
Given the following Python 3 function, write the documentation def to_python(self, value): if not value: return None if isinstance(value, list): for index, position_val in enumerate(value): val = super(MultipleDecimalField, self).to_python(position_val) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a random alphanumeric string of the given length.
Can you generate a brief explanation for the following Python 3 code def random_alphanum(length=10, lower_only=False): character_set = ALPHANUM_LOWER if lower_only else ALPHANUM sample_size = 5 chars = random.sample(character_set, sample_size) while len(chars) < length: chars += random.sample(c...
As a Python code translator, you convert algorithms and pseudocode into Python.
Generates a random alphanumeric key between low and high characters in length.
Can you generate the documentation for the following Python 3 function def generate_key(low=7, high=10, lower_only=False): return random_alphanum(length=randint(7, 10), lower_only=lower_only)
You are a Python code analyst, evaluating scripts for potential improvements.
def get_absolute_url_link(self, text=None, cls=None, icon_class=None, **attrs): """Gets the html link for the object.""" if text is None: text = self.get_link_text() return build_link(href=self.get_absolute_url(), text=text, ...
How would you code a function in Python 3 to get the html link for the object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Gets the html edit link for the object.
How would you explain what the following Python 3 function does def get_edit_url_link(self, text=None, cls=None, icon_class=None, **attrs): """Gets the html edit link for the object.""" if text is None: text = 'Edit' return build_link(href=self.get_edit_url...
You are a Python code analyst, evaluating scripts for potential improvements.
Gets the html delete link for the object.
Make a summary of the following Python 3 code def get_delete_url_link(self, text=None, cls=None, icon_class=None, **attrs): """Gets the html delete link for the object.""" if text is None: text = 'Delete' return build_link(href=self.get_delete_url(), ...
As a Python code analyst, you investigate and solve complex coding mysteries
def expire_by_email(self, email_address, **kwargs): """Expires tokens for an email address or email addresses. :param email_address: the string email address or emails addresses to expire tokens for. :param reason: the codified reason for the tokens. If explicitly set t...
Implement a function in Python 3 to expire all tokens for an email address or list of emails.
You are a Python code architect, reviewing and designing scalable and efficient code
def map_query_string(self): """Maps the GET query string params the the query_key_mapper dict and updates the request's GET QueryDict with the mapped keys. """ if (not self.query_key_mapper or self.request.method == 'POST'): # Nothing to map, don't do anything. ...
Create a Python 3 function to map the GET query string params to the mapped keys and updates the request s GET QueryDict with the mapped keys.
As a Python code composer, you craft elegant and concise scripts.
Bump the version number of a Python module in all repos.
Can you generate a brief explanation for the following Python 3 code def bump_repos_version(module_name, new_version, local_only): # Make the cloning directory and change directories into it. tmp_dir = tempfile.mkdtemp(dir=os.getcwd()) # Iterate through each repository. for owner, repo_name in REPOS_TO...
As a Python code analyst, you investigate and solve complex coding mysteries
async def call(self, method, **params): """ Call an Slack Web API method :param method: Slack Web API method to call :param params: {str: object} parameters to method :return: dict() """ url = self.SLACK_RPC_PREFIX + method data = FormData() data....
Write a Python 3 function that can call an Slack Web API method with parameters.
You are a Python code generator, capable of creating scripts from specifications.
Handle a message from the Slack RTM.
Here you have a function in Python 3, explain what it does def rtm_handler(self, ws_message): message = json.loads(ws_message.data) if 'reply_to' in message: reply_to = message['reply_to'] future = self.response_futures.pop(reply_to, None) if future is None: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_default_prefix(self, instance=None): """Gets the prefix for this form. :param instance: the form model instance. When calling this method directly this should almost always stay None so it looks for self.instance. """ if instance is None and hasattr(self...
How would you implement a function in Python 3 that gets the default prefix for this form.
As a Python code analyst, you investigate and solve complex coding mysteries
Checks if a user is authenticated and returns the user s unique ID.
Can you generate a brief explanation for the following Python 3 code def authenticate(self, username, password): # If username is an email address, then try to pull it up user = self.get_by_username_or_email(username) if not user: return None if user.check_password(password...
You are a Python code generator, capable of creating scripts from specifications.
def powerset(iterable) -> FrozenSet: "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" combs = _powerset(iterable) res = frozenset(frozenset(x) for x in combs) # res = map(frozenset, combs) return res
Create a Python 3 function to return a set of all the elements in iterable that are the powerset of the elements of iterable.
As a Python code translator, you convert algorithms and pseudocode into Python.
This method returns the edit url for the object
Explain what the following Python 3 code does def edit_url_link(obj, **kwargs): if hasattr(obj, 'get_edit_url_link'): return obj.get_edit_url_link(**kwargs) edit_url = obj.get_edit_url() return build_link(href=edit_url, **kwargs)
As a Python code translator, you convert algorithms and pseudocode into Python.
This method returns the delete url link for the object
Explain what the following Python 3 code does def delete_url_link(obj, **kwargs): if hasattr(obj, 'get_delete_url_link'): return obj.get_delete_url_link(**kwargs) delete_url = obj.get_delete_url() return build_link(href=delete_url, **kwargs)
As a Python code translator, you convert algorithms and pseudocode into Python.
Make the default formfield a CommaSeparatedListField.
Make a summary of the following Python 3 code def formfield(self, form_class=None, choices_form_class=None, **kwargs): defaults = { 'form_class': form_class or self.get_form_class() } defaults.update(kwargs) return super(ListField, self).formfield(**defaults)
You are a Python code architect, reviewing and designing scalable and efficient code
This follows the validate rules for the choices_form_class field used.
Given the following Python 3 function, write the documentation def validate(self, value, model_instance, **kwargs): self.get_choices_form_class().validate(value, model_instance, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
def to_python(self, value): """ Convert the input JSON value into python structures, raises django.core.exceptions.ValidationError if the data can't be converted. """ if isinstance(value, dict): return value if self.blank and not value: return Non...
Implement a Python 3 function for converting the input JSON value into python structures. Raises a ValidationError if the input JSON value can t be converted.
You are a Python code analyst, evaluating scripts for potential improvements.
Convert value to JSON string before save
Can you generate a brief explanation for the following Python 3 code def get_prep_value(self, value): try: return json.dumps(value, cls=DjangoJSONEncoder) except Exception as e: raise ValidationError(str(e))
As a Python code composer, you craft elegant and concise scripts.
Return the farthest origin of a generic class.
Here you have a function in Python 3, explain what it does def _gorg(a): assert isinstance(a, GenericMeta) while a.__origin__ is not None: a = a.__origin__ return a
As a Python code translator, you convert algorithms and pseudocode into Python.