output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Calculates the similarity between the current model of biclusters and the reference model of biclusters. | How would you explain what the following Python 3 function does
def bicluster_similarity(self, reference_model):
similarity_score = consensus_score(self.model.biclusters_, reference_model.biclusters_)
return similarity_score | As a Python code composer, you craft elegant and concise scripts. |
def load(self, path, genes_uuid, regs=['chr', 'left', 'right', 'strand'], meta=[], values=[], full_load=False):
"""
Loads the multi referenced mapped data from the file system
:param path: The path to the files
:param genes_uuid: The unique identifier metadata column name to sep... | Can you write a function in Python 3 where it
loads the multi - referenced mapped data from the file system. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates and returns the compact view where the index of the dataframe is a multi index of the selected metadata. | How would you explain what the following Python 3 function does
def compact_view(self, merged_data, selected_meta, reference_no):
meta_names = list(selected_meta)
meta_index = []
for x in meta_names:
meta_index.append(self.all_meta_data.ix[merged_data.index.get_level_values(referenc... | You are a Python code architect, reviewing and designing scalable and efficient code |
This method is used to remove the attributes that are more than a percentage of missing values. | Explain what the following Python 3 code does
def prune_by_missing_percent(df, percentage=0.4):
mask = (df.isnull().sum() / df.shape[0]).map(lambda x: True if x < percentage else False)
pruned_df = df[df.columns[mask.values]]
return pruned_df | As a Python code analyst, you investigate and solve complex coding mysteries |
def impute_using_statistics(df, method='min'):
"""
Imputes the missing values by the selected statistical property of each column
:param df: The input dataframe that contains missing values
:param method: The imputation method (min by default)
"zero": fill missing entries wi... | Can you create a Python 3 function that
imputes the missing values by the selected statistical property of each column | You are a Python code architect, reviewing and designing scalable and efficient code |
This function imputes the k nearest neighbour imputations which weights samples using the mean squared difference on features for which two rows both have observed data. | Can you tell what is the following Python 3 function doing
def impute_knn(df, k=3):
imputed_matrix = KNN(k=k).complete(df.values)
imputed_df = pd.DataFrame(imputed_matrix, df.index, df.columns)
return imputed_df | As a Python code translator, you convert algorithms and pseudocode into Python. |
def impute_svd(df, rank=10, convergence_threshold=0.00001, max_iters=200):
"""
Imputes the missing values by using SVD decomposition
Based on the following publication: 'Missing value estimation methods for DNA microarrays' by Troyanskaya et. al.
:param df:The input dataframe that conta... | Write a Python 3 function for
imputing the missing values by using SVD decomposition | As a Python code analyst, you investigate and solve complex coding mysteries |
def feature_selection(df, labels, n_features, method='chi2'):
"""
Reduces the number of features in the imput dataframe.
Ex: labels = gs.meta['biospecimen_sample__sample_type_id'].apply(int).apply(lambda x: 0 if x < 10 else 1)
chi2_fs(gs.data, labels, 50)
:param df: The inpu... | Create a Python 3 function for
selecting the desired number of features in the imput dataframe. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set_spark_conf(self, key=None, value=None, d=None):
""" Sets a spark property as a ('key', 'value') pair of using a dictionary
{'key': 'value', ...}
:param key: string
:param value: string
:param d: dictionary
:return: None
"""
if isinstance(d, dict):... | Write a Python 3 function for
setting a spark property as a key value pair of using a dictionary d. | As a python code expert, you are capable of creating scripts from specifications. |
def set_system_conf(self, key=None, value=None, d=None):
""" Sets a java system property as a ('key', 'value') pair of using a dictionary
{'key': 'value', ...}
:param key: string
:param value: string
:param d: dictionary
:return: None
"""
if isinstance(d,... | How would you code a function in Python 3 to
set a java system property as a key value pair of using a dictionary d. | You are a Python code analyst, evaluating scripts for potential improvements. |
Select the samples having the metadata attribute between the provided values as input
. | Given the following Python 3 function, write the documentation
def isin(self, values):
if not isinstance(values, list):
raise TypeError("Input should be a string. {} was provided".format(type(values)))
if not (self.name.startswith("(") and self.name.endswith(")")):
first = True
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_flatpages_i18n(parser, token):
"""
Retrieves all flatpage objects available for the current site and
visible to the specific user (or visible to all users if no user is
specified). Populates the template context with them in a variable
whose name is defined by the ``as`` clause.
An opti... | Implement a function in Python 3 to
return the flatpages available for the current site and all of the users in the current template context. | As a Python code analyst, you investigate and solve complex coding mysteries |
Double fork and set the pid. | Can you tell what is the following Python 3 function doing
def daemonize(self):
self._double_fork()
# Write pidfile.
self.pid = os.getpid()
LOG.info(
"Succesfully daemonized process {0}.".format(self.pid)
) | As a Python code analyst, you investigate and solve complex coding mysteries |
Do the UNIX double - fork magic. | How would you explain what the following Python 3 function does
def _double_fork(self):
try:
pid = os.fork()
if pid > 0:
# Exit first parent.
sys.exit(0)
return None
except OSError as err:
LOG.exception(
... | As a Python code composer, you craft elegant and concise scripts. |
def from_memory(cls, data, meta):
"""
Overloaded constructor to create the GenometricSpace object from memory data and meta variables.
The indexes of the data and meta dataframes should be the same.
:param data: The data model
:param meta: The metadata
:return: A Genome... | Write a Python 3 script for
overloading constructor to create the GenometricSpace object from memory data and meta variables. | As a Python code analyst, you investigate and solve complex coding mysteries |
def load(self, _path, regs=['chr', 'left', 'right', 'strand'], meta=[], values=[], full_load=False, file_extension="gdm"):
"""Parses and loads the data into instance attributes.
The indexes of the data and meta dataframes should be the same.
:param path: The path to the dataset on the filesyste... | Write a Python 3 script to
parse and loads the data into the instance attributes. | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets one axis of the 2D multi - indexed dataframe
index to the selected meta data. | Can you tell what is the following Python 3 function doing
def set_meta(self, selected_meta):
meta_names = list(selected_meta)
meta_names.append('sample')
meta_index = []
# To set the index for existing samples in the region dataframe.
# The index size of the region dataframe doe... | You are a Python code architect, reviewing and designing scalable and efficient code |
def to_matrix(self, values, selected_regions, default_value=0):
"""Creates a 2D multi-indexed matrix representation of the data.
This representation allows the data to be sent to the machine learning algorithms.
Args:
:param values: The value or values that are going to fill the... | Implement a function in Python 3 to
create a 2D multi-indexed matrix representation of the data. This representation allows the data to be sent to the machine learning algorithms. Args: :param values: The value or values that are going to fill the matrix. :param selected_regions: The index to one axis of the matrix. :p... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the values of the selected metadata values of the given set | Given the following Python 3 function, write the documentation
def get_values(self, set, selected_meta):
warnings.warn("\n\nThis method assumes that the last level of the index is the sample_id.\n"
"In case of single index, the index itself should be the sample_id")
sample_ids = se... | You are a Python code architect, reviewing and designing scalable and efficient code |
Provides statistics of a group based on the meta data selected. | How would you explain what the following Python 3 function does
def group_statistics(self, group, selected_meta, stat_code='mean'):
values = self.get_values(group, selected_meta)
if stat_code == 'mean':
res = statistics.mean(values)
elif stat_code == 'variance':
res = sta... | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates a bag of genomes representation for data mining purposes | Can you generate the documentation for the following Python 3 function
def to_bag_of_genomes(self, clustering_object):
meta_files = Parser._get_files('meta', self._path)
meta_dict = {}
for f in meta_files:
meta_dict[Parser.get_sample_id(f)] = f
clusters = []
if isin... | You are a Python code architect, reviewing and designing scalable and efficient code |
def to_term_document_matrix(path_to_bag_of_genomes, max_df=0.99, min_df=1, use_idf=False):
"""
Creates a term-document matrix which is a mathematical matrix that describes the frequency of terms
that occur in a collection of documents (in our case a collection of genomes).
:param path_t... | Implement a Python 3 function for
creating a term - document matrix that describes the frequency of terms that occur in a collection of genomes. | You are a Python code analyst, evaluating scripts for potential improvements. |
Computes the term frequency and stores it as a dictionary | Can you tell what is the following Python 3 function doing
def tf(cluster):
counts = dict()
words = cluster.split(' ')
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts | You are a Python code generator, capable of creating scripts from specifications. |
def best_descriptive_meta_dict(path_to_bag_of_genomes, cluster_no):
"""
Computes the importance of each metadata by using tf * coverage (the percentage of the term occuring in a cluster)
:param path_to_bag_of_genomes: The directory path
:param cluster_no: cluster number
:param p... | How would you implement a function in Python 3 that
computes the dictionary of metadata for each cluster. | You are a Python code architect, reviewing and designing scalable and efficient code |
def visualize_cloud_of_words(dictionary, image_path=None):
"""
Renders the cloud of words representation for a given dictionary of frequencies
:param dictionary: the dictionary object that contains key-frequency pairs
:param image_path: the path to the image mask, None if no masking is ... | Create a Python 3 function for
rendering the cloud of words representation for a given dictionary of frequencies. | You are a Python code generator, capable of creating scripts from specifications. |
def cloud_of_words(path_to_bog, cluster_no, image_path=None):
"""
Draws the cloud of words representation
:param path_to_bog: path to bag of words
:param cluster_no: the number of document to be visualized
:param image_path: path to the image file for the masking, None if no mas... | Implement a Python 3 function for
drawing the cloud of words representation | You are a Python code generator, capable of creating scripts from specifications. |
def _get_files(extension, path):
"""
Returns a sorted list of all of the files having the same extension under the same directory
:param extension: the extension of the data files such as 'gdm'
:param path: path to the folder containing the files
:return: sorted list of files
... | Write a Python 3 script for
returning a sorted list of all of the files having the same extension under the same directory | As a python code expert, you are capable of creating scripts from specifications. |
Returns the schema file containing the specified extension | Make a summary of the following Python 3 code
def _get_schema_file(extension, path):
for file in os.listdir(path):
if file.endswith(extension):
return os.path.join(path, file) | As a python code expert, you are capable of creating scripts from specifications. |
Parses the schema file and returns the columns that are later going to represent the columns of the genometric space dataframe
| Explain what the following Python 3 code does
def parse_schema(schema_file):
e = xml.etree.ElementTree.parse(schema_file)
root = e.getroot()
cols = []
for elem in root.findall(".//{http://genomic.elet.polimi.it/entities}field"): # XPATH
cols.append(elem.text)
return ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def parse_single_meta(self, fname, selected_meta_data):
"""
Parses a single meta data file
:param fname: name of the file
:param selected_meta_data: If not none then only the specified columns of metadata are parsed
:return: the resulting pandas series
"""
# reads... | Write a Python 3 script for
parsing a single meta data file into a pandas dataframe | As a Python code analyst, you investigate and solve complex coding mysteries |
Parses all of the metadata files and returns a dataframe with the metadata columns that are contained in the selected_meta_data. | Can you tell what is the following Python 3 function doing
def parse_meta(self, selected_meta_data):
# reads all meta data files
files = self._get_files("meta", self.path)
df = pd.DataFrame()
print("Parsing the metadata files...")
for f in tqdm(files):
data = self.par... | You are a Python code architect, reviewing and designing scalable and efficient code |
def parse_single_data(self, path, cols, selected_region_data, selected_values, full_load):
"""
Parses a single region data file
:param path: path to the file
:param cols: the column names coming from the schema file
:param selected_region_data: the selected of the region data to ... | Create a Python 3 function to
parse a single region data file and returns a dataframe containing the region data. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Parses the data files and returns a dataframe with the data. | Here you have a function in Python 3, explain what it does
def parse_data(self, selected_region_data, selected_values, full_load=False, extension="gdm"):
regions = list(selected_region_data)
if type(selected_values) is list:
regions.extend(selected_values)
else:
regions.a... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates a GDataframe from a pandas dataframe of region and metadata. | Can you generate the documentation for the following Python 3 function
def from_pandas(regs, meta=None, chr_name=None, start_name=None, stop_name=None,
strand_name=None, sample_name=None):
""" Creates a GDataframe from a pandas dataframe of region and a pandas dataframe of metadata
:param regs:... | You are a Python code generator, capable of creating scripts from specifications. |
def check_regs(region_df, chr_name=None, start_name=None, stop_name=None,
strand_name=None, sample_name=None):
""" Modifies a region dataframe to be coherent with the GMQL data model
:param region_df: a pandas Dataframe of regions that is coherent with the GMQL data model
:param chr_name: (o... | Create a Python 3 function for
checking that a dataframe of regions that are coherent with the GMQL data model. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def to_dataset_files(self, local_path=None, remote_path=None):
""" Save the GDataframe to a local or remote location
:param local_path: a local path to the folder in which the data must be saved
:param remote_path: a remote dataset name that wants to be used for these data
:return: None... | Can you create a Python 3 function that
saves the GDataframe to a local or remote location | As a Python code composer, you craft elegant and concise scripts. |
Converts the GDataframe into a GMQLDataset for later local or remote computation. | Here you have a function in Python 3, explain what it does
def to_GMQLDataset(self, local_path=None, remote_path=None):
local = None
remote = None
if (local_path is None) and (remote_path is None):
# get a temporary path
local = TempFileManager.get_new_dataset_tmp_folder(... | You are a Python code analyst, evaluating scripts for potential improvements. |
Projects the specified metadata attributes to a new GDataframe with additional region fields
| Can you tell what is the following Python 3 function doing
def project_meta(self, attributes):
if not isinstance(attributes, list):
raise TypeError('attributes must be a list')
meta_to_project = self.meta[attributes].applymap(lambda l: ", ".join(l))
new_regs = self.regs.merge(meta_to... | As a Python code composer, you craft elegant and concise scripts. |
def to_matrix(self, index_regs=None, index_meta=None,
columns_regs=None, columns_meta=None,
values_regs=None, values_meta=None, **kwargs):
""" Transforms the GDataframe to a pivot matrix having as index and columns the
ones specified. This function is a wrapper around... | Can you write a function in Python 3 where it
transforms the GDataframe to a pivot matrix having as index and columns the ones specified. | You are a Python code architect, reviewing and designing scalable and efficient code |
def charts_get(self, **kwargs):
"""
Charts
Returns a list of Charts, ordered by creation date (newest first). A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysi... | Can you create a Python 3 function that
gets Charts from Pollster. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get a Chart by its unique identifier. | Here you have a function in Python 3, explain what it does
def charts_slug_get(self, slug, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.charts_slug_get_with_http_info(slug, **kwargs)
else:
(data) = self.charts_slug_get_with_htt... | As a Python code analyst, you investigate and solve complex coding mysteries |
This method returns a TSV for a particular poll question in a Pollster Chart. | Can you generate a brief explanation for the following Python 3 code
def charts_slug_pollster_chart_poll_questions_tsv_get(self, slug, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.charts_slug_pollster_chart_poll_questions_tsv_get_with_http_info(sl... | As a Python code analyst, you investigate and solve complex coding mysteries |
def charts_slug_pollster_trendlines_tsv_get(self, slug, **kwargs):
"""
Estimates of what the polls suggest about trends
Derived data presented on a Pollster Chart. The trendlines on a Pollster chart don't add up to 100: we calculate each label's trendline separately. Use the `charts/{slug}` re... | Create a Python 3 function for
estimating of what the polls suggest about trends Derived data presented on a Pollster Chart. The trendlines on a Pollster chart don't add up to 100: we calculate each label's trendline separately. Use the `charts/{slug}` response's `chart.pollster_estimates[0].algorithm` to find the algo... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get a list of polls on a Pollster. | Given the following Python 3 function, write the documentation
def polls_get(self, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.polls_get_with_http_info(**kwargs)
else:
(data) = self.polls_get_with_http_info(**kwargs)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def polls_slug_get(self, slug, **kwargs):
"""
Poll
A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include ever... | Can you create a Python 3 function that
gets a Poll from the Pollster with the given slug. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get Questions from Pollster. | Can you tell what is the following Python 3 function doing
def questions_get(self, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.questions_get_with_http_info(**kwargs)
else:
(data) = self.questions_get_with_http_info(**kwargs)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def questions_slug_get(self, slug, **kwargs):
"""
Question
A Question is chosen by Pollster editors. One example is \"Obama job approval\". Different survey houses may publish varying phrasings (\"Do you approve or disapprove\" vs \"What do you think of the job\") and prompt readers with varyin... | Can you write a function in Python 3 where it
gets a single Question by its unique identifier. | As a Python code composer, you craft elegant and concise scripts. |
This method is used to get the TSV of a Poll from the TSV table. | How would you explain what the following Python 3 function does
def questions_slug_poll_responses_clean_tsv_get(self, slug, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.questions_slug_poll_responses_clean_tsv_get_with_http_info(slug, **kwargs)
... | As a Python code composer, you craft elegant and concise scripts. |
def questions_slug_poll_responses_raw_tsv_get(self, slug, **kwargs):
"""
One row per PollQuestion+Subpopulation+Response concerning the given Question (Large)
Raw data from which we derived `poll-responses-clean.tsv`. Each row represents a single PollQuestion+Subpopulation+Response. See the Pol... | Can you implement a function in Python 3 that
gets a single entry in the raw data from which we derived a question. | As a Python code analyst, you investigate and solve complex coding mysteries |
def tags_get(self, **kwargs):
"""
Tags
Returns the list of Tags. A Tag can apply to any number of Charts and Questions; Charts and Questions, in turn, can have any number of Tags. Tags all look `like-this`: lowercase letters, numbers and hyphens.
This method makes a synchronous HTTP ... | Create a Python 3 function for
getting a list of Tags. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sanitize the data for serialization. | Can you tell what is the following Python 3 function doing
def sanitize_for_serialization(self, obj):
types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,)
if isinstance(obj, type(None)):
return None
elif isinstance(obj, types):
return obj
elif i... | As a Python code analyst, you investigate and solve complex coding mysteries |
def select_header_content_type(self, content_types):
"""
Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json).
"""
if not content_types:
return 'applicat... | Write a Python 3 function for
selecting the content - type based on an array of content - types provided. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Deserializes list or dict to model object. | Given the following Python 3 function, write the documentation
def __deserialize_model(self, data, klass):
instance = klass()
if not instance.swagger_types:
return data
for attr, attr_type in iteritems(instance.swagger_types):
if data is not None \
and in... | As a Python code analyst, you investigate and solve complex coding mysteries |
Render a flat page. | Can you tell what is the following Python 3 function doing
def render_flatpage(request, f):
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated():
from django.contrib.auth.... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the absolute path of the pidfile. | Can you tell what is the following Python 3 function doing
def pidfile(self):
return os.path.abspath(
os.path.expandvars(
os.path.expanduser(
self._pidfile,
),
),
) | As a Python code composer, you craft elegant and concise scripts. |
Computes the square matrix of the argument | Make a summary of the following Python 3 code
def SQRT(argument):
if isinstance(argument, MetaField):
return argument._unary_expression("SQRT")
elif isinstance(argument, RegField):
return argument._unary_expression("SQRT")
else:
raise TypeError("You have to give as input a RegField (... | You are a Python code analyst, evaluating scripts for potential improvements. |
def login():
""" Enables the user to login to the remote GMQL service.
If both username and password are None, the user will be connected as guest.
"""
from .RemoteConnection.RemoteManager import RemoteManager
global __remote_manager, __session_manager
logger = logging.getLogger()
remote_ad... | Can you create a Python 3 function that
enables the user to login to the remote GMQL service. | You are a Python code generator, capable of creating scripts from specifications. |
This is the main function which runs a loop. | Can you generate the documentation for the following Python 3 function
def main(idle):
while True:
LOG.debug("Sleeping for {0} seconds.".format(idle))
time.sleep(idle) | As a Python code composer, you craft elegant and concise scripts. |
Returns the metadata related to the current GMQLDataset. | Can you tell what is the following Python 3 function doing
def get_metadata(self):
if self.path_or_name is None:
raise ValueError("You cannot explore the metadata of an intermediate query."
"You can get metadata only after a load_from_local or load_from_remote")
... | As a python code expert, you are capable of creating scripts from specifications. |
Creates an instance of a MetaField object that is used in creating expressions for projection or selection. | Here you have a function in Python 3, explain what it does
def MetaField(self, name, t=None):
return MetaField(name=name, index=self.__index, t=t) | You are a Python code architect, reviewing and designing scalable and efficient code |
Select metadata and region features from the external dataset. | How would you explain what the following Python 3 function does
def select(self, meta_predicate=None, region_predicate=None,
semiJoinDataset=None, semiJoinMeta=None):
""" *Wrapper of* ``SELECT``
Selection operation. Enables to filter datasets on the basis of region features or metadata ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def meta_select(self, predicate=None, semiJoinDataset=None, semiJoinMeta=None):
"""
*Wrapper of* ``SELECT``
Wrapper of the :meth:`~.select` function filtering samples only based on metadata.
:param predicate: logical predicate on the values of the rows
:param semiJoinDataset: a... | Implement a Python 3 function for
wrapping of ~. select function filtering samples only based on metadata. | As a Python code analyst, you investigate and solve complex coding mysteries |
def reg_select(self, predicate=None, semiJoinDataset=None, semiJoinMeta=None):
"""
*Wrapper of* ``SELECT``
Wrapper of the :meth:`~.select` function filtering regions only based on region attributes.
:param predicate: logical predicate on the values of the regions
:param semiJoi... | Create a Python 3 function to
wrap of ~. select function that returns a new GMQLDataset containing only the regions whose field score is greater than the sample s size. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def project(self, projected_meta=None, new_attr_dict=None, all_but_meta=None,
projected_regs=None, new_field_dict=None, all_but_regs=None):
"""
*Wrapper of* ``PROJECT``
The PROJECT operator creates, from an existing dataset, a new dataset with all the samples
(with their... | Create a Python 3 function to
create a new GMQLDataset from the input dataset and returns the new dataset with all the samples in the input one. | You are a Python code analyst, evaluating scripts for potential improvements. |
def meta_project(self, attr_list=None, all_but=None, new_attr_dict=None):
"""
*Wrapper of* ``PROJECT``
Project the metadata based on a list of attribute names
:param attr_list: list of the metadata fields to select
:param all_but: list of metadata that must be excluded ... | Can you write a function in Python 3 where it
projects the metadata based on a list of attribute names and return a new GMQLDataset object | As a Python code translator, you convert algorithms and pseudocode into Python. |
This method extends the current GMQLDataset with the values from the input dictionary. | Can you tell what is the following Python 3 function doing
def extend(self, new_attr_dict):
if isinstance(new_attr_dict, dict):
expBuild = self.pmg.getNewExpressionBuilder(self.__index)
aggregates = []
for k in new_attr_dict.keys():
if isinstance(k, str):
... | You are a Python code architect, reviewing and designing scalable and efficient code |
A wrapper around the COVER method that returns a new set of normal entries for the given time range. | How would you explain what the following Python 3 function does
def normal_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="normal") | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a flat version of the cover function that returns all the regions in the COVER that are in the given range. | Can you generate a brief explanation for the following Python 3 code
def flat_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
return self.cover(minAcc, maxAcc, groupBy, new_reg_fields, cover_type="flat") | As a Python code translator, you convert algorithms and pseudocode into Python. |
def summit_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns only those portions of the COVER
result where the maximum number of regions overlap (this is done by returning only
regions ... | Implement a function in Python 3 to
return a COVER that returns only those that are within the given minimum and maximum accumulation index. | As a python code expert, you are capable of creating scripts from specifications. |
def histogram_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns all regions contributing to
the COVER divided in different (contiguous) parts according to their accumulation
index val... | Implement a function in Python 3 to
return a histogram of all regions contributing to a particular accumulation value. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function joins two GMQLDataset objects and returns a GMQLDataset object that is the union of the input two datasets with the same number of samples and the number of samples in the output. | Can you generate a brief explanation for the following Python 3 code
def join(self, experiment, genometric_predicate, output="LEFT", joinBy=None,
refName="REF", expName="EXP", left_on=None, right_on=None):
"""
*Wrapper of* ``JOIN``
The JOIN operator takes in input two datasets, res... | You are a Python code architect, reviewing and designing scalable and efficient code |
This method returns a GMQLDataset that contains the difference between the current and the given other GMQLDataset. | Here you have a function in Python 3, explain what it does
def difference(self, other, joinBy=None, exact=False):
if isinstance(other, GMQLDataset):
other_idx = other.__index
else:
raise TypeError("other must be a GMQLDataset. "
"{} was provided".form... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function performs a union operation on the current GMQLDataset and returns the result. | Can you generate a brief explanation for the following Python 3 code
def union(self, other, left_name="LEFT", right_name="RIGHT"):
if not isinstance(left_name, str) or \
not isinstance(right_name, str):
raise TypeError("left_name and right_name must be strings. "
... | You are a Python code architect, reviewing and designing scalable and efficient code |
This method creates a new GMQLDataset that contains all the samples in the input dataset and the union of all the metadata attribute - values of the input samples. | Explain what the following Python 3 code does
def merge(self, groupBy=None):
if isinstance(groupBy, list) and \
all([isinstance(x, str) for x in groupBy]):
groupBy = Some(groupBy)
elif groupBy is None:
groupBy = none()
else:
raise TypeError("group... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def group(self, meta=None, meta_aggregates=None, regs=None,
regs_aggregates=None, meta_group_name="_group"):
"""
*Wrapper of* ``GROUP``
The GROUP operator is used for grouping both regions and/or metadata of input
dataset samples according to distinct values of certain att... | Write a Python 3 script for
grouping the samples by meta and meta_aggregates. | As a python code expert, you are capable of creating scripts from specifications. |
Group only for metadata. | Here you have a function in Python 3, explain what it does
def meta_group(self, meta, meta_aggregates=None):
return self.group(meta=meta, meta_aggregates=meta_aggregates) | As a Python code analyst, you investigate and solve complex coding mysteries |
*Wrapper of* ``GROUP``
Group operation only for region data. For further information check :meth:`~.group` | Here you have a function in Python 3, explain what it does
def regs_group(self, regs, regs_aggregates=None):
return self.group(regs=regs, regs_aggregates=regs_aggregates) | As a Python code composer, you craft elegant and concise scripts. |
Materialize the GMQL dataset. | How would you explain what the following Python 3 function does
def materialize(self, output_path=None, output_name=None, all_load=True):
current_mode = get_mode()
new_index = self.__modify_dag(current_mode)
if current_mode == 'local':
return Materializations.materialize_local(new_i... | You are a Python code analyst, evaluating scripts for potential improvements. |
Grab a new message and dispatch it to the handler. | Make a summary of the following Python 3 code
def step(self):
message = self.get_message()
if message is None:
self.sleep(self.idle_time)
return None
self.dispatch(message)
# In non-greenthread environments this does nothing. In green-thread
# environmen... | You are a Python code analyst, evaluating scripts for potential improvements. |
A decorator to register a command. | Given the following Python 3 function, write the documentation
def command(self, command, token, team_id=None, methods=['GET'], **kwargs):
if team_id is None:
team_id = self.team_id
if team_id is None:
raise RuntimeError('TEAM_ID is not found in your configuration!')
def... | You are a Python code generator, capable of creating scripts from specifications. |
Dispatch http request to registerd commands. | Can you generate a brief explanation for the following Python 3 code
def dispatch(self):
from flask import request
method = request.method
data = request.args
if method == 'POST':
data = request.form
token = data.get('token')
team_id = data.get('team_id')
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Validate request queries with registerd commands | Make a summary of the following Python 3 code
def validate(self, command, token, team_id, method):
if (team_id, command) not in self._commands:
raise SlackError('Command {0} is not found in team {1}'.format(
command, team_id))
func, _token, methods, kwargs = sel... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a response with json format | Can you generate the documentation for the following Python 3 function
def response(self, text, response_type='ephemeral', attachments=None):
from flask import jsonify
if attachments is None:
attachments = []
data = {
'response_type': response_type,
'text': t... | As a Python code composer, you craft elegant and concise scripts. |
Get the pid which represents a daemonized process. | Can you generate a brief explanation for the following Python 3 code
def pid(self):
try:
with open(self.pidfile, 'r') as pidfile:
try:
pid = int(pidfile.read().strip())
except ValueError:
return None
try:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def pid(self, pidnum):
"""Set the pid for a running process."""
try:
with open(self.pidfile, "w+") as pidfile:
pidfile.write("{0}\n".format(pidnum))
except IOError:
LOG.exception("Failed to write pidfile {0}).".format(self.pidfile))
sys.exi... | Can you write a function in Python 3 where it
sets the pid for a running process. | You are a Python code architect, reviewing and designing scalable and efficient code |
Stop managing the current pid. | How would you explain what the following Python 3 function does
def pid(self):
try:
os.remove(self.pidfile)
except IOError:
if not os.path.isfile(self.pidfile):
return None
LOG.exception("Failed to clear pidfile {0}).".format(self.pidfile))
... | You are a Python code generator, capable of creating scripts from specifications. |
def pool(self):
"""Get an gevent pool used to dispatch requests."""
self._pool = self._pool or gevent.pool.Pool(size=self.pool_size)
return self._pool | Write a Python 3 function that can
get an gevent pool used to dispatch requests. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets the ESSID of a given interface. | Can you tell what is the following Python 3 function doing
def set_essid(interface, essid):
interface = _get_bytes(interface)
essid = _get_bytes(essid)
wrq = ffi.new('struct iwreq*')
with iwlib_socket() as sock:
if essid.lower() in (b'off', b'any'):
wrq.u.essid.flags = 0
... | As a python code expert, you are capable of creating scripts from specifications. |
Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format. | Given the following Python 3 function, write the documentation
def read_adjacency_matrix(file_path, separator):
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
# Initialize lists for row and column sparse matrix arguments
row = list()
col = list()
append_row = row.... | As a Python code analyst, you investigate and solve complex coding mysteries |
Reads node - label pairs in csv format and returns a list of tuples and a sparse adjacency matrix. | Given the following Python 3 function, write the documentation
def read_node_label_matrix(file_path, separator, number_of_nodes):
# Open file
file_row_generator = get_file_row_generator(file_path, separator)
# Initialize lists for row and column sparse matrix arguments
row = list()
col = list()
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def ensure_data():
'''
Ensure that the Garuda directory and files
'''
if not os.path.exists(GARUDA_DIR):
os.makedirs(GARUDA_DIR)
Path(f'{GARUDA_DIR}/__init__.py').touch() | Create a Python 3 function for
ensuring that the Garuda directory and files are created. | You are a Python code generator, capable of creating scripts from specifications. |
Construct protobuf compiler arguments | Explain what the following Python 3 code does
def protoc_arguments():
'''
Construct protobuf compiler arguments
'''
proto_include = resource_filename('grpc_tools', '_proto')
return [
protoc.__file__, '-I', GARUDA_DIR, f'--python_out={GARUDA_DIR}',
f'--grpc_python_out={GARUDA_DIR}', G... | You are a Python code architect, reviewing and designing scalable and efficient code |
Simple utility function that writes an average score row in a file designated by a file pointer. | Can you generate the documentation for the following Python 3 function
def write_average_score_row(fp, score_name, scores):
row = "--" + score_name + "--"
fp.write(row)
for vector in scores:
row = list(vector)
row = [str(score) for score in row]
row = "\n" + "\t".join(row)
fp... | You are a Python code analyst, evaluating scripts for potential improvements. |
def catch_errors(f):
"""
Catches specific errors in admin actions and shows a friendly error.
"""
@functools.wraps(f)
def wrapper(self, request, *args, **kwargs):
try:
return f(self, request, *args, **kwargs)
except exceptions.CertificateExpired:
self.message... | Can you write a function in Python 3 where it
catches specific errors in admin actions and shows a friendly error. | You are a Python code architect, reviewing and designing scalable and efficient code |
Augmented TF - IDF normalization on a bag - of - words vector representation of data. | Explain what the following Python 3 code does
def augmented_tf_idf(attribute_matrix):
number_of_documents = attribute_matrix.shape[0]
max_term_frequencies = np.ones(number_of_documents, dtype=np.float64)
idf_array = np.ones(attribute_matrix.shape[1], dtype=np.float64)
# Calculate inverse document freq... | You are a Python code generator, capable of creating scripts from specifications. |
Reads an separated value file row by row. | Make a summary of the following Python 3 code
def get_file_row_generator(file_path, separator, encoding=None):
with open(file_path, encoding=encoding) as file_object:
for line in file_object:
words = line.strip().split(separator)
yield words | As a Python code composer, you craft elegant and concise scripts. |
def store_pickle(file_path, data):
"""
Pickle some data to a given path.
Inputs: - file_path: Target file path.
- data: The python object to be serialized via pickle.
"""
pkl_file = open(file_path, 'wb')
pickle.dump(data, pkl_file)
pkl_file.close() | How would you implement a function in Python 3 that
stores a pickle object to a given path. | As a Python code composer, you craft elegant and concise scripts. |
Load a pickle file from disk. | Can you tell what is the following Python 3 function doing
def load_pickle(file_path):
pkl_file = open(file_path, 'rb')
data = pickle.load(pkl_file)
pkl_file.close()
return data | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a packet to set the servo to a new ID | Make a summary of the following Python 3 code
def makeServoIDPacket(curr_id, new_id):
pkt = Packet.makeWritePacket(curr_id, xl320.XL320_ID, [new_id])
return pkt | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculates the approximate Pagerank and residual vectors at a given push node. | Can you generate the documentation for the following Python 3 function
def pagerank_limit_push(s, r, w_i, a_i, push_node, rho):
# Calculate the A and B quantities to infinity
A_inf = rho*r[push_node]
B_inf = (1-rho)*r[push_node]
# Update approximate Pagerank and residual vectors
s[push_node] += A_i... | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.