output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def transform_annotation(self, ann, duration):
'''Apply the vector transformation.
Parameters
----------
ann : jams.Annotation
The input annotation
duration : number > 0
The duration of the track
Returns
-------
data : dict
... | Write a Python 3 script to
apply the vector transformation. | You are a Python code analyst, evaluating scripts for potential improvements. |
def set_transition(self, p_self):
'''Set the transition matrix according to self-loop probabilities.
Parameters
----------
p_self : None, float in (0, 1), or np.ndarray [shape=(n_labels,)]
Optional self-loop probability(ies), used for Viterbi decoding
'''
if ... | Create a Python 3 function to
set the transition matrix according to self - loop probabilities. | As a python code expert, you are capable of creating scripts from specifications. |
def empty(self, duration):
'''Empty label annotations.
Constructs a single observation with an empty value (None).
Parameters
----------
duration : number > 0
The duration of the annotation
'''
ann = super(DynamicLabelTransformer, self).empty(duratio... | Write a Python 3 script to
empty label annotations. Empty label annotations. | You are a Python code generator, capable of creating scripts from specifications. |
def transform_annotation(self, ann, duration):
'''Transform an annotation to dynamic label encoding.
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
Returns
-------
... | Can you create a Python 3 function that
transforms an annotation to dynamic label encoding. | You are a Python code architect, reviewing and designing scalable and efficient code |
Inverse transformation of the resource. | How would you explain what the following Python 3 function does
def inverse(self, encoded, duration=None):
'''Inverse transformation'''
ann = jams.Annotation(namespace=self.namespace, duration=duration)
for start, end, value in self.decode_intervals(encoded,
... | You are a Python code generator, capable of creating scripts from specifications. |
def transform_annotation(self, ann, duration):
'''Transform an annotation to static label encoding.
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
Returns
-------
... | Implement a function in Python 3 to
transform an annotation to static label encoding. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Inverse static tag transformation | Explain what the following Python 3 code does
def inverse(self, encoded, duration=None):
'''Inverse static tag transformation'''
ann = jams.Annotation(namespace=self.namespace, duration=duration)
if np.isrealobj(encoded):
detected = (encoded >= 0.5)
else:
detect... | As a python code expert, you are capable of creating scripts from specifications. |
Compute the time position encoding of the audio buffer y. | Explain what the following Python 3 code does
def transform_audio(self, y):
'''Compute the time position encoding
Parameters
----------
y : np.ndarray
Audio buffer
Returns
-------
data : dict
data['relative'] = np.ndarray, shape=(n_frames... | As a Python code composer, you craft elegant and concise scripts. |
def add(self, operator):
'''Add an operation to this pump.
Parameters
----------
operator : BaseTaskTransformer, FeatureExtractor
The operation to add
Raises
------
ParameterError
if `op` is not of a correct type
'''
if no... | Can you implement a function in Python 3 that
adds an operation to this pump. | As a Python code analyst, you investigate and solve complex coding mysteries |
Apply the transformations to an audio file and optionally JAMS object. | Make a summary of the following Python 3 code
def transform(self, audio_f=None, jam=None, y=None, sr=None, crop=False):
'''Apply the transformations to an audio file, and optionally JAMS object.
Parameters
----------
audio_f : str
Path to audio file
jam : optional, ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Construct a sampler object for this pump s operators. | Here you have a function in Python 3, explain what it does
def sampler(self, n_samples, duration, random_state=None):
'''Construct a sampler object for this pump's operators.
Parameters
----------
n_samples : None or int > 0
The number of samples to generate
duratio... | You are a Python code generator, capable of creating scripts from specifications. |
A dictionary of fields constructed by this pump | Can you tell what is the following Python 3 function doing
def fields(self):
'''A dictionary of fields constructed by this pump'''
out = dict()
for operator in self.ops:
out.update(**operator.fields)
return out | You are a Python code architect, reviewing and designing scalable and efficient code |
Construct Keras input layers for all feature transformers
in the pump. | Given the following Python 3 function, write the documentation
def layers(self):
'''Construct Keras input layers for all feature transformers
in the pump.
Returns
-------
layers : {field: keras.layers.Input}
A dictionary of keras input layers, keyed by the correspond... | You are a Python code analyst, evaluating scripts for potential improvements. |
def set_transition_beat(self, p_self):
'''Set the beat-tracking transition matrix according to
self-loop probabilities.
Parameters
----------
p_self : None, float in (0, 1), or np.ndarray [shape=(2,)]
Optional self-loop probability(ies), used for Viterbi decoding
... | Can you write a function in Python 3 where it
sets the beat - tracking transition matrix according to the self - loop probabilities. | As a Python code composer, you craft elegant and concise scripts. |
Set the downbeat - tracking transition matrix according to the self - loop probabilities. | Here you have a function in Python 3, explain what it does
def set_transition_down(self, p_self):
'''Set the downbeat-tracking transition matrix according to
self-loop probabilities.
Parameters
----------
p_self : None, float in (0, 1), or np.ndarray [shape=(2,)]
Opt... | You are a Python code analyst, evaluating scripts for potential improvements. |
def transform_annotation(self, ann, duration):
'''Apply the beat transformer
Parameters
----------
ann : jams.Annotation
The input annotation
duration : number > 0
The duration of the audio
Returns
-------
data : dict
... | Can you write a function in Python 3 where it
applies the beat transformer to the specific resource. | You are a Python code analyst, evaluating scripts for potential improvements. |
Inverse transformation for beats and optional downbeats | Can you tell what is the following Python 3 function doing
def inverse(self, encoded, downbeat=None, duration=None):
'''Inverse transformation for beats and optional downbeats'''
ann = jams.Annotation(namespace=self.namespace, duration=duration)
beat_times = np.asarray([t for t, _ in self.deco... | As a Python code analyst, you investigate and solve complex coding mysteries |
Transform an annotation to the beat - position encoding | Make a summary of the following Python 3 code
def transform_annotation(self, ann, duration):
'''Transform an annotation to the beat-position encoding
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration... | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute the tempogram of the current object. | Can you generate a brief explanation for the following Python 3 code
def transform_audio(self, y):
'''Compute the tempogram
Parameters
----------
y : np.ndarray
Audio buffer
Returns
-------
data : dict
data['tempogram'] : np.ndarray, shap... | You are a Python code generator, capable of creating scripts from specifications. |
Apply the scale transform to the tempogram
| Make a summary of the following Python 3 code
def transform_audio(self, y):
'''Apply the scale transform to the tempogram
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['temposcale'] : np.ndarray, s... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def transform_annotation(self, ann, duration):
'''Apply the structure agreement transformation.
Parameters
----------
ann : jams.Annotation
The segment annotation
duration : number > 0
The target duration
Returns
-------
data : d... | How would you implement a function in Python 3 that
applies the structure agreement transformation. | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute the STFT magnitude and phase of the audio buffer. | How would you explain what the following Python 3 function does
def transform_audio(self, y):
'''Compute the STFT magnitude and phase.
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndar... | You are a Python code architect, reviewing and designing scalable and efficient code |
Compute the STFT with phase differentials. | Can you generate a brief explanation for the following Python 3 code
def transform_audio(self, y):
'''Compute the STFT with phase differentials.
Parameters
----------
y : np.ndarray
the audio buffer
Returns
-------
data : dict
data['mag']... | As a Python code analyst, you investigate and solve complex coding mysteries |
def transform_audio(self, y):
'''Compute the STFT
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, 1 + n_fft//2)
The STFT magnitude
'''
... | Write a Python 3 script for
computing the STFT data from the audio data. | You are a Python code architect, reviewing and designing scalable and efficient code |
Pad a chord annotation with no - chord flags. | Can you generate the documentation for the following Python 3 function
def _pad_nochord(target, axis=-1):
'''Pad a chord annotation with no-chord flags.
Parameters
----------
target : np.ndarray
the input data
axis : int
the axis along which to pad
Returns
-------
targ... | As a Python code composer, you craft elegant and concise scripts. |
Empty chord annotations
Parameters
----------
duration : number
The length (in seconds) of the empty annotation
Returns
-------
ann : jams.Annotation
A chord annotation consisting of a single `no-chord` observation. | Here you have a function in Python 3, explain what it does
def empty(self, duration):
'''Empty chord annotations
Parameters
----------
duration : number
The length (in seconds) of the empty annotation
Returns
-------
ann : jams.Annotation
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def transform_annotation(self, ann, duration):
'''Apply the chord transformation.
Parameters
----------
ann : jams.Annotation
The chord annotation
duration : number > 0
The target duration
Returns
-------
data : dict
... | How would you implement a function in Python 3 that
applies the chord transformation. | You are a Python code architect, reviewing and designing scalable and efficient code |
Apply the chord transformation. | Can you generate the documentation for the following Python 3 function
def transform_annotation(self, ann, duration):
'''Apply the chord transformation.
Parameters
----------
ann : jams.Annotation
The chord annotation
duration : number > 0
The target dur... | You are a Python code analyst, evaluating scripts for potential improvements. |
Set the transition matrix according to self - loop probabilities. | How would you explain what the following Python 3 function does
def set_transition(self, p_self):
'''Set the transition matrix according to self-loop probabilities.
Parameters
----------
p_self : None, float in (0, 1), or np.ndarray [shape=(n_labels,)]
Optional self-loop pro... | You are a Python code generator, capable of creating scripts from specifications. |
def simplify(self, chord):
'''Simplify a chord string down to the vocabulary space'''
# Drop inversions
chord = re.sub(r'/.*$', r'', chord)
# Drop any additional or suppressed tones
chord = re.sub(r'\(.*?\)', r'', chord)
# Drop dangling : indicators
chord = re.sub... | Implement a function in Python 3 to
simplify a chord string down to the vocabulary space | As a Python code analyst, you investigate and solve complex coding mysteries |
def transform_annotation(self, ann, duration):
'''Transform an annotation to chord-tag encoding
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
Returns
-------
... | Implement a Python 3 function for
transforming an annotation to chord - tag encoding | As a Python code analyst, you investigate and solve complex coding mysteries |
def transform_audio(self, y):
'''Compute the CQT
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape = (n_frames, n_bins)
The CQT magnitude
data['p... | Can you implement a function in Python 3 that
computes the CQT magnitude and phase of the audio buffer. | As a python code expert, you are capable of creating scripts from specifications. |
def transform_audio(self, y):
'''Compute CQT magnitude.
Parameters
----------
y : np.ndarray
the audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, n_bins)
The CQT magnitude
'''
... | Implement a Python 3 function for
computing CQT magnitude. Parameters ---------- y : np.ndarray the audio buffer Returns ------- data : dict data['mag'] : np.ndarray, shape=(n_frames, n_bins) The CQT magnitude | You are a Python code generator, capable of creating scripts from specifications. |
def transform_audio(self, y):
'''Compute the CQT with unwrapped phase
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, n_bins)
CQT magnitude
... | Can you implement a function in Python 3 that
computes the CQT with unwrapped phase | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute the HCQT magnitude and phase of the audio buffer. | Given the following Python 3 function, write the documentation
def transform_audio(self, y):
'''Compute the HCQT
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape = (n_frames... | As a Python code composer, you craft elegant and concise scripts. |
def _index(self, value):
'''Rearrange a tensor according to the convolution mode
Input is assumed to be in (channels, bins, time) format.
'''
if self.conv in ('channels_last', 'tf'):
return np.transpose(value, (2, 1, 0))
else: # self.conv in ('channels_first', 'th... | Create a Python 3 function for
rearranging a tensor according to the convolution mode Input is assumed to be in ( channels bins time format. | You are a Python code generator, capable of creating scripts from specifications. |
Compute HCQT magnitude.
Parameters
----------
y : np.ndarray
the audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, n_bins)
The CQT magnitude | How would you explain what the following Python 3 function does
def transform_audio(self, y):
'''Compute HCQT magnitude.
Parameters
----------
y : np.ndarray
the audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_... | You are a Python code generator, capable of creating scripts from specifications. |
Compute the HCQT with unwrapped phase
| Can you generate a brief explanation for the following Python 3 code
def transform_audio(self, y):
'''Compute the HCQT with unwrapped phase
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np... | As a Python code composer, you craft elegant and concise scripts. |
def fill_value(dtype):
'''Get a fill-value for a given dtype
Parameters
----------
dtype : type
Returns
-------
`np.nan` if `dtype` is real or complex
0 otherwise
'''
if np.issubdtype(dtype, np.floating) or np.issubdtype(dtype, np.complexfloating):
return dtype(np.nan)... | Implement a Python 3 function for
getting a fill - value for a given dtype | As a Python code composer, you craft elegant and concise scripts. |
def empty(self, duration):
'''Create an empty jams.Annotation for this task.
This method should be overridden by derived classes.
Parameters
----------
duration : int >= 0
Duration of the annotation
'''
return jams.Annotation(namespace=self.namespace... | Implement a Python 3 function for
creating an empty jams. Annotation for this task. | As a python code expert, you are capable of creating scripts from specifications. |
def transform(self, jam, query=None):
'''Transform jam object to make data for this task
Parameters
----------
jam : jams.JAMS
The jams container object
query : string, dict, or callable [optional]
An optional query to narrow the elements of `jam.annotat... | How would you implement a function in Python 3 that
transforms the jam object to make data for this task. | You are a Python code generator, capable of creating scripts from specifications. |
def encode_events(self, duration, events, values, dtype=np.bool):
'''Encode labeled events as a time-series matrix.
Parameters
----------
duration : number
The duration of the track
events : ndarray, shape=(n,)
Time index of the events
values : ... | How would you code a function in Python 3 to
encode labeled events as a time - series matrix. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def encode_intervals(self, duration, intervals, values, dtype=np.bool,
multi=True, fill=None):
'''Encode labeled intervals as a time-series matrix.
Parameters
----------
duration : number
The duration (in frames) of the track
intervals : np.... | How would you implement a function in Python 3 that
encodes labeled intervals as a time - series matrix. | As a Python code composer, you craft elegant and concise scripts. |
Decode labeled events into time value pairs. | Explain what the following Python 3 code does
def decode_events(self, encoded, transition=None, p_state=None, p_init=None):
'''Decode labeled events into (time, value) pairs
Real-valued inputs are thresholded at 0.5.
Optionally, viterbi decoding can be applied to each event class.
Par... | You are a Python code architect, reviewing and designing scalable and efficient code |
Decode labeled intervals into start end value pairs. | Can you tell what is the following Python 3 function doing
def decode_intervals(self, encoded, duration=None, multi=True, sparse=False,
transition=None, p_state=None, p_init=None):
'''Decode labeled intervals into (start, end, value) triples
Parameters
----------
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def transform(self, y, sr):
'''Transform an audio signal
Parameters
----------
y : np.ndarray
The audio signal
sr : number > 0
The native sampling rate of y
Returns
-------
dict
Data dictionary containing features ext... | Implement a function in Python 3 to
transform an audio signal y into a dictionary containing features extracted from y. | You are a Python code architect, reviewing and designing scalable and efficient code |
def phase_diff(self, phase):
'''Compute the phase differential along a given axis
Parameters
----------
phase : np.ndarray
Input phase (in radians)
Returns
-------
dphase : np.ndarray like `phase`
The phase differential.
'''
... | Can you write a function in Python 3 where it
computes the phase differential along a given axis | As a Python code analyst, you investigate and solve complex coding mysteries |
Construct Keras input layers for the given transformer
| Can you generate the documentation for the following Python 3 function
def layers(self):
'''Construct Keras input layers for the given transformer
Returns
-------
layers : {field: keras.layers.Input}
A dictionary of keras input layers, keyed by the corresponding
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the number of frames for a given duration | Can you tell what is the following Python 3 function doing
def n_frames(self, duration):
'''Get the number of frames for a given duration
Parameters
----------
duration : number >= 0
The duration, in seconds
Returns
-------
n_frames : int >= 0
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new release branch. | Can you generate a brief explanation for the following Python 3 code
def start(component, exact):
# type: (str, str) -> None
""" Create a new release branch.
Args:
component (str):
Version component to bump when creating the release. Can be *major*,
*minor* or *patch*.
... | As a Python code composer, you craft elegant and concise scripts. |
def tag(message):
# type: () -> None
""" Tag the current commit with the current version. """
release_ver = versioning.current()
message = message or 'v{} release'.format(release_ver)
with conf.within_proj_dir():
log.info("Creating release tag")
git.tag(
author=git.lates... | Implement a Python 3 function for
tagging the current commit with the current version. | As a python code expert, you are capable of creating scripts from specifications. |
def lint(exclude, skip_untracked, commit_only):
# type: (List[str], bool, bool) -> None
""" Lint python files.
Args:
exclude (list[str]):
A list of glob string patterns to test against. If the file/path
matches any of those patters, it will be filtered out.
skip_untr... | Implement a function in Python 3 to
lint python files. Args: exclude (list[str]): A list of glob string patterns to test against. If the file/path matches any of those patters, it will be filtered out. skip_untracked (bool): If set to **True** it will skip all files not tracked by git. commit_only (bool): Only lint fil... | You are a Python code generator, capable of creating scripts from specifications. |
Run code checks using pep8. | Can you generate the documentation for the following Python 3 function
def pep8_check(files):
# type: (List[str]) -> int
""" Run code checks using pep8.
Args:
files (list[str]):
A list of files to check
Returns:
bool: **True** if all files passed the checks, **False** other... | You are a Python code analyst, evaluating scripts for potential improvements. |
def pylint_check(files):
# type: (List[str]) -> int
""" Run code checks using pylint.
Args:
files (list[str]):
A list of files to check
Returns:
bool: **True** if all files passed the checks, **False** otherwise.
"""
files = fs.wrap_paths(files)
cfg_path = conf.... | Write a Python 3 function for
running code checks using pylint. | As a Python code composer, you craft elegant and concise scripts. |
def run(self):
# type: () -> bool
""" Run all linters and report results.
Returns:
bool: **True** if all checks were successful, **False** otherwise.
"""
with util.timed_block() as t:
files = self._collect_files()
log.info("Collected <33>{} <32>f... | Can you write a function in Python 3 where it
runs all linters and report results. | As a python code expert, you are capable of creating scripts from specifications. |
Send data to the Azure Cloud | Can you generate the documentation for the following Python 3 function
def send_to_azure(instance, data, replace=True, types=None, primary_key=(), sub_commit=True):
# Time initialization
start = datetime.datetime.now()
# Extract info
rows = data["rows"]
if not rows:
return 0
table_name... | You are a Python code generator, capable of creating scripts from specifications. |
def getdict(source):
"""Returns a standard python Dict with computed values
from the DynDict
:param source: (DynDict) input
:return: (dict) Containing computed values
"""
std_dict = {}
for var, val in source.iteritems():
std_dict[var] = source[var]
return std_dict | Can you implement a function in Python 3 that
returns a standard python Dict with computed values from the DynDict | You are a Python code analyst, evaluating scripts for potential improvements. |
Add a new property to the app with setattr | Explain what the following Python 3 code does
def enrich_app(self, name, value):
'''
Add a new property to the app (with setattr)
Args:
name (str): the name of the new property
value (any): the value of the new property
'''
#Method shouldn't be added: ht... | As a python code expert, you are capable of creating scripts from specifications. |
def linfit(x_true, y, sigmay=None, relsigma=True, cov=False, chisq=False, residuals=False):
"""
Least squares linear fit.
Fit a straight line `f(x_true) = a + bx` to points `(x_true, y)`. Returns
coefficients `a` and `b` that minimize the squared error.
Parameters
----------
x_t... | Implement a Python 3 function for
returning a new node with the least squares linear fit. | As a Python code analyst, you investigate and solve complex coding mysteries |
Set Isogeo base URL according to platform. | Can you tell what is the following Python 3 function doing
def set_base_url(self, platform: str = "prod"):
platform = platform.lower()
self.platform = platform
if platform == "prod":
ssl = True
logging.debug("Using production platform.")
elif platform == "qa":
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def convert_uuid(self, in_uuid: str = str, mode: bool = 0):
"""Convert a metadata UUID to its URI equivalent. And conversely.
:param str in_uuid: UUID or URI to convert
:param int mode: conversion direction. Options:
* 0 to HEX
* 1 to URN (RFC4122)
* 2 to URN (Iso... | Write a Python 3 function that can
convert a UUID to its URI equivalent. | You are a Python code generator, capable of creating scripts from specifications. |
def encoded_words_to_text(self, in_encoded_words: str):
"""Pull out the character set, encoding, and encoded text from the input
encoded words. Next, it decodes the encoded words into a byte string,
using either the quopri module or base64 module as determined by the
encoding. Finally, i... | Implement a function in Python 3 to
pull out the character set, encoding, and encoded text from the input encoded words. Next, it decodes the encoded words into a byte string, using either the quopri module or base64 module as determined by the encoding. Finally, it decodes the byte string using the character set and r... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_isogeo_version(self, component: str = "api", prot: str = "https"):
"""Get Isogeo components versions. Authentication not required.
:param str component: which platform component. Options:
* api [default]
* db
* app
"""
# which component
if... | Write a Python 3 script for
getting Isogeo components versions. Authentication not required. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Constructs the edition URL of a metadata. | Make a summary of the following Python 3 code
def get_edit_url(
self,
md_id: str = None,
md_type: str = None,
owner_id: str = None,
tab: str = "identification",
):
"""Constructs the edition URL of a metadata.
:param str md_id: metadata/resource UUID
:... | You are a Python code generator, capable of creating scripts from specifications. |
def get_view_url(self, webapp: str = "oc", **kwargs):
"""Constructs the view URL of a metadata.
:param str webapp: web app destination
:param dict kwargs: web app specific parameters. For example see WEBAPPS
"""
# build wbeapp URL depending on choosen webapp
if webapp in... | Can you implement a function in Python 3 that
constructs the view URL of a metadata. | As a python code expert, you are capable of creating scripts from specifications. |
Register a new WEBAPP to use with the view URL builder. | Can you generate the documentation for the following Python 3 function
def register_webapp(self, webapp_name: str, webapp_args: list, webapp_url: str):
# check parameters
for arg in webapp_args:
if arg not in webapp_url:
raise ValueError(
"Inconsistent web... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the Isogeo API root URL from the Isogeo API ID token generator. | Can you generate a brief explanation for the following Python 3 code
def get_url_base_from_url_token(
self, url_api_token: str = "https://id.api.isogeo.com/oauth/token"
):
"""Returns the Isogeo API root URL (which is not included into
credentials file) from the token URL (which is always inc... | As a Python code analyst, you investigate and solve complex coding mysteries |
Simple helper to handle pagination. Returns the number of pages for a specific number of results. | Can you tell what is the following Python 3 function doing
def pages_counter(self, total: int, page_size: int = 100) -> int:
if total <= page_size:
count_pages = 1
else:
if (total % page_size) == 0:
count_pages = total / page_size
else:
... | As a python code expert, you are capable of creating scripts from specifications. |
Reverse search tags dictionary to values as keys. Used to populate filters comboboxes for example. | Can you generate the documentation for the following Python 3 function
def tags_to_dict(self, tags=dict, prev_query=dict, duplicated: str = "rename"):
# for rename option, get workgroups
if duplicated == "rename":
wgs = {k.split(":")[1]: v for k, v in tags.items() if k.startswith("owner")}
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Extend share model with additional informations. | Given the following Python 3 function, write the documentation
def share_extender(self, share: dict, results_filtered: dict):
# add share administration URL
creator_id = share.get("_creator").get("_tag")[6:]
share["admin_url"] = "{}/groups/{}/admin/shares/{}".format(
self.app_url, cr... | As a Python code analyst, you investigate and solve complex coding mysteries |
Generate. pypirc config with the given credentials. | Can you generate a brief explanation for the following Python 3 code
def configure(username, password):
# type: (str, str) -> None
"""
Generate .pypirc config with the given credentials.
Example:
$ peltak pypi configure my_pypi_user my_pypi_pass
"""
from peltak.extra.pypi import logic... | As a Python code composer, you craft elegant and concise scripts. |
Returns the string in the translation dictionary. | Can you tell what is the following Python 3 function doing
def tr(self, subdomain: str, string_to_translate: str = "") -> str:
if subdomain not in self.translations.keys():
raise ValueError(
"'{}' is not a correct subdomain."
" Must be one of {}".format(subdomain, sel... | As a Python code composer, you craft elegant and concise scripts. |
Creates an EC2 client object | Given the following Python 3 function, write the documentation
def get_ec2_client(region_name=None, aws_access_key_id=None, aws_secret_access_key=None):
log = logging.getLogger(mod_logger + '.get_ec2_client')
# Connect to EC2 API
try:
client = boto3.client('ec2', region_name=region_name, aws_access_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_vpc_id(self):
"""Gets the VPC ID for this EC2 instance
:return: String instance ID or None
"""
log = logging.getLogger(self.cls_logger + '.get_vpc_id')
# Exit if not running on AWS
if not self.is_aws:
log.info('This machine is not running in AWS, exi... | Can you write a function in Python 3 where it
gets the VPC ID for this instance | As a python code expert, you are capable of creating scripts from specifications. |
def get_eni_id(self, interface=1):
"""Given an interface number, gets the AWS elastic network
interface associated with the interface.
:param interface: Integer associated to the interface/device number
:return: String Elastic Network Interface ID or None if not found
:raises OS... | Can you create a Python 3 function that
gives an interface number gets the elastic network interface ID associated with the interface. | You are a Python code analyst, evaluating scripts for potential improvements. |
Adds an IP address as a secondary IP address. | Can you generate a brief explanation for the following Python 3 code
def add_secondary_ip(self, ip_address, interface=1):
log = logging.getLogger(self.cls_logger + '.add_secondary_ip')
# Get the ENI ID
eni_id = self.get_eni_id(interface)
# Verify the ENI ID was found
if eni_id ... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function associates an elastic IP to the interface number on this host. | Can you tell what is the following Python 3 function doing
def associate_elastic_ip(self, allocation_id, interface=1, private_ip=None):
log = logging.getLogger(self.cls_logger + '.associate_elastic_ip')
if private_ip is None:
log.info('No private IP address provided, getting the primary IP'... | You are a Python code architect, reviewing and designing scalable and efficient code |
def allocate_elastic_ip(self):
"""Allocates an elastic IP address
:return: Dict with allocation ID and Public IP that were created
:raises: AWSAPIError, EC2UtilError
"""
log = logging.getLogger(self.cls_logger + '.allocate_elastic_ip')
# Attempt to allocate a new elasti... | Write a Python 3 function for
allocating an elastic IP address and returns the allocation ID and Public IP that were created. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates a new elastic network interface on the subnet with the specified name and security group IDs and then attaches an Elastic IP address to the EC2 instance instance_id at the specified device index. | Can you tell what is the following Python 3 function doing
def attach_new_eni(self, subnet_name, security_group_ids, device_index=2, allocation_id=None, description=''):
log = logging.getLogger(self.cls_logger + '.attach_new_eni')
log.info('Attempting to attach a new network interface to this instance..... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the Elastic IPs for this instance any are
attached to the instance. | Can you generate the documentation for the following Python 3 function
def get_elastic_ips(self):
log = logging.getLogger(self.cls_logger + '.get_elastic_ips')
instance_id = get_instance_id()
if instance_id is None:
log.error('Unable to get the Instance ID for this machine')
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def disassociate_elastic_ips(self):
"""For each attached Elastic IP, disassociate it
:return: None
:raises AWSAPIError
"""
log = logging.getLogger(self.cls_logger + '.disassociate_elastic_ips')
try:
address_info = self.get_elastic_ips()
except AWSAPI... | Write a Python 3 function that can
disassociate each attached Elastic IP from the instance. | You are a Python code architect, reviewing and designing scalable and efficient code |
def create_security_group(self, name, description='', vpc_id=None):
"""Creates a new Security Group with the specified name,
description, in the specified vpc_id if provided. If
vpc_id is not provided, use self.vpc_id
:param name: (str) Security Group Name
:param description: (... | Implement a Python 3 function for
creating a new Security Group with the specified name and description in the specified VPC ID. | As a python code expert, you are capable of creating scripts from specifications. |
def list_security_groups_in_vpc(self, vpc_id=None):
"""Lists security groups in the VPC. If vpc_id is not provided, use self.vpc_id
:param vpc_id: (str) VPC ID to list security groups for
:return: (list) Security Group info
:raises: AWSAPIError, EC2UtilError
"""
log = l... | Implement a function in Python 3 to
return a list of security groups in the VPC. | You are a Python code analyst, evaluating scripts for potential improvements. |
def configure_security_group_ingress(self, security_group_id, port, desired_cidr_blocks):
"""Configures the security group ID allowing access
only to the specified CIDR blocks, for the specified
port number.
:param security_group_id: (str) Security Group ID
:param port: (str) TC... | Write a Python 3 function for
configuring the security group ID allowing access to the specified CIDR blocks for the specified TCP Port number. | You are a Python code architect, reviewing and designing scalable and efficient code |
Revokes all ingress rules for a security group bu ID
| How would you explain what the following Python 3 function does
def revoke_security_group_ingress(self, security_group_id, ingress_rules):
log = logging.getLogger(self.cls_logger + '.revoke_security_group_ingress')
log.info('Revoking ingress rules from security group: {g}'.format(g=security_group_id))
... | As a Python code composer, you craft elegant and concise scripts. |
def launch_instance(self, ami_id, key_name, subnet_id, security_group_id=None, security_group_list=None,
user_data_script_path=None, instance_type='t2.small', root_device_name='/dev/xvda'):
"""Launches an EC2 instance with the specified parameters, intended to launch
an instance ... | Write a Python 3 script to
launch an EC2 instance with the specified parameters intended to create a CONS3RT template. | As a Python code analyst, you investigate and solve complex coding mysteries |
Describes the EC2 instances and returns a dict containing the EC2 instance data | Given the following Python 3 function, write the documentation
def get_ec2_instances(self):
log = logging.getLogger(self.cls_logger + '.get_ec2_instances')
log.info('Describing EC2 instances...')
try:
response = self.client.describe_instances()
except ClientError:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Build the documentation for the current project. | Given the following Python 3 function, write the documentation
def docs_cli(ctx, recreate, gen_index, run_doctests):
# type: (click.Context, bool, bool, bool) -> None
""" Build project documentation.
This command will run sphinx-refdoc first to generate the reference
documentation for the code base. Th... | As a Python code composer, you craft elegant and concise scripts. |
Convert a value to a Unicode string for matching with a query. | Can you generate the documentation for the following Python 3 function
def as_string(value):
if six.PY2:
buffer_types = buffer, memoryview # noqa: F821
else:
buffer_types = memoryview
if value is None:
return u''
elif isinstance(value, buffer_types):
return bytes(value)... | As a python code expert, you are capable of creating scripts from specifications. |
Given a bytestring path to a unicode object for the
purpose of displaying it to the user. | Here you have a function in Python 3, explain what it does
def displayable_path(path, separator=u'; '):
if isinstance(path, (list, tuple)):
return separator.join(displayable_path(p) for p in path)
elif isinstance(path, six.text_type):
return path
elif not isinstance(path, bytes):
# A... | As a python code expert, you are capable of creating scripts from specifications. |
Convert a path to a Unicode string for use by the operating system. | Given the following Python 3 function, write the documentation
def syspath(path, prefix=True):
# Don't do anything if we're not on windows
if os.path.__name__ != 'ntpath':
return path
if not isinstance(path, six.text_type):
# Beets currently represents Windows paths internally with UTF-8
... | You are a Python code analyst, evaluating scripts for potential improvements. |
This method is called when a new notebook template is selected. | Given the following Python 3 function, write the documentation
def on_new(self, button):
'''
Copy selected notebook template to notebook directory.
## Notes ##
- An exception is raised if the parent of the selected file is the
notebook directory.
- If notebook with... | As a Python code analyst, you investigate and solve complex coding mysteries |
Loads Swedish monetary institution codes in CSV format. | Can you generate the documentation for the following Python 3 function
def se_iban_load_map(filename: str) -> list:
out = []
name_repl = {
'BNP Paribas Fortis SA/NV, Bankfilial Sverige': 'BNP Paribas Fortis SA/NV',
'Citibank International Plc, Sweden Branch': 'Citibank International Plc',
... | As a Python code composer, you craft elegant and concise scripts. |
def admin_log(instances, msg: str, who: User=None, **kw):
"""
Logs an entry to admin logs of model(s).
:param instances: Model instance or list of instances
:param msg: Message to log
:param who: Who did the change
:param kw: Optional key-value attributes to append to message
:return: None
... | Can you implement a function in Python 3 that
logs an entry to admin logs of model instances. | You are a Python code analyst, evaluating scripts for potential improvements. |
The history admin view for this model. | Make a summary of the following Python 3 code
def history_view(self, request, object_id, extra_context=None):
from django.template.response import TemplateResponse
from django.contrib.admin.options import get_content_type_for_model
from django.contrib.admin.utils import unquote
from djan... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_object_by_filename(self, request, filename):
"""
Returns owner object by filename (to be downloaded).
This can be used to implement custom permission checks.
:param request: HttpRequest
:param filename: File name of the downloaded object.
:return: owner object
... | How would you code a function in Python 3 to
return owner object by filename. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of file download URLs for this model. | Make a summary of the following Python 3 code
def get_download_urls(self):
info = self.model._meta.app_label, self.model._meta.model_name
return [
url(r'^.+(' + self.upload_to + '/.+)/$', self.file_download_view, name='%s_%s_file_download' % info),
] | As a python code expert, you are capable of creating scripts from specifications. |
def write(version):
# type: (str) -> None
""" Write the given version to the VERSION_FILE """
if not is_valid(version):
raise ValueError("Invalid version: ".format(version))
storage = get_version_storage()
storage.write(version) | How would you code a function in Python 3 to
write the given version to the VERSION_FILE. | You are a Python code architect, reviewing and designing scalable and efficient code |
def bump(component='patch', exact=None):
# type: (str, str) -> Tuple[str, str]
""" Bump the given version component.
Args:
component (str):
What part of the version should be bumped. Can be one of:
- major
- minor
- patch
exact (str):
... | How would you code a function in Python 3 to
bump the given version component. | As a python code expert, you are capable of creating scripts from specifications. |
Bump the given version component. | Here you have a function in Python 3, explain what it does
def _bump_version(version, component='patch'):
# type: (str, str) -> str
""" Bump the given version component.
Args:
version (str):
The current version. The format is: MAJOR.MINOR[.PATCH].
component (str):
Wh... | As a python code expert, you are capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.