output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Extract the contents of the archive file to specified path. | How would you explain what the following Python 3 function does
def extract(archive_file, path=".", delete_on_success=False,
enable_rar=False):
"""
Automatically detect archive type and extract all files to specified path.
.. code:: python
import os
os.listdir(".")
# [... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def archive(files_to_archive, name="archive.zip", archive_type=None,
overwrite=False, store=False, depth=None, err_non_exist=True,
allow_zip_64=True, **tarfile_kwargs):
""" Archive a list of files (or files inside a folder), can chose between
- zip
- tar
- gz (tar.gz... | Implement a Python 3 function for
archiving a list of files or folders in a single archive. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Save a list of lists to a CSV file. | Can you generate a brief explanation for the following Python 3 code
def list_to_csv(my_list, csv_file):
if PY3:
csv_handler = open(csv_file, 'w', newline='')
else:
csv_handler = open(csv_file, 'wb')
try:
writer = csv.writer(csv_handler, delimiter=',', quoting=csv.QUOTE_ALL)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def csv_to_list(csv_file):
"""
Open and transform a CSV file into a matrix (list of lists).
.. code:: python
reusables.csv_to_list("example.csv")
# [['Name', 'Location'],
# ['Chris', 'South Pole'],
# ['Harry', 'Depth of Winter'],
# ['Bob', 'Skull']]
:param c... | Create a Python 3 function for
opening and transform a CSV file into a list of lists. | As a python code expert, you are capable of creating scripts from specifications. |
Open and load data from a JSON file. | Can you generate a brief explanation for the following Python 3 code
def load_json(json_file, **kwargs):
with open(json_file) as f:
return json.load(f, **kwargs) | As a Python code composer, you craft elegant and concise scripts. |
def save_json(data, json_file, indent=4, **kwargs):
"""
Takes a dictionary and saves it to a file as JSON
.. code:: python
my_dict = {"key_1": "val_1",
"key_for_dict": {"sub_dict_key": 8}}
reusables.save_json(my_dict,"example.json")
example.json
.. code::
... | Write a Python 3 function that can
save a dictionary to a JSON file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return configuration options as dictionary. Accepts either a single config file or a list of files. | Explain what the following Python 3 code does
def config_dict(config_file=None, auto_find=False, verify=True, **cfg_options):
if not config_file:
config_file = []
cfg_parser = ConfigParser.ConfigParser(**cfg_options)
cfg_files = []
if config_file:
if not isinstance(config_file, (list, ... | As a Python code composer, you craft elegant and concise scripts. |
def config_namespace(config_file=None, auto_find=False,
verify=True, **cfg_options):
"""
Return configuration options as a Namespace.
.. code:: python
reusables.config_namespace(os.path.join("test", "data",
"test_config.ini"))
... | Can you create a Python 3 function that
returns the configuration options as a Namespace. | You are a Python code analyst, evaluating scripts for potential improvements. |
Internal function to return a walk generator from os. walk
on Python < 3. 5 | Can you tell what is the following Python 3 function doing
def _walk(directory, enable_scandir=False, **kwargs):
walk = os.walk
if python_version < (3, 5) and enable_scandir:
import scandir
walk = scandir.walk
return walk(directory, **kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a dictionary of the contents of a directory as a dictionary hierarchy. | Can you generate a brief explanation for the following Python 3 code
def os_tree(directory, enable_scandir=False):
if not os.path.exists(directory):
raise OSError("Directory does not exist")
if not os.path.isdir(directory):
raise OSError("Path is not a directory")
full_list = []
for roo... | As a Python code analyst, you investigate and solve complex coding mysteries |
def file_hash(path, hash_type="md5", block_size=65536, hex_digest=True):
"""
Hash a given file with md5, or any other and return the hex digest. You
can run `hashlib.algorithms_available` to see which are available on your
system unless you have an archaic python version, you poor soul).
This funct... | Implement a function in Python 3 to
hash a given file with md5 or any other and return the hex digest. | You are a Python code analyst, evaluating scripts for potential improvements. |
def find_files(directory=".", ext=None, name=None,
match_case=False, disable_glob=False, depth=None,
abspath=False, enable_scandir=False):
"""
Walk through a file directory and return an iterator of files
that match requirements. Will autodetect if name has glob as magic
ch... | How would you implement a function in Python 3 that
finds all files in a directory and return an iterator of all files that match the requirements. | You are a Python code analyst, evaluating scripts for potential improvements. |
def remove_empty_directories(root_directory, dry_run=False, ignore_errors=True,
enable_scandir=False):
"""
Remove all empty folders from a path. Returns list of empty directories.
:param root_directory: base directory to start at
:param dry_run: just return a list of what w... | Can you write a function in Python 3 where it
removes all empty directories from a path. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def remove_empty_files(root_directory, dry_run=False, ignore_errors=True,
enable_scandir=False):
"""
Remove all empty files from a path. Returns list of the empty files removed.
:param root_directory: base directory to start at
:param dry_run: just return a list of what would be ... | Create a Python 3 function for
removing all empty files from a directory. | You are a Python code architect, reviewing and designing scalable and efficient code |
A generator that returns the duplicate files of a file in a directory. | Given the following Python 3 function, write the documentation
def dup_finder(file_path, directory=".", enable_scandir=False):
size = os.path.getsize(file_path)
if size == 0:
for empty_file in remove_empty_files(directory, dry_run=True):
yield empty_file
else:
with open(file_path... | You are a Python code architect, reviewing and designing scalable and efficient code |
def directory_duplicates(directory, hash_type='md5', **kwargs):
"""
Find all duplicates in a directory. Will return a list, in that list
are lists of duplicate files.
.. code: python
dups = reusables.directory_duplicates('C:\\Users\\Me\\Pictures')
print(len(dups))
# 56
... | Write a Python 3 script for
finding all duplicates in a directory. Will return a list of duplicates in that list. | As a Python code composer, you craft elegant and concise scripts. |
Join multiple paths together and return the absolute path of them. | Here you have a function in Python 3, explain what it does
def join_paths(*paths, **kwargs):
path = os.path.abspath(paths[0])
for next_path in paths[1:]:
path = os.path.join(path, next_path.lstrip("\\").lstrip("/").strip())
path.rstrip(os.sep)
return path if not kwargs.get('safe') else safe_pat... | You are a Python code analyst, evaluating scripts for potential improvements. |
Join any path or paths as a sub directory of the current file s directory. | Can you generate the documentation for the following Python 3 function
def join_here(*paths, **kwargs):
path = os.path.abspath(".")
for next_path in paths:
next_path = next_path.lstrip("\\").lstrip("/").strip() if not \
kwargs.get('strict') else next_path
path = os.path.abspath(os.pa... | As a Python code composer, you craft elegant and concise scripts. |
def check_filename(filename):
"""
Returns a boolean stating if the filename is safe to use or not. Note that
this does not test for "legal" names accepted, but a more restricted set of:
Letters, numbers, spaces, hyphens, underscores and periods.
:param filename: name of a file as a string
:retu... | Create a Python 3 function to
check if the filename is safe to use or not. | You are a Python code generator, capable of creating scripts from specifications. |
Returns a string that is safe for a given filename. | Make a summary of the following Python 3 code
def safe_filename(filename, replacement="_"):
if not isinstance(filename, str):
raise TypeError("filename must be a string")
if regex.path.linux.filename.search(filename):
return filename
safe_name = ""
for char in filename:
safe_name... | As a Python code composer, you craft elegant and concise scripts. |
def safe_path(path, replacement="_"):
"""
Replace unsafe path characters with underscores. Do NOT use this
with existing paths that cannot be modified, this to to help generate
new, clean paths.
Supports windows and *nix systems.
:param path: path as a string
:param replacement: character ... | Write a Python 3 function for
returning a path that can be used as a safe version of the file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Blocking request to change the number of running tasks | How would you explain what the following Python 3 function does
def change_task_size(self, size):
self._pause.value = True
self.log.debug("About to change task size to {0}".format(size))
try:
size = int(size)
except ValueError:
self.log.error("Cannot change task s... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Hard stop the server and sub process | Here you have a function in Python 3, explain what it does
def stop(self):
self._end.value = True
if self.background_process:
try:
self.background_process.terminate()
except Exception:
pass
for task_id, values in self.current_tasks.items():... | As a Python code composer, you craft elegant and concise scripts. |
Get the state of the class | Can you tell what is the following Python 3 function doing
def get_state(self):
return {"started": (True if self.background_process and
self.background_process.is_alive() else False),
"paused": self._pause.value,
"stopped": self._end.value,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def main_loop(self, stop_at_empty=False):
"""Blocking function that can be run directly, if so would probably
want to specify 'stop_at_empty' to true, or have a separate process
adding items to the queue. """
try:
while True:
self.hook_pre_command()
... | How would you implement a function in Python 3 that
blocks function that can be run directly and can be used to run a single process. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def run(self):
"""Start the main loop as a background process. *nix only"""
if win_based:
raise NotImplementedError("Please run main_loop, "
"backgrounding not supported on Windows")
self.background_process = mp.Process(target=self.main_loop)
... | How would you implement a function in Python 3 that
starts the main loop as a background process. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def cmd(command, ignore_stderr=False, raise_on_return=False, timeout=None,
encoding="utf-8"):
""" Run a shell command and have it automatically decoded and printed
:param command: Command to run as str
:param ignore_stderr: To not print stderr
:param raise_on_return: Run CompletedProcess.check_... | Implement a function in Python 3 to
run a shell command and have it automatically decoded and printed | You are a Python code architect, reviewing and designing scalable and efficient code |
Change working directories in style and stay organized! | Can you generate a brief explanation for the following Python 3 code
def pushd(directory):
directory = os.path.expanduser(directory)
_saved_paths.insert(0, os.path.abspath(os.getcwd()))
os.chdir(directory)
return [directory] + _saved_paths | As a Python code analyst, you investigate and solve complex coding mysteries |
Go back to where you once were. | Can you tell what is the following Python 3 function doing
def popd():
try:
directory = _saved_paths.pop(0)
except IndexError:
return [os.getcwd()]
os.chdir(directory)
return [directory] + _saved_paths | You are a Python code generator, capable of creating scripts from specifications. |
This function is just a python implementation of ls. It s just to subprocess ls. | Given the following Python 3 function, write the documentation
def ls(params="", directory=".", printed=True):
command = "{0} {1} {2}".format("ls" if not win_based else "dir",
params, directory)
response = run(command, shell=True) # Shell required for windows
response.che... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function is used to find all files in a directory or not in a file system. | Given the following Python 3 function, write the documentation
def find(name=None, ext=None, directory=".", match_case=False,
disable_glob=False, depth=None):
""" Designed for the interactive interpreter by making default order
of find_files faster.
:param name: Part of the file name
:param ex... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def head(file_path, lines=10, encoding="utf-8", printed=True,
errors='strict'):
"""
Read the first N lines of a file, defaults to 10
:param file_path: Path to file to read
:param lines: Number of lines to read in
:param encoding: defaults to utf-8 to decode as, will fail on binary
:par... | How would you implement a function in Python 3 that
reads the first N lines of a file | As a python code expert, you are capable of creating scripts from specifications. |
Returns the last N lines of a node in a node list. | Explain what the following Python 3 code does
def tail(file_path, lines=10, encoding="utf-8",
printed=True, errors='strict'):
"""
A really silly way to get the last N lines, defaults to 10.
:param file_path: Path to file to read
:param lines: Number of lines to read in
:param encoding: de... | You are a Python code architect, reviewing and designing scalable and efficient code |
Copy files from one folder to another. | Given the following Python 3 function, write the documentation
def cp(src, dst, overwrite=False):
if not isinstance(src, list):
src = [src]
dst = os.path.expanduser(dst)
dst_folder = os.path.isdir(dst)
if len(src) > 1 and not dst_folder:
raise OSError("Cannot copy multiple item to sam... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of N characters from a string. | Can you generate a brief explanation for the following Python 3 code
def cut(string, characters=2, trailing="normal"):
split_str = [string[i:i + characters] for
i in range(0, len(string), characters)]
if trailing != "normal" and len(split_str[-1]) != characters:
if trailing.lower() == ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def int_to_roman(integer):
"""
Convert an integer into a string of roman numbers.
.. code: python
reusables.int_to_roman(445)
# 'CDXLV'
:param integer:
:return: roman string
"""
if not isinstance(integer, int):
raise ValueError("Input integer must be of type int")... | Write a Python 3 function for
converting an integer into a roman string. | As a Python code composer, you craft elegant and concise scripts. |
Convert a string of roman numbers into an integer. | Make a summary of the following Python 3 code
def roman_to_int(roman_string):
roman_string = roman_string.upper().strip()
if "IIII" in roman_string:
raise ValueError("Malformed roman string")
value = 0
skip_one = False
last_number = None
for i, letter in enumerate(roman_string):
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Converts an integer or float to words. | Here you have a function in Python 3, explain what it does
def int_to_words(number, european=False):
def ones(n):
return "" if n == 0 else _numbers[n]
def tens(n):
teen = int("{0}{1}".format(n[0], n[1]))
if n[0] == 0:
return ones(n[1])
if teen in _numbers:
... | As a python code expert, you are capable of creating scripts from specifications. |
Download and compiles the OSM file and filter out the road elements. | Given the following Python 3 function, write the documentation
def filter_osm_file():
print_info('Filtering OSM file...')
start_time = time.time()
if check_osmfilter():
# params = '--keep="highway=motorway =motorway_link =trunk =trunk_link =primary =primary_link =secondary' \
# '... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a list of all tasks that are available in the RQ_JOBS_MODULES | Can you tell what is the following Python 3 function doing
def task_list():
try:
jobs_module = settings.RQ_JOBS_MODULE
except AttributeError:
raise ImproperlyConfigured(_("You have to define RQ_JOBS_MODULE in settings.py"))
if isinstance(jobs_module, string_types):
jobs_modules = (j... | You are a Python code generator, capable of creating scripts from specifications. |
Link to Django - RQ status page for this job | Explain what the following Python 3 code does
def rq_link(self):
if self.rq_job:
url = reverse('rq_job_detail',
kwargs={'job_id': self.rq_id, 'queue_index': queue_index_by_name(self.rq_origin)})
return '<a href="{}">{}</a>'.format(url, self.rq_id) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the class that is responsible for retrieving the current task s information. | How would you explain what the following Python 3 function does
def rq_task(self):
task_path = self.task.split('.')
module_name = '.'.join(task_path[:-1])
task_name = task_path[-1]
module = importlib.import_module(module_name)
return getattr(module, task_name) | You are a Python code architect, reviewing and designing scalable and efficient code |
def fix_module(job):
"""
Fix for tasks without a module. Provides backwards compatibility with < 0.1.5
"""
modules = settings.RQ_JOBS_MODULE
if not type(modules) == tuple:
modules = [modules]
for module in modules:
try:
module_match = importlib.import_module(module)
... | Can you implement a function in Python 3 that
fixes for tasks without a module. Provides backwards compatibility with < 0. 1. 5 | As a python code expert, you are capable of creating scripts from specifications. |
async def drop_model_tables(models, **drop_table_kwargs):
"""Drop tables for all given models (in the right order)."""
for m in reversed(sort_models_topologically(models)):
await m.drop_table(**drop_table_kwargs) | Implement a function in Python 3 to
drop tables for all given models. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert a model instance to a dictionary. | Make a summary of the following Python 3 code
async def model_to_dict(model, recurse=True, backrefs=False, only=None,
exclude=None, seen=None, extra_attrs=None,
fields_from_query=None, max_depth=None):
"""
Convert a model instance (and any related objects) to a di... | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def extract_rows(self, file_or_name, **reader_kwargs):
"""
Extract `self.sample_size` rows from the CSV file and analyze their
data-types.
:param str file_or_name: A string filename or a file handle.
:param reader_kwargs: Arbitrary parameters to pass to the CSV reader.
... | Implement a function in Python 3 to
extract the rows from the CSV file and analyze their data - types. | You are a Python code generator, capable of creating scripts from specifications. |
def get_checks(self):
"""Return a list of functions to use when testing values."""
return [
self.is_date,
self.is_datetime,
self.is_integer,
self.is_float,
self.default] | Create a Python 3 function to
return a list of functions to use when testing values. | As a Python code analyst, you investigate and solve complex coding mysteries |
def analyze(self, rows):
"""
Analyze the given rows and try to determine the type of value stored.
:param list rows: A list-of-lists containing one or more rows from a
csv file.
:returns: A list of peewee Field objects for each column in the CSV.
"""
... | How would you code a function in Python 3 to
analyze the given rows and try to determine the type of value stored in the table. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Clean text using bleach. | Here you have a function in Python 3, explain what it does
def clean_text(self, text):
'''Clean text using bleach.'''
if text is None:
return ''
text = re.sub(ILLEGAL_CHARACTERS_RE, '', text)
if '<' in text or '<' in text:
text = clean(text, tags=self.tags, stri... | As a Python code composer, you craft elegant and concise scripts. |
def path(self, category = None, image = None, feature = None):
"""
Constructs the path to categories, images and features.
This path function assumes that the following storage scheme is used on
the hard disk to access categories, images and features:
- categories: /impath/categor... | How would you implement a function in Python 3 that
constructs the path to the image and feature of the unique key. | You are a Python code analyst, evaluating scripts for potential improvements. |
Loads an image from disk. | How would you explain what the following Python 3 function does
def get_image(self, cat, img):
filename = self.path(cat, img)
data = []
if filename.endswith('mat'):
data = loadmat(filename)['output']
else:
data = imread(filename)
if self.size is not None:
... | As a python code expert, you are capable of creating scripts from specifications. |
Load a feature from disk. | Given the following Python 3 function, write the documentation
def get_feature(self, cat, img, feature):
filename = self.path(cat, img, feature)
data = loadmat(filename)
name = [k for k in list(data.keys()) if not k.startswith('__')]
if self.size is not None:
return imresize(... | As a python code expert, you are capable of creating scripts from specifications. |
Saves a new image. | Can you generate the documentation for the following Python 3 function
def save_image(self, cat, img, data):
filename = self.path(cat, img)
mkdir(filename)
if type(data) == np.ndarray:
data = Image.fromarray(data).convert('RGB')
data.save(filename) | You are a Python code generator, capable of creating scripts from specifications. |
Saves a new feature. | Here you have a function in Python 3, explain what it does
def save_feature(self, cat, img, feature, data):
filename = self.path(cat, img, feature)
mkdir(filename)
savemat(filename, {'output':data}) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def randsample(vec, nr_samples, with_replacement = False):
"""
Draws nr_samples random samples from vec.
"""
if not with_replacement:
return np.random.permutation(vec)[0:nr_samples]
else:
return np.asarray(vec)[np.random.randint(0, len(vec), nr_samples)] | Can you implement a function in Python 3 that
draws nr_samples random samples from vec. | As a Python code composer, you craft elegant and concise scripts. |
def calc_resize_factor(prediction, image_size):
"""
Calculates how much prediction.shape and image_size differ.
"""
resize_factor_x = prediction.shape[1] / float(image_size[1])
resize_factor_y = prediction.shape[0] / float(image_size[0])
if abs(resize_factor_x - resize_factor_y) > 1.0/image_size... | Can you implement a function in Python 3 that
calculates how much prediction. shape and image_size differ. | You are a Python code generator, capable of creating scripts from specifications. |
def dict_2_mat(data, fill = True):
"""
Creates a NumPy array from a dictionary with only integers as keys and
NumPy arrays as values. Dimension 0 of the resulting array is formed from
data.keys(). Missing values in keys can be filled up with np.nan (default)
or ignored.
Parameters
---------... | Can you implement a function in Python 3 that
converts a dictionary to a NumPy matrix. | As a Python code composer, you craft elegant and concise scripts. |
Apply a function to all values in a dictionary return a dictionary with the keys as data and the values as function. | Can you tell what is the following Python 3 function doing
def dict_fun(data, function):
return dict((k, function(v)) for k, v in list(data.items())) | You are a Python code generator, capable of creating scripts from specifications. |
def snip_string_middle(string, max_len=20, snip_string='...'):
"""
>>> snip_string_middle('this is long', 8)
'th...ong'
>>> snip_string_middle('this is long', 12)
'this is long'
>>> snip_string_middle('this is long', 8, '~')
'thi~long'
"""
#warn('use snip_string() instead', Dep... | Can you implement a function in Python 3 that
middles string of length max_len | As a python code expert, you are capable of creating scripts from specifications. |
Snips a string so that it is no longer than max_len replacing deleted characters with the snip_string. | Can you generate a brief explanation for the following Python 3 code
def snip_string(string, max_len=20, snip_string='...', snip_point=0.5):
if len(string) <= max_len:
new_string = string
else:
visible_len = (max_len - len(snip_string))
start_len = int(visible_len*snip_point)
end... | You are a Python code generator, capable of creating scripts from specifications. |
def find_common_beginning(string_list, boundary_char = None):
"""Given a list of strings, finds finds the longest string that is common
to the *beginning* of all strings in the list.
boundary_char defines a boundary that must be preserved, so that the
common string removed must end with this char.
... | Implement a Python 3 function for
giving a list of strings finds the longest string that is common to all strings in the list. | As a python code expert, you are capable of creating scripts from specifications. |
def factorise_strings (string_list, boundary_char=None):
"""Given a list of strings, finds the longest string that is common
to the *beginning* of all strings in the list and
returns a new list whose elements lack this common beginning.
boundary_char defines a boundary that must be preserved, so th... | How would you implement a function in Python 3 that
gives a list of strings finds the longest string that is common to all strings in the list and returns a new list of strings. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def load(path, variable='Datamat'):
"""
Load datamat at path.
Parameters:
path : string
Absolute path of the file to load from.
"""
f = h5py.File(path,'r')
try:
dm = fromhdf5(f[variable])
finally:
f.close()
return dm | Can you write a function in Python 3 where it
loads a datamat from a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a datamat from a dictionary that contains lists or arrays as values. | Explain what the following Python 3 code does
def VectorFactory(fields, parameters, categories = None):
'''
Creates a datamat from a dictionary that contains lists/arrays as values.
Input:
fields: Dictionary
The values will be used as fields of the datamat and the keys
as fi... | You are a Python code generator, capable of creating scripts from specifications. |
This function filters a datamat by different aspects. | Make a summary of the following Python 3 code
def filter(self, index): #@ReservedAssignment
return Datamat(categories=self._categories, datamat=self, index=index) | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a copy of the datamat. | Here you have a function in Python 3, explain what it does
def copy(self):
return self.filter(np.ones(self._num_fix).astype(bool)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Saves the object to a file. | Make a summary of the following Python 3 code
def save(self, path):
f = h5py.File(path, 'w')
try:
fm_group = f.create_group('Datamat')
for field in self.fieldnames():
try:
fm_group.create_dataset(field, data = self.__dict__[field])
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def set_param(self, key, value):
"""
Set the value of a parameter.
"""
self.__dict__[key] = value
self._parameters[key] = value | Create a Python 3 function for
setting the value of a parameter. | As a python code expert, you are capable of creating scripts from specifications. |
Returns an iterator that iterates over unique values of field | How would you explain what the following Python 3 function does
def by_field(self, field):
for value in np.unique(self.__dict__[field]):
yield self.filter(self.__dict__[field] == value) | You are a Python code architect, reviewing and designing scalable and efficient code |
Iterate over datamat and categories and returns a filtered datamat. | Explain what the following Python 3 code does
def by_cat(self):
for value in np.unique(self.category):
cat_fm = self.filter(self.category == value)
if self._categories:
yield (cat_fm, self._categories[value])
else:
yield (cat_fm, None) | You are a Python code generator, capable of creating scripts from specifications. |
def by_filenumber(self):
"""
Iterates over categories and returns a filtered datamat.
If a categories object is attached, the images object for the given
category is returned as well (else None is returned).
Returns:
(datamat, categories) : A tuple that contains fir... | Write a Python 3 script for
iterating over datamat and returns a filtered datamat and associated categories objects. | As a Python code analyst, you investigate and solve complex coding mysteries |
Add a new field to the datamat. | Make a summary of the following Python 3 code
def add_field(self, name, data):
if name in self._fields:
raise ValueError
if not len(data) == self._num_fix:
raise ValueError
self._fields.append(name)
self.__dict__[name] = data | As a Python code composer, you craft elegant and concise scripts. |
Add a new field to the Datamat with the dtype of the like_array and the shape of the like_array except for the first
dimension. | Make a summary of the following Python 3 code
def add_field_like(self, name, like_array):
new_shape = list(like_array.shape)
new_shape[0] = len(self)
new_data = ma.empty(new_shape, like_array.dtype)
new_data.mask = True
self.add_field(name, new_data) | You are a Python code architect, reviewing and designing scalable and efficient code |
def annotate (self, src_dm, data_field, key_field, take_first=True):
"""
Adds a new field (data_field) to the Datamat with data from the
corresponding field of another Datamat (src_dm).
This is accomplished through the use of a key_field, which is
used to determine how the data is c... | How would you implement a function in Python 3 that
adds a new field (data_field) to the Datamat with data from the corresponding field of another Datamat (src_dm). This is accomplished through the use of a key_field, which is used to determine how the data is copied. This operation corresponds loosely to an SQL join o... | You are a Python code architect, reviewing and designing scalable and efficient code |
Removes a field from the datamat. | Can you tell what is the following Python 3 function doing
def rm_field(self, name):
if not name in self._fields:
raise ValueError
self._fields.remove(name)
del self.__dict__[name] | You are a Python code analyst, evaluating scripts for potential improvements. |
Adds a parameter to the existing Datamat. | Can you generate the documentation for the following Python 3 function
def add_parameter(self, name, value):
if name in self._parameters:
raise ValueError("'%s' is already a parameter" % (name))
elif name in self.__dict__:
raise ValueError("'%s' conflicts with the Datamat name-sp... | As a Python code analyst, you investigate and solve complex coding mysteries |
Removes a parameter from the existing Datamat. | Here you have a function in Python 3, explain what it does
def rm_parameter(self, name):
if name not in self._parameters:
raise ValueError("no '%s' parameter found" % (name))
del self._parameters[name]
del self.__dict__[name] | As a python code expert, you are capable of creating scripts from specifications. |
def parameter_to_field(self, name):
"""
Promotes a parameter to a field by creating a new array of same
size as the other existing fields, filling it with the current
value of the parameter, and then removing that parameter.
"""
if name not in self._parameters:
... | Implement a function in Python 3 to
promote a parameter to a field by creating a new array of same size as the other existing fields and filling it with the current value of the parameter. | You are a Python code analyst, evaluating scripts for potential improvements. |
def join(self, fm_new, minimal_subset=True):
"""
Adds content of a new Datamat to this Datamat.
If a parameter of the Datamats is not equal or does not exist
in one, it is promoted to a field.
If the two Datamats have different fields then the elements for the
Datamats ... | Write a Python 3 function that can
join the current instance of Datamat with the new instance of Datamat. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def makeAngLenHist(ad, ld, fm = None, collapse=True, fit=spline_base.fit2d):
"""
Histograms and performs a spline fit on the given data,
usually angle and length differences.
Parameters:
ad : array
The data to be histogrammed along the x-axis.
May range from -180 t... | Implement a function in Python 3 to
generate a histogram of the given data along the x - axis and length differences. | You are a Python code architect, reviewing and designing scalable and efficient code |
def makeHist(x_val, y_val, fit=spline_base.fit2d,
bins=[np.linspace(-36.5,36.5,74),np.linspace(-180,180,361)]):
"""
Constructs a (fitted) histogram of the given data.
Parameters:
x_val : array
The data to be histogrammed along the x-axis.
y_val : array
... | Implement a function in Python 3 to
construct a 2D histogram of the given data. | You are a Python code architect, reviewing and designing scalable and efficient code |
Computes the distribution of angle and length of the first saccades
. | Make a summary of the following Python 3 code
def firstSacDist(fm):
ang, leng, ad, ld = anglendiff(fm, return_abs=True)
y_arg = leng[0][np.roll(fm.fix == min(fm.fix), 1)]/fm.pixels_per_degree
x_arg = reshift(ang[0][np.roll(fm.fix == min(fm.fix), 1)])
bins = [list(range(int(ceil(np.nanmax(y_arg)))+1)), n... | As a Python code composer, you craft elegant and concise scripts. |
def trajLenDist(fm):
"""
Computes the distribution of trajectory lengths, i.e.
the number of saccades that were made as a part of one trajectory
Parameters:
fm : ocupy.fixmat
The fixation data to be analysed
"""
trajLen = np.roll(fm.fix, 1... | Implement a Python 3 function for
returning the distribution of trajectory lengths i. e. the number of saccades that were made as part of one trajectory ArcGIS record. | As a python code expert, you are capable of creating scripts from specifications. |
def reshift(I):
"""
Transforms the given number element into a range of [-180, 180],
which covers all possible angle differences. This method reshifts larger or
smaller numbers that might be the output of other angular calculations
into that range by adding or subtracting 360, respectively.
To... | Write a Python 3 function that can
transform the given number element into a range of [-180, 180], which covers all possible angle differences. This method reshifts larger or smaller numbers that might be the output of other angular calculations into that range by adding or subtracting 360, respectively. To make sure t... | As a Python code composer, you craft elegant and concise scripts. |
Initializes the data for the given object. | Here you have a function in Python 3, explain what it does
def initializeData(self, fit = None, full_H1=None, max_length = 40,
in_deg = True):
"""
Prepares the data to be replicated. Calculates the second-order length
and angle dependencies between saccades and stores them in a fitt... | You are a Python code analyst, evaluating scripts for potential improvements. |
Calculates the coordinates after a specific saccade was made. | Make a summary of the following Python 3 code
def _calc_xy(self, xxx_todo_changeme, angle, length):
(x, y) = xxx_todo_changeme
return (x+(cos(radians(angle))*length),
y+(sin(radians(angle))*length)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Draw a new length - and angle - difference pair and calculates the last saccade drawn. | Explain what the following Python 3 code does
def _draw(self, prev_angle = None, prev_length = None):
if (prev_angle is None) or (prev_length is None):
(length, angle)= np.unravel_index(self.drawFrom('self.firstLenAng_cumsum', self.getrand('self.firstLenAng_cumsum')),
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Generates a given number of trajectories using the method sample. | How would you explain what the following Python 3 function does
def sample_many(self, num_samples = 2000):
x = []
y = []
fix = []
sample = []
# XXX: Delete ProgressBar
pbar = ProgressBar(widgets=[Percentage(),Bar()], maxval=num_samples).start()
f... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Draw a trajectory length first coordinates lengths angles and length - angle - difference pairs according to the empirical distribution. Each call creates one complete trajectory. | Explain what the following Python 3 code does
def sample(self):
lenghts = []
angles = []
coordinates = []
fix = []
sample_size = int(round(self.trajLen_borders[self.drawFrom('self.trajLen_cumsum', self.getrand('self.trajLen_cumsum'))]))
coordinates.append([0, 0])
... | As a python code expert, you are capable of creating scripts from specifications. |
def drawFrom(self, cumsum, r):
"""
Draws a value from a cumulative sum.
Parameters:
cumsum : array
Cumulative sum from which shall be drawn.
Returns:
int : Index of the cumulative sum element drawn.
"""
a = cumsum.rsplit(... | How would you implement a function in Python 3 that
draws a value from a cumulative sum. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def load(path):
"""
Load fixmat at path.
Parameters:
path : string
Absolute path of the file to load from.
"""
f = h5py.File(path,'r')
if 'Fixmat' in f:
fm_group = f['Fixmat']
else:
fm_group = f['Datamat']
fields = {}
params = {}
for field, va... | Can you create a Python 3 function that
loads a fixmat from a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def compute_fdm(fixmat, fwhm=2, scale_factor=1):
"""
Computes a fixation density map for the calling fixmat.
Creates a map the size of the image fixations were recorded on.
Every pixel contains the frequency of fixations
for this image. The fixation map is smoothed by convolution with a
... | Can you write a function in Python 3 where it
computes the fixation density map for the calling fixmat. | As a Python code composer, you craft elegant and concise scripts. |
Computes the relative bias of a single class hierarchy. | How would you explain what the following Python 3 function does
def relative_bias(fm, scale_factor = 1, estimator = None):
assert 'fix' in fm.fieldnames(), "Can not work without fixation numbers"
excl = fm.fix - np.roll(fm.fix, 1) != 1
# Now calculate the direction where the NEXT fixation goes to
dif... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a new fixmat object that contains all fixmats in a directory. | Can you tell what is the following Python 3 function doing
def DirectoryFixmatFactory(directory, categories = None, glob_str = '*.mat', var_name = 'fixmat'):
files = glob(join(directory,glob_str))
if len(files) == 0:
raise ValueError("Could not find any fixmats in " +
join(directory, glob_s... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function creates a new fixmat object from a matlab fixmat file. | Given the following Python 3 function, write the documentation
def FixmatFactory(fixmatfile, categories = None, var_name = 'fixmat', field_name='x'):
try:
data = loadmat(fixmatfile, struct_as_record = False)
keys = list(data.keys())
data = data[var_name][0][0]
except KeyError:
ra... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function adds feature values of feature to all fixations in
. | Given the following Python 3 function, write the documentation
def add_feature_values(self, features):
if not 'x' in self.fieldnames():
raise RuntimeError("""add_feature_values expects to find
(x,y) locations in self.x and self.y. But self.x does not exist""")
if not self._categori... | As a python code expert, you are capable of creating scripts from specifications. |
def make_reg_data(self, feature_list=None, all_controls=False):
"""
Generates two M x N matrices with M feature values at fixations for
N features. Controls are a random sample out of all non-fixated regions
of an image or fixations of the same subject group on a randomly chosen
... | Write a Python 3 function for
generating two M x N matrices with M feature values at fixations for N features. Controls are a random sample out of all non-fixated regions of an image or fixations of the same subject group on a randomly chosen image. Fixations are pooled over all subjects in the calling fixmat. Paramete... | You are a Python code generator, capable of creating scripts from specifications. |
def get_velocity(samplemat, Hz, blinks=None):
'''
Compute velocity of eye-movements.
Samplemat must contain fields 'x' and 'y', specifying the x,y coordinates
of gaze location. The function assumes that the values in x,y are sampled
continously at a rate specified by 'Hz'.
'''
Hz = float(Hz... | Write a Python 3 script to
compute velocity of eye - movements. | As a Python code analyst, you investigate and solve complex coding mysteries |
def saccade_detection(samplemat, Hz=200, threshold=30,
acc_thresh=2000, min_duration=21, min_movement=.35,
ignore_blinks=False):
'''
Detect saccades in a stream of gaze location samples.
Coordinates in samplemat are assumed to be in degrees.
Saccades are det... | Can you write a function in Python 3 where it
detects saccades in a stream of gaze location samples. | As a Python code composer, you craft elegant and concise scripts. |
def fixation_detection(samplemat, saccades, Hz=200, samples2fix=None,
respect_trial_borders=False, sample_times=None):
'''
Detect Fixation from saccades.
Fixations are defined as intervals between saccades. This function
also calcuates start and end times (in ms) for each fixatio... | Implement a function in Python 3 to
detect fixation from saccades. | 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.