text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def crop(self, data):
'''Crop a data dictionary down to its common time
Parameters
----------
data : dict
As produced by pumpp.transform
Returns
-------
data_cropped : dict
Like `data` but with all time-like axes truncated to the
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def transform_audio(self, y):
'''Compute the Mel spectrogram
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, n_mels)
The Mel spectrogram
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def empty(self, duration):
'''Empty vector annotations.
This returns an annotation with a single observation
vector consisting of all-zeroes.
Parameters
----------
duration : number >0
Length of the track
Returns
-------
ann : jams.A... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def inverse(self, vector, duration=None):
'''Inverse vector transformer'''
ann = jams.Annotation(namespace=self.namespace, duration=duration)
if duration is None:
duration = 0
ann.append(time=0, duration=duration, value=vector)
return ann |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
-------
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
-------
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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:
detected = encoded
for vd in self.encoder.i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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, 2)
data['absolute'] = np.ndarray... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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, `jams.JAMS`, str or file-like
Opti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
duration : int > 0
The duration (in frames) of each sa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fields(self):
'''A dictionary of fields constructed by this pump'''
out = dict()
for operator in self.ops:
out.update(**operator.fields)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 corresponding
fields.
'''
layermap = dict()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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,)]
Optional self-loop probability(ies), used for Viterbi decoding... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.decode_events(encoded,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 of the track
Returns
-------... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def transform_audio(self, y):
'''Compute the tempogram
Parameters
----------
y : np.ndarray
Audio buffer
Returns
-------
data : dict
data['tempogram'] : np.ndarray, shape=(n_frames, win_length)
The tempogram
'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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, shape=(n_frames, n_fmt)
The sca... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def transform_audio(self, y):
'''Compute the STFT magnitude and phase.
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, 1 + n_fft//2)
STFT magnitu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def transform_audio(self, y):
'''Compute the STFT with phase differentials.
Parameters
----------
y : np.ndarray
the audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, 1 + n_fft//2)
The STF... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
-------
target_pad
`target` expanded by 1 along the specified `axis`.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def empty(self, duration):
'''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` obser... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
-------
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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, n_bins, n_harmonics)
The CQT magnitude
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def transform_audio(self, y):
'''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
'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def transform_audio(self, y):
'''Compute the HCQT with unwrapped phase
Parameters
----------
y : np.ndarray
The audio buffer
Returns
-------
data : dict
data['mag'] : np.ndarray, shape=(n_frames, n_bins)
CQT magnitude
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 : ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.
'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
field keys.
'''
from keras.layers import Input
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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
The number of frames at this extractor's sampling rat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.latest_commit().author,
name='v{}'.format(release_ver),
message=message,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
exclude = list(exclude) + conf.get('lint.exclude', [])
runner = LintRunner(exclude, skip_untracked, commit_only)
if not runner.run():
exit(1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tool(name):
# type: (str) -> FunctionType """ Decorator for defining lint tools. Args: name (str):
The name of the tool. This name will be used to identify ... |
global g_tools
def decorator(fn): # pylint: disable=missing-docstring
# type: (FunctionType) -> FunctionType
g_tools[name] = fn
return fn
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 a... |
files = fs.wrap_paths(files)
cfg_path = conf.get_path('lint.pep8_cfg', 'ops/tools/pep8.ini')
pep8_cmd = 'pep8 --config {} {}'.format(cfg_path, files)
return shell.run(pep8_cmd, exit_on_error=False).return_code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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** ... |
files = fs.wrap_paths(files)
cfg_path = conf.get_path('lint.pylint_cfg', 'ops/tools/pylint.ini')
pylint_cmd = 'pylint --rcfile {} {}'.format(cfg_path, files)
return shell.run(pylint_cmd, exit_on_error=False).return_code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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>files in <33>{}s".format(
len(files), t.elapsed_s
))
if self.verbose:
for p in files:
log.info(" <0>{}", p)
# No files to lint - retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_base_url(self, platform: str = "prod"):
"""Set Isogeo base URLs according to platform. :param str platform: platform to use. Options: * prod [DEFAULT] * ... |
platform = platform.lower()
self.platform = platform
if platform == "prod":
ssl = True
logging.debug("Using production platform.")
elif platform == "qa":
ssl = False
logging.debug("Using Quality Assurance platform (reduced perfs).")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
# parameters check
if not isinstance(in_uuid, str):
raise TypeError("'in_uuid' expected a str value.")
else:
pass
if not checker.check_is_uuid(in_uuid):
raise ValueError("{} is not a correct UUID".format(in_uuid))
else:
pass
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
# handle RFC2047 quoting
if '"' in in_encoded_words:
in_encoded_words = in_encoded_words.strip('"')
# regex
encoded_word_regex = r"=\?{1}(.+)\?{1}([B|Q])\?{1}(.+)\?{1}="
# pull out
try:
charset, encoding, encoded_text = re.match(
e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_isogeo_version(self, component: str = "api", prot: str = "https"):
"""Get Isogeo components versions. Authentication not required. :param str component: ... |
# which component
if component == "api":
version_url = "{}://v1.{}.isogeo.com/about".format(prot, self.api_url)
elif component == "db":
version_url = "{}://v1.{}.isogeo.com/about/database".format(
prot, self.api_url
)
elif component ==... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
# checks inputs
if not checker.check_is_uuid(md_id) or not checker.check_is_uuid(owner_id):
raise ValueError("One of md_id or owner_id is not a correct UUID.")
else:
pass
if checker.check_edit_tab(tab, md_type=md_type):
pass
# construct URL
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ap... |
# build wbeapp URL depending on choosen webapp
if webapp in self.WEBAPPS:
webapp_args = self.WEBAPPS.get(webapp).get("args")
# check kwargs parameters
if set(webapp_args) <= set(kwargs):
# construct and return url
url = self.WEBAPPS.ge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_webapp(self, webapp_name: str, webapp_args: list, webapp_url: str):
"""Register a new WEBAPP to use with the view URL builder. :param str webapp_nam... |
# check parameters
for arg in webapp_args:
if arg not in webapp_url:
raise ValueError(
"Inconsistent web app arguments and URL."
" It should contain arguments to replace"
" dynamically. Example: 'http://webapp.com"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pages_counter(self, total: int, page_size: int = 100) -> int: """Simple helper to handle pagination. Returns the number of pages for a given number of results... |
if total <= page_size:
count_pages = 1
else:
if (total % page_size) == 0:
count_pages = total / page_size
else:
count_pages = (total / page_size) + 1
# method ending
return int(count_pages) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def share_extender(self, share: dict, results_filtered: dict):
"""Extend share model with additional informations. :param dict share: share returned by API :para... |
# add share administration URL
creator_id = share.get("_creator").get("_tag")[6:]
share["admin_url"] = "{}/groups/{}/admin/shares/{}".format(
self.app_url, creator_id, share.get("_id")
)
# check if OpenCatalog is activated
opencat_url = "{}/s/{}/{}".format(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def credentials_loader(self, in_credentials: str = "client_secrets.json") -> dict: """Loads API credentials from a file, JSON or INI. :param str in_credentials: p... |
accepted_extensions = (".ini", ".json")
# checks
if not path.isfile(in_credentials):
raise IOError("Credentials file doesn't exist: {}".format(in_credentials))
else:
in_credentials = path.normpath(in_credentials)
if path.splitext(in_credentials)[1] not in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(username, password):
# type: (str, str) -> None """ Generate .pypirc config with the given credentials. Example: $ peltak pypi configure my_pypi_us... |
from peltak.extra.pypi import logic
logic.gen_pypirc(username, password) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tr(self, subdomain: str, string_to_translate: str = "") -> str: """Returns translation of string passed. :param str subdomain: subpart of strings dictionary. ... |
if subdomain not in self.translations.keys():
raise ValueError(
"'{}' is not a correct subdomain."
" Must be one of {}".format(subdomain, self.translations.keys())
)
else:
pass
# translate
str_translated = self.translat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def optout_saved(sender, instance, **kwargs):
""" This is a duplicte of the view code for DRF to stop future internal Django implementations breaking. """ |
if instance.identity is None:
# look up using the address_type and address
identities = Identity.objects.filter_by_addr(
instance.address_type, instance.address
)
if identities.count() == 1:
instance.identity = identities[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_ec2_client(region_name=None, aws_access_key_id=None, aws_secret_access_key=None):
"""Gets an EC2 client :return: boto3.client object :raises: AWSAPIError... |
log = logging.getLogger(mod_logger + '.get_ec2_client')
# Connect to EC2 API
try:
client = boto3.client('ec2', region_name=region_name, aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key)
except ClientError:
_, ex, trace = sys.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_eni_id(self, interface=1):
"""Given an interface number, gets the AWS elastic network interface associated with the interface. :param interface: Integer ... |
log = logging.getLogger(self.cls_logger + '.get_eni_id')
# Get the instance-id
if self.instance_id is None:
msg = 'Instance ID not found for this machine'
log.error(msg)
raise OSError(msg)
log.info('Found instance ID: {i}'.format(i=self.instance_id))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_secondary_ip(self, ip_address, interface=1):
"""Adds an IP address as a secondary IP address :param ip_address: String IP address to add as a secondary I... |
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 is None:
msg = 'Unable to find the corresponding ENI ID for interface: {i}'. \
format(i=inter... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def associate_elastic_ip(self, allocation_id, interface=1, private_ip=None):
"""Given an elastic IP address and an interface number, associates the elastic IP to... |
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'
'address on interface {i}...'.format(i=interface))
private_ip = get_ip_addresses()['eth{i}'.format(i=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allocate_elastic_ip(self):
"""Allocates an elastic IP address :return: Dict with allocation ID and Public IP that were created :raises: AWSAPIError, EC2UtilE... |
log = logging.getLogger(self.cls_logger + '.allocate_elastic_ip')
# Attempt to allocate a new elastic IP
log.info('Attempting to allocate an elastic IP...')
try:
response = self.client.allocate_address(
DryRun=False,
Domain='vpc'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_elastic_ips(self):
"""Returns the elastic IP info for this instance any are attached :return: (dict) Info about the Elastic IPs :raises AWSAPIError """ |
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')
return
log.info('Found Instance ID: {i}'.format(i=instance_id))
log.info('Qu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 AWSAPIError:
_, ex, trace = sys.exc_info()
msg = 'Unable to determine Elastic IPs on this EC2 instance'
log.error(msg)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 t... |
log = logging.getLogger(self.cls_logger + '.list_security_groups_in_vpc')
if vpc_id is None and self.vpc_id is not None:
vpc_id = self.vpc_id
else:
msg = 'Unable to determine VPC ID to use to create the Security Group'
log.error(msg)
raise EC2Util... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def revoke_security_group_ingress(self, security_group_id, ingress_rules):
"""Revokes all ingress rules for a security group bu ID :param security_group_id: (str... |
log = logging.getLogger(self.cls_logger + '.revoke_security_group_ingress')
log.info('Revoking ingress rules from security group: {g}'.format(g=security_group_id))
try:
self.client.revoke_security_group_ingress(
DryRun=False,
GroupId=security_group_id... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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', roo... |
log = logging.getLogger(self.cls_logger + '.launch_instance')
log.info('Launching with AMI ID: {a}'.format(a=ami_id))
log.info('Launching with Key Pair: {k}'.format(k=key_name))
if security_group_list:
if not isinstance(security_group_list, list):
raise EC2U... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_ec2_instances(self):
"""Describes the EC2 instances :return: dict containing EC2 instance data :raises: EC2UtilError """ |
log = logging.getLogger(self.cls_logger + '.get_ec2_instances')
log.info('Describing EC2 instances...')
try:
response = self.client.describe_instances()
except ClientError:
_, ex, trace = sys.exc_info()
msg = '{n}: There was a problem describing EC2 i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def docs_cli(ctx, recreate, gen_index, run_doctests):
# type: (click.Context, bool, bool, bool) -> None """ Build project documentation. This command will run sp... |
if ctx.invoked_subcommand:
return
from peltak.logic import docs
docs.docs(recreate, gen_index, run_doctests) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_string(value):
"""Convert a value to a Unicode object for matching with a query. None becomes the empty string. Bytestrings are silently decoded. """ |
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).decode('utf8', 'ignore')
elif isinstance(value, bytes):
return value.decode('ut... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def displayable_path(path, separator=u'; '):
"""Attempts to decode a bytestring path to a unicode object for the purpose of displaying it to the user. If the `pa... |
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 non-string object: just get its unicode representation.
return six.text_type(path)
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_version_storage():
# type: () -> VersionStorage """ Get version storage for the given version file. The storage engine used depends on the extension of t... |
version_file = conf.get_path('version_file', 'VERSION')
if version_file.endswith('.py'):
return PyVersionStorage(version_file)
elif version_file.endswith('package.json'):
return NodeVersionStorage(version_file)
else:
return RawVersionStorage(version_file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, version):
# type: (str) -> None """ Write the project version to .py file. This will regex search in the file for a ``__version__ = VERSION_STRIN... |
with open(self.version_file) as fp:
content = fp.read()
ver_statement = "__version__ = '{}'".format(version)
new_content = RE_PY_VERSION.sub(ver_statement, content)
fs.write_file(self.version_file, new_content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loggray(x, a, b):
"""Auxiliary function that specifies the logarithmic gray scale. a and b are the cutoffs.""" |
linval = 10.0 + 990.0 * (x-float(a))/(b-a)
return (np.log10(linval)-1.0)*0.5 * 255.0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rebin(self, factor):
""" I robustly rebin your image by a given factor. You simply specify a factor, and I will eventually take care of a crop to bring the i... |
if self.pilimage != None:
raise RuntimeError, "Cannot rebin anymore, PIL image already exists !"
if type(factor) != type(0):
raise RuntimeError, "Rebin factor must be an integer !"
if factor < 1:
return
origshape = np.asarr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makedraw(self):
"""Auxiliary method to make a draw object if not yet done. This is also called by changecolourmode, when we go from L to RGB, to get a new dr... |
if self.draw == None:
self.draw = imdw.Draw(self.pilimage) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upsample(self, factor):
""" The inverse operation of rebin, applied on the PIL image. Do this before writing text or drawing on the image ! The coordinates w... |
self.checkforpilimage()
if type(factor) != type(0):
raise RuntimeError, "Upsample factor must be an integer !"
if self.verbose:
print "Upsampling by a factor of %i" % factor
self.pilimage = self.pilimage.resize((self.pilimage.size[0] * ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drawpoint(self, x, y, colour = None):
""" Most elementary drawing, single pixel, used mainly for testing purposes. Coordinates are those of your initial imag... |
self.checkforpilimage()
colour = self.defaultcolour(colour)
self.changecolourmode(colour)
self.makedraw()
(pilx, pily) = self.pilcoords((x,y))
self.draw.point((pilx, pily), fill = colour) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writetitle(self, titlestring, colour = None):
""" We write a title, centered below the image. """ |
self.checkforpilimage()
colour = self.defaultcolour(colour)
self.changecolourmode(colour)
self.makedraw()
self.loadtitlefont()
imgwidth = self.pilimage.size[0]
imgheight = self.pilimage.size[1]
textwidth = self.draw.textsize(tit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writeinfo(self, linelist, colour = None):
""" We add a longer chunk of text on the upper left corner of the image. Provide linelist, a list of strings that w... |
self.checkforpilimage()
colour = self.defaultcolour(colour)
self.changecolourmode(colour)
self.makedraw()
self.loadinfofont()
for i, line in enumerate(linelist):
topspacing = 5 + (12 + 5)*i
self.draw.text((10, t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drawstarslist(self, dictlist, r = 10, colour = None):
""" Calls drawcircle and writelable for an list of stars. Provide a list of dictionnaries, where each d... |
self.checkforpilimage()
colour = self.defaultcolour(colour)
self.changecolourmode(colour)
self.makedraw()
for star in dictlist:
self.drawcircle(star["x"], star["y"], r = r, colour = colour, label = star["name"])
#self.writelabel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tonet(self, outfile):
""" Writes the PIL image into a png. We do not want to flip the image at this stage, as you might have written on it ! """ |
self.checkforpilimage()
if self.verbose :
print "Writing image to %s...\n%i x %i pixels, mode %s" % (outfile, self.pilimage.size[0], self.pilimage.size[1], self.pilimage.mode)
self.pilimage.save(outfile, "PNG") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cors_setup(self, request):
""" Sets up the CORS headers response based on the settings used for the API. :param request: <pyramid.request.Request> """ |
def cors_headers(request, response):
if request.method.lower() == 'options':
response.headers.update({
'-'.join([p.capitalize() for p in k.split('_')]): v
for k, v in self.cors_options.items()
})
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def factory(self, request, parent=None, name=None):
""" Returns a new service for the given request. :param request | <pyramid.request.Request> :return <pyramid_... |
traverse = request.matchdict['traverse']
# show documentation at the root path
if not traverse:
return {}
else:
service = {}
name = name or traverse[0]
# look for direct pattern matches
traversed = '/' + '/'.join(traverse)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, service, name=''):
""" Exposes a given service to this API. """ |
# expose a sub-factory
if isinstance(service, ApiFactory):
self.services[name] = (service.factory, None)
# expose a module dynamically as a service
elif inspect.ismodule(service):
name = name or service.__name__.split('.')[-1]
# exclude endpoints wi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serve(self, config, path, route_name=None, permission=None, **view_options):
""" Serves this API from the inputted root path """ |
route_name = route_name or path.replace('/', '.').strip('.')
path = path.strip('/') + '*traverse'
self.route_name = route_name
self.base_permission = permission
# configure the route and the path
config.add_route(route_name, path, factory=self.factory)
config.a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def padd(text, padding="top", size=1):
""" Adds extra new lines to the top, bottom or both of a String @text: #str text to pad @padding: #str 'top', 'bottom' or ... |
if padding:
padding = padding.lower()
pad_all = padding == 'all'
padding_top = ""
if padding and (padding == 'top' or pad_all):
padding_top = "".join("\n" for x in range(size))
padding_bottom = ""
if padding and (padding == 'bottom' or pad_all):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def colorize(text, color="BLUE", close=True):
""" Colorizes text for terminal outputs @text: #str to colorize @color: #str color from :mod:colors @close: #bool w... |
if color:
color = getattr(colors, color.upper())
return color + uncolorize(str(text)) + (colors.RESET if close else "")
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bold(text, close=True):
""" Bolds text for terminal outputs @text: #str to bold @close: #bool whether or not to reset the bold flag -> #str bolded @text .. f... |
return getattr(colors, "BOLD") + str(text) + \
(colors.RESET if close else "") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_class_that_defined_method(meth):
""" Gets the class object which defined a given method @meth: a class method -> owner class object """ |
if inspect.ismethod(meth):
for cls in inspect.getmro(meth.__self__.__class__):
if cls.__dict__.get(meth.__name__) is meth:
return cls
meth = meth.__func__ # fallback to __qualname__ parsing
if inspect.isfunction(meth):
cls = getattr(
inspect.getm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_obj_name(obj, delim="<>"):
""" Formats the object name in a pretty way @obj: any python object @delim: the characters to wrap a parent object name in ... |
pname = ""
parent_name = get_parent_name(obj)
if parent_name:
pname = "{}{}{}".format(delim[0], get_parent_name(obj), delim[1])
return "{}{}".format(get_obj_name(obj), pname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preprX(*attributes, address=True, full_name=False, pretty=False, keyless=False, **kwargs):
""" `Creates prettier object representations` @*attributes: (#str)... |
def _format(obj, attribute):
try:
if keyless:
val = getattr_in(obj, attribute)
if val is not None:
return repr(val)
else:
return '%s=%s' % (attribute,
repr(getattr_in(obj, attribute... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.