output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Get a sample from the DataStore. | Here you have a function in Python 3, explain what it does
def get_sample(self, md5):
# First we try a sample, if we can't find one we try getting a sample_set.
sample = self.data_store.get_sample(md5)
if not sample:
return {'sample_set': {'md5_list': self.get_sample_set(md5)}}
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def is_sample_set(self, md5):
""" Does the md5 represent a sample_set?
Args:
md5: the md5 of the sample_set
Returns:
True/False
"""
try:
self.get_sample_set(md5)
return True
except WorkBench.DataNotFound:
... | Can you write a function in Python 3 where it
returns True if the md5 represent a sample_set False otherwise | As a python code expert, you are capable of creating scripts from specifications. |
def get_sample_window(self, type_tag, size):
""" Get a sample from the DataStore.
Args:
type_tag: the type of samples ('pcap','exe','pdf')
size: the size of the window in MegaBytes (10 = 10MB)
Returns:
A sample_set handle which represents t... | Write a Python 3 function for
getting a sample from the DataStore. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def combine_samples(self, md5_list, filename, type_tag):
"""Combine samples together. This may have various use cases the most significant
involving a bunch of sample 'chunks' got uploaded and now we combine them together
Args:
md5_list: The list of md5s to combine, orde... | Write a Python 3 function that can
combine the samples together and store the result in the file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Stream the sample by giving back a generator that yields rows of the file. | Given the following Python 3 function, write the documentation
def stream_sample(self, md5, kwargs=None):
# Get the max_rows if specified
max_rows = kwargs.get('max_rows', None) if kwargs else None
# Grab the sample and it's raw bytes
sample = self.get_sample(md5)['sample']
raw... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_dataframe(self, md5, compress='lz4'):
"""Return a dataframe from the DataStore. This is just a convenience method
that uses get_sample internally.
Args:
md5: the md5 of the dataframe
compress: compression to use: (defaults to 'lz4' but can be set t... | Can you write a function in Python 3 where it
returns a dataframe from the DataStore. This is just a convenience method that uses get_sample internally. | As a python code expert, you are capable of creating scripts from specifications. |
Try to guess the type of the sample from the file. | Make a summary of the following Python 3 code
def guess_type_tag(self, input_bytes, filename):
mime_to_type = {'application/jar': 'jar',
'application/java-archive': 'jar',
'application/octet-stream': 'data',
'application/pdf': 'pdf',
... | You are a Python code generator, capable of creating scripts from specifications. |
Add tags to this sample | How would you explain what the following Python 3 function does
def add_tags(self, md5, tags):
if not tags: return
tag_set = set(self.get_tags(md5)) if self.get_tags(md5) else set()
if isinstance(tags, str):
tags = [tags]
for tag in tags:
tag_set.add(tag)
... | As a python code expert, you are capable of creating scripts from specifications. |
Set the tags for this sample | Here you have a function in Python 3, explain what it does
def set_tags(self, md5, tags):
if isinstance(tags, str):
tags = [tags]
tag_set = set(tags)
self.data_store.store_work_results({'tags': list(tag_set)}, 'tags', md5) | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_tags(self, md5):
"""Get tags for this sample"""
tag_data = self.data_store.get_work_results('tags', md5)
return tag_data['tags'] if tag_data else None | Write a Python 3 script for
getting tags for this sample | As a Python code analyst, you investigate and solve complex coding mysteries |
Index a stored sample with the Indexer.
| Can you tell what is the following Python 3 function doing
def index_sample(self, md5, index_name):
generator = self.stream_sample(md5)
for row in generator:
self.indexer.index_data(row, index_name) | You are a Python code generator, capable of creating scripts from specifications. |
Index the data in the index_name with the Indexer. | Given the following Python 3 function, write the documentation
def index_worker_output(self, worker_name, md5, index_name, subfield):
# Grab the data
if subfield:
data = self.work_request(worker_name, md5)[worker_name][subfield]
else:
data = self.work_request(worker_name... | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_node(self, node_id, name, labels):
""" Add a node to the graph with name and labels.
Args:
node_id: the unique node_id e.g. 'www.evil4u.com'
name: the display name of the node e.g. 'evil4u'
labels: a list of labels e.g. ['domain','evil']
... | Can you write a function in Python 3 where it
adds a node to the database. | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_rel(self, source_id, target_id, rel):
""" Add a relationship: source, target must already exist (see add_node)
'rel' is the name of the relationship 'contains' or whatever.
Args:
source_id: the unique node_id of the source
target_id: the unique nod... | Create a Python 3 function to
add a relationship between two nodes. | You are a Python code architect, reviewing and designing scalable and efficient code |
Clears the Main Database of all samples and worker output. | Given the following Python 3 function, write the documentation
def clear_db(self):
self.data_store.clear_db()
# Have the plugin manager reload all the plugins
self.plugin_manager.load_all_plugins()
# Store information about commands and workbench
self._store_information() | As a Python code composer, you craft elegant and concise scripts. |
Drops all of the worker output collections
Args : None
| How would you explain what the following Python 3 function does
def clear_worker_output(self):
self.data_store.clear_worker_output()
# Have the plugin manager reload all the plugins
self.plugin_manager.load_all_plugins()
# Store information about commands and workbench
self._st... | As a python code expert, you are capable of creating scripts from specifications. |
This function is used to make a work request for an existing stored sample. | Make a summary of the following Python 3 code
def work_request(self, worker_name, md5, subkeys=None):
# Pull the worker output
work_results = self._recursive_work_resolver(worker_name, md5)
# Subkeys (Fixme this is super klutzy)
if subkeys:
if isinstance(subkeys, str):
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set_work_request(self, worker_name, sample_set, subkeys=None):
""" Make a work request for an existing stored sample (or sample_set).
Args:
worker_name: 'strings', 'pe_features', whatever
sample_set: the md5 of a sample_set in the Workbench data store
... | Can you create a Python 3 function that
makes a work request for an existing stored sample (or sample_set). Args: worker_name: 'strings', 'pe_features', whatever sample_set: the md5 of a sample_set in the Workbench data store subkeys: just get a subkey of the output: 'foo' or 'foo.bar' (None for all) Returns: The outpu... | You are a Python code architect, reviewing and designing scalable and efficient code |
Store a sample set in the data store. | Can you tell what is the following Python 3 function doing
def store_sample_set(self, md5_list):
# Sanity check
if not md5_list:
print 'Warning: Trying to store an empty sample_set'
return None
# Remove any duplicates
md5_list = list(set(md5_list))
for ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate a sample_set that maches the tags or all if tags are not specified. | Explain what the following Python 3 code does
def generate_sample_set(self, tags=None):
if isinstance(tags, str):
tags = [tags]
md5_list = self.data_store.tag_match(tags)
return self.store_sample_set(md5_list) | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the formatted help for the given topic | Make a summary of the following Python 3 code
def help(self, topic=None):
if not topic:
topic = 'workbench'
# It's possible to ask for help on something that doesn't exist
# so we'll catch the exception and push back an object that
# indicates we didn't find what they were a... | You are a Python code analyst, evaluating scripts for potential improvements. |
Help for Workbench Basics | Can you generate a brief explanation for the following Python 3 code
def _help_basic(self):
help = '%sWorkbench: Getting started...' % (color.Yellow)
help += '\n%sStore a sample into Workbench:' % (color.Green)
help += '\n\t%s$ workbench.store_sample(raw_bytes, filename, type_tag)' % (color.Li... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _help_commands(self):
""" Help on all the available commands """
help = 'Workbench Commands:'
for command in self.list_all_commands():
full_help = self.work_request('help_formatter', command)['help_formatter']['help']
compact_help = full_help.split('\n')[:2]
... | Implement a Python 3 function for
helping on all available commands | You are a Python code architect, reviewing and designing scalable and efficient code |
Help on all the available workers | Explain what the following Python 3 code does
def _help_workers(self):
help = 'Workbench Workers:'
for worker in self.list_all_workers():
full_help = self.work_request('help_formatter', worker)['help_formatter']['help']
compact_help = full_help.split('\n')[:4]
help +... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of all the Workbench commands | Explain what the following Python 3 code does
def list_all_commands(self):
commands = [name for name, _ in inspect.getmembers(self, predicate=inspect.isroutine) if not name.startswith('_')]
return commands | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the information about this component | Can you generate a brief explanation for the following Python 3 code
def get_info(self, component):
# Grab it, clean it and ship it
work_results = self._get_work_results('info', component)
return self.data_store.clean_for_serialization(work_results) | You are a Python code analyst, evaluating scripts for potential improvements. |
Store information about a specific component. | How would you explain what the following Python 3 function does
def store_info(self, info_dict, component, type_tag):
# Enforce dictionary input
if not isinstance(info_dict, dict):
print 'Critical: info_dict must be a python dictionary, got %s' % type(info_dict)
return
... | You are a Python code generator, capable of creating scripts from specifications. |
Stores information about Workbench commands and workers and help text into the system s information. | Can you tell what is the following Python 3 function doing
def _store_information(self):
print '<<< Generating Information Storage >>>'
# Stores information on Workbench commands and signatures
for name, meth in inspect.getmembers(self, predicate=inspect.isroutine):
if not ... | As a Python code composer, you craft elegant and concise scripts. |
Internal method for handling new plugins. | Can you generate the documentation for the following Python 3 function
def _new_plugin(self, plugin):
# First store the plugin info into our data store
self.store_info(plugin, plugin['name'], type_tag='worker')
# Place it into our active plugin list
self.plugin_meta[plugin['name']] = p... | As a Python code analyst, you investigate and solve complex coding mysteries |
Internal method to store the work results in the data store. | Can you tell what is the following Python 3 function doing
def _store_work_results(self, results, collection, md5):
self.data_store.store_work_results(results, collection, md5) | As a Python code composer, you craft elegant and concise scripts. |
Internal method that recursively generates the work results for the given worker_name and md5. | How would you explain what the following Python 3 function does
def _recursive_work_resolver(self, worker_name, md5):
# Looking for the sample?
if worker_name == 'sample':
return self.get_sample(md5)
# Looking for info?
if worker_name == 'info':
return self._get... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Load a sample into a workbench object | Given the following Python 3 function, write the documentation
def load_sample(self, file_path, tags=None):
# Recommend a tag
if not tags:
print '\n%sRequired: Add a list of tags when you load samples (put \'unknown\' if you must). \
\n\t%sExamples: [\'bad\'], [\'good\'],... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Pivot on an md5 | Here you have a function in Python 3, explain what it does
def pivot(self, md5, tag=''):
# Is the md5 a tag?
ss = self.workbench.generate_sample_set(md5)
if ss:
tag = md5 if not tag else tag
md5 = ss
# Is the md5 a sample_set?
if self.workbench.is_sample... | You are a Python code analyst, evaluating scripts for potential improvements. |
Display tag information for all samples in database | Given the following Python 3 function, write the documentation
def tags(self):
'''Display tag information for all samples in database'''
tags = self.workbench.get_all_tags()
if not tags:
return
tag_df = pd.DataFrame(tags)
tag_df = self.vectorize(tag_df, 'tags')
... | You are a Python code generator, capable of creating scripts from specifications. |
Wrapper for the Workbench get_dataframe method
| Here you have a function in Python 3, explain what it does
def pull_df(self, md5):
try:
_packed_df = self.workbench.get_dataframe(md5)
_df = pd.read_msgpack(lz4.loads(_packed_df))
return _df
except zerorpc.exceptions.RemoteError as e:
return repr_to_str_de... | You are a Python code analyst, evaluating scripts for potential improvements. |
Flatten a column in the dataframe that contains lists | Can you tell what is the following Python 3 function doing
def flatten(self, df, column_name):
_exp_list = [[md5, x] for md5, value_list in zip(df['md5'], df[column_name]) for x in value_list]
return pd.DataFrame(_exp_list, columns=['md5',column_name]) | As a python code expert, you are capable of creating scripts from specifications. |
Give aggregation counts and correlations | Can you generate a brief explanation for the following Python 3 code
def top_corr(self, df):
tag_freq = df.sum()
tag_freq.sort(ascending=False)
corr = df.corr().fillna(1)
corr_dict = corr.to_dict()
for tag, count in tag_freq.iteritems():
print ' %s%s: %s%s%s (' % (... | As a Python code composer, you craft elegant and concise scripts. |
Wrapper for the Workbench search method
| Can you generate the documentation for the following Python 3 function
def search(self, tags=None):
if isinstance(tags, str):
tags = [tags]
return self.workbench.generate_sample_set(tags) | As a Python code composer, you craft elegant and concise scripts. |
Announce Versions of CLI and Server
| Can you generate the documentation for the following Python 3 function
def versions(self):
print '%s<<< Workbench CLI Version %s >>>%s' % (color.LightBlue, self.version, color.Normal)
print self.workbench.help('version') | You are a Python code architect, reviewing and designing scalable and efficient code |
Runs the workbench CLI | Given the following Python 3 function, write the documentation
def run(self):
''' Running the workbench CLI '''
# Announce versions
self.versions()
# Sample/Tag info and Help
self.tags()
print '\n%s' % self.workbench.help('cli')
# Now that we have the Workbench... | As a Python code composer, you craft elegant and concise scripts. |
Connect to the workbench server | How would you explain what the following Python 3 function does
def _connect(self, server_info):
# First we do a temp connect with a short heartbeat
_tmp_connect = zerorpc.Client(timeout=300, heartbeat=2)
_tmp_connect.connect('tcp://'+server_info['server']+':'+server_info['port'])
try:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Print the current progress of the current upload. | Given the following Python 3 function, write the documentation
def _progress_print(self, sent, total):
percent = min(int(sent*100.0/total), 100)
sys.stdout.write('\r{0}[{1}{2}] {3}{4}%{5}'.
format(color.Green, '#'*(percent/2), ' '*(50-percent/2), color.Yellow, percent, color.Nor... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _work_request(self, worker, md5=None):
"""Wrapper for a work_request to workbench"""
# I'm sure there's a better way to do this
if not md5 and not self.session.md5:
return 'Must call worker with an md5 argument...'
elif not md5:
md5 = self.session.md5
... | Write a Python 3 function that can
wrap for a work_request to workbench | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate a dict of functions that will be used to make the workbench with a bunch of shortcuts
and helper/alias functions that will make the shell MUCH easier. | Here you have a function in Python 3, explain what it does
def _generate_command_dict(self):
# First add all the workers
commands = {}
for worker in self.workbench.list_all_workers():
commands[worker] = lambda md5=None, worker=worker: self._work_request(worker, md5)
# Next ... | As a python code expert, you are capable of creating scripts from specifications. |
Register local methods in the Workbench Information system | Make a summary of the following Python 3 code
def _register_info(self):
# Stores information on Workbench commands and signatures
for name, meth in inspect.getmembers(self, predicate=inspect.isroutine):
if not name.startswith('_') and name != 'run':
info = {'command': name, '... | As a python code expert, you are capable of creating scripts from specifications. |
Shortcut Workbench commands by using auto - quotes | Can you generate the documentation for the following Python 3 function
def transform(self, line, _continue_prompt):
# Capture the original line
orig_line = line
# Get tokens from all the currently active namespace
ns_token_set = set([token for nspace in self.shell.all_ns_refs for token... | As a Python code analyst, you investigate and solve complex coding mysteries |
Deserialize a string representation of a BioC collection into a BioC object. | Can you generate the documentation for the following Python 3 function
def decodes(self, s: str) -> BioCCollection:
tree = etree.parse(io.BytesIO(bytes(s, encoding='UTF-8')))
collection = self.__parse_collection(tree.getroot())
collection.encoding = tree.docinfo.encoding
collection.stand... | You are a Python code analyst, evaluating scripts for potential improvements. |
Deserialize a file - like object containing a BioC collection. | Can you generate the documentation for the following Python 3 function
def decode(self, fp: TextIO) -> BioCCollection:
# utf8_parser = etree.XMLParser(encoding='utf-8')
tree = etree.parse(fp)
collection = self.__parse_collection(tree.getroot())
collection.encoding = tree.docinfo.encoding... | As a Python code analyst, you investigate and solve complex coding mysteries |
def execute(self, input_data):
''' Execute method '''
# Grab the raw bytes of the sample
raw_bytes = input_data['sample']['raw_bytes']
# Spin up the rekall session and render components
session = MemSession(raw_bytes)
renderer = WorkbenchRenderer(session=session)
... | Implement a function in Python 3 to
execute the plugin and return the output | You are a Python code generator, capable of creating scripts from specifications. |
Process the row data from Rekall | Explain what the following Python 3 code does
def process_row(cls, data, column_map):
row = {}
for key,value in data.iteritems():
if not value:
value = '-'
elif isinstance(value, list):
value = value[1]
elif isinstance(v... | You are a Python code generator, capable of creating scripts from specifications. |
Start method that initial data structures and store some meta data. | How would you explain what the following Python 3 function does
def start(self, plugin_name=None, kwargs=None):
self.output = [] # Start basically resets the output data
super(WorkbenchRenderer, self).start(plugin_name=plugin_name)
return self | As a Python code composer, you craft elegant and concise scripts. |
Presentation Information from the Plugin | Explain what the following Python 3 code does
def format(self, formatstring, *args):
# Make a new section
if self.incoming_section:
self.SendMessage(['s', {'name': args}])
self.incoming_section = False | As a Python code analyst, you investigate and solve complex coding mysteries |
def open(self, directory=None, filename=None, mode="rb"):
"""Opens a file for writing or reading."""
path = os.path.join(directory, filename)
return open(path, mode) | How would you code a function in Python 3 to
open a file for writing or reading. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _file_chunks(self, data, chunk_size):
""" Yield compressed chunks from a data array"""
for i in xrange(0, len(data), chunk_size):
yield self.compressor(data[i:i+chunk_size]) | Implement a Python 3 function for
yielding compressed chunks from a data array | You are a Python code analyst, evaluating scripts for potential improvements. |
Stream a large file into chunks and send them to Workbench | How would you explain what the following Python 3 function does
def stream_to_workbench(self, raw_bytes, filename, type_tag, tags):
md5_list = []
sent_bytes = 0
total_bytes = len(raw_bytes)
for chunk in self._file_chunks(raw_bytes, self.chunk_size):
md5_list.append(self.workb... | As a Python code composer, you craft elegant and concise scripts. |
def dumps(obj, **kwargs) -> str:
"""
Serialize a BioC ``obj`` to a JSON formatted ``str``.
"""
return json.dumps(obj, cls=BioCJSONEncoder, **kwargs) | How would you implement a function in Python 3 that
serializes a BioC object to a JSON formatted str. | You are a Python code analyst, evaluating scripts for potential improvements. |
def dump(obj, fp, **kwargs):
"""
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object)
"""
return json.dump(obj, fp, cls=BioCJSONEncoder, **kwargs) | How would you code a function in Python 3 to
serialize obj as a JSON formatted stream to fp. | You are a Python code architect, reviewing and designing scalable and efficient code |
Encode and write a single object. | Can you generate a brief explanation for the following Python 3 code
def write(self, obj: BioCDocument or BioCPassage or BioCSentence):
if self.level == DOCUMENT and not isinstance(obj, BioCDocument):
raise ValueError
if self.level == PASSAGE and not isinstance(obj, BioCPassage):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Execute the rekall adapter and return the output | Can you generate a brief explanation for the following Python 3 code
def execute(self, input_data):
''' Execute method '''
# Spin up the rekall adapter
adapter = RekallAdapter()
adapter.set_plugin_name(self.plugin_name)
rekall_output = adapter.execute(input_data)
# Proc... | As a Python code composer, you craft elegant and concise scripts. |
Execute the ViewMemoryDeep worker | Can you generate the documentation for the following Python 3 function
def execute(self, input_data):
''' Execute the ViewMemoryDeep worker '''
# Aggregate the output from all the memory workers, clearly this could be kewler
output = input_data['view_memory']
output['tables'] = {}
... | As a Python code composer, you craft elegant and concise scripts. |
Execute the ViewMemory worker | Here you have a function in Python 3, explain what it does
def execute(self, input_data):
''' Execute the ViewMemory worker '''
# Aggregate the output from all the memory workers into concise summary info
output = {'meta': input_data['mem_meta']['tables']['info']}
output['connscan'] = l... | As a python code expert, you are capable of creating scripts from specifications. |
def store(self, name, value, atype, new_name=None, multiplier=None, allowed_values=None):
''' store a config value in a dictionary, these values are used to populate a trasnfer spec
validation -- check type, check allowed values and rename if required '''
if value is not None:
_b... | Can you write a function in Python 3 where it
stores a config value in a dictionary | As a Python code translator, you convert algorithms and pseudocode into Python. |
convert the multi_session param a number | Given the following Python 3 function, write the documentation
def multi_session(self):
''' convert the multi_session param a number '''
_val = 0
if "multi_session" in self._dict:
_val = self._dict["multi_session"]
if str(_val).lower() == 'all':
_val = -1
... | You are a Python code generator, capable of creating scripts from specifications. |
def _raw_aspera_metadata(self, bucket):
''' get the Aspera connection details on Aspera enabled buckets '''
response = self._client.get_bucket_aspera(Bucket=bucket)
# Parse metadata from response
aspera_access_key = response['AccessKey']['Id']
aspera_secret_key = response['Acces... | How would you code a function in Python 3 to
get the Aspera connection details on Aspera enabled buckets | You are a Python code generator, capable of creating scripts from specifications. |
def _fetch_transfer_spec(self, node_action, token, bucket_name, paths):
''' make hhtp call to Aspera to fetch back trasnfer spec '''
aspera_access_key, aspera_secret_key, ats_endpoint = self._get_aspera_metadata(bucket_name)
_headers = {'accept': "application/json",
'Content... | How would you implement a function in Python 3 that
makes hhtp call to Aspera to fetch back trasnfer spec | You are a Python code architect, reviewing and designing scalable and efficient code |
def _create_transfer_spec(self, call_args):
''' pass the transfer details to aspera and receive back a
populated transfer spec complete with access token '''
_paths = []
for _file_pair in call_args.file_pair_list:
_path = OrderedDict()
if call_args.direction =... | Can you implement a function in Python 3 that
passes the transfer details to aspera and receive back a populated with access token | As a Python code composer, you craft elegant and concise scripts. |
def upload_directory(self, directory, bucket, key, transfer_config=None, subscribers=None):
''' upload a directory using Aspera '''
check_io_access(directory, os.R_OK)
return self._queue_task(bucket, [FilePair(key, directory)], transfer_config,
subscribers, enumAs... | Write a Python 3 function that can
upload a directory using Aspera | As a python code expert, you are capable of creating scripts from specifications. |
download a directory using Aspera | Here you have a function in Python 3, explain what it does
def download_directory(self, bucket, key, directory, transfer_config=None, subscribers=None):
''' download a directory using Aspera '''
check_io_access(directory, os.W_OK)
return self._queue_task(bucket, [FilePair(key, directory)], trans... | As a Python code composer, you craft elegant and concise scripts. |
def upload(self, fileobj, bucket, key, transfer_config=None, subscribers=None):
''' upload a file using Aspera '''
check_io_access(fileobj, os.R_OK, True)
return self._queue_task(bucket, [FilePair(key, fileobj)], transfer_config,
subscribers, enumAsperaDirection.S... | Can you write a function in Python 3 where it
uploads a file using Aspera | You are a Python code generator, capable of creating scripts from specifications. |
download a file using Aspera | How would you explain what the following Python 3 function does
def download(self, bucket, key, fileobj, transfer_config=None, subscribers=None):
''' download a file using Aspera '''
check_io_access(os.path.dirname(fileobj), os.W_OK)
return self._queue_task(bucket, [FilePair(key, fileobj)], tran... | As a Python code composer, you craft elegant and concise scripts. |
def set_log_details(aspera_log_path=None,
sdk_log_level=logging.NOTSET):
''' set the aspera log path - used by th Ascp process
set the internal aspera sdk activity - for debug purposes '''
if aspera_log_path:
check_io_access(aspera_log_path, os.W_OK)
... | Write a Python 3 function that can
set the log details for the current aspera process | You are a Python code architect, reviewing and designing scalable and efficient code |
def _validate_args(self, args):
''' validate the user arguments '''
assert(args.bucket)
if args.subscribers:
for _subscriber in args.subscribers:
assert(isinstance(_subscriber, AsperaBaseSubscriber))
if (args.transfer_config):
assert(isinstance(a... | How would you code a function in Python 3 to
validate the user arguments | As a python code expert, you are capable of creating scripts from specifications. |
Internal shutdown used by shutdown method above. | Given the following Python 3 function, write the documentation
def _shutdown(self, cancel, cancel_msg, exc_type=CancelledError):
''' Internal shutdown used by 'shutdown' method above '''
if cancel:
# Cancel all in-flight transfers if requested, before waiting
# for them to compl... | As a Python code analyst, you investigate and solve complex coding mysteries |
Stop backgroud thread and cleanup resources | Explain what the following Python 3 code does
def cleanup(self):
''' Stop backgroud thread and cleanup resources '''
self._processing_stop = True
self._wakeup_processing_thread()
self._processing_stopped_event.wait(3) | As a Python code composer, you craft elegant and concise scripts. |
count the number of cooridnators currently being processed and the number of ascps currently being used | Make a summary of the following Python 3 code
def tracked_coordinator_count(self, count_ascps=False):
''' count the number of cooridnators currently being processed
or count the number of ascps currently being used '''
with self._lock:
_count = 0
if count_ascps:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
add a transfer to waiting queue if possible then notify the background thread to process it | Can you generate a brief explanation for the following Python 3 code
def _queue_task(self, args):
''' add transfer to waiting queue if possible
then notify the background thread to process it '''
if self._cancel_called:
raise AsperaTransferQueueError("Cancel already called")
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def remove_aspera_coordinator(self, transfer_coordinator):
''' remove entry from the waiting waiting
or remove item from processig queue and add to processed quque
notify background thread as it may be able to process watiign requests
'''
# usually called on processing co... | Write a Python 3 script for
removing entry from waiting waiting or remove item from processig queue and add to processed quque notify background thread as it may be able to process watiign requests | You are a Python code analyst, evaluating scripts for potential improvements. |
def append_waiting_queue(self, transfer_coordinator):
''' append item to waiting queue '''
logger.debug("Add to waiting queue count=%d" % self.waiting_coordinator_count())
with self._lockw:
self._waiting_transfer_coordinators.append(transfer_coordinator) | Write a Python 3 function for
appending item to waiting queue | You are a Python code generator, capable of creating scripts from specifications. |
call the Aspera sdk to freeup resources | Can you generate the documentation for the following Python 3 function
def free_processed_queue(self):
''' call the Aspera sdk to freeup resources '''
with self._lock:
if len(self._processed_coordinators) > 0:
for _coordinator in self._processed_coordinators:
... | As a python code expert, you are capable of creating scripts from specifications. |
def is_stop(self):
''' has either of the stop processing flags been set '''
if len(self._processed_coordinators) > 0:
self.free_processed_queue()
return self._cancel_called or self._processing_stop | How would you code a function in Python 3 to
have either of the stop processing flags been set | You are a Python code analyst, evaluating scripts for potential improvements. |
thread to process the waiting queue
fetches transfer spec
then calls start transfer | How would you explain what the following Python 3 function does
def _process_waiting_queue(self):
''' thread to processes the waiting queue
fetches transfer spec
then calls start transfer
ensures that max ascp is not exceeded '''
logger.info("Queue processing thread s... | You are a Python code generator, capable of creating scripts from specifications. |
def clear_waiting_coordinators(self, cancel=False):
''' remove all entries from waiting queue or cancell all in waiting queue '''
with self._lockw:
if cancel:
for _coordinator in self._waiting_transfer_coordinators:
_coordinator.notify_cancelled("Clear Wai... | Write a Python 3 script to
remove all entries from waiting queue or cancell all in waiting queue | As a python code expert, you are capable of creating scripts from specifications. |
def cancel(self, *args, **kwargs):
""" Cancel all queue items - then attempt to cancel all in progress items """
self._cancel_called = True
self.clear_waiting_coordinators(cancel=True)
super(AsperaTransferCoordinatorController, self).cancel(*args, **kwargs) | Create a Python 3 function to
cancel all queue items - then attempt to cancel all in progress items - then attempt to cancel all in progress items - then clear waiting coordinator list | As a Python code translator, you convert algorithms and pseudocode into Python. |
Wait until all in progress and queued items are processed. | Can you generate a brief explanation for the following Python 3 code
def wait(self):
self._wait_called = True
while self.tracked_coordinator_count() > 0 or \
self.waiting_coordinator_count() > 0:
time.sleep(1)
super(AsperaTransferCoordinatorController, self).wait(... | You are a Python code generator, capable of creating scripts from specifications. |
Execute the ViewZip worker | Explain what the following Python 3 code does
def execute(self, input_data):
''' Execute the ViewZip worker '''
# Just a small check to make sure we haven't been called on the wrong file type
if (input_data['meta']['type_tag'] != 'zip'):
return {'error': self.__class__.__name__+': c... | You are a Python code generator, capable of creating scripts from specifications. |
Sets the exception on the future. | Make a summary of the following Python 3 code
def set_exception(self, exception):
if not self.is_done():
raise TransferNotDoneError(
'set_exception can only be called once the transfer is '
'complete.')
self._coordinator.set_exception(exception, override=True) | You are a Python code analyst, evaluating scripts for potential improvements. |
def start_transfer(self):
''' pass the transfer spec to the Aspera sdk and start the transfer '''
try:
if not self.is_done():
faspmanager2.startTransfer(self.get_transfer_id(),
None,
self.ge... | Create a Python 3 function to
pass the transfer spec to the Aspera sdk and start the transfer | You are a Python code architect, reviewing and designing scalable and efficient code |
def is_running(self, is_stopped):
''' check whether a transfer is currently running '''
if is_stopped and self.is_stopped():
return False
return faspmanager2.isRunning(self.get_transfer_id()) | How would you code a function in Python 3 to
check whether a transfer is currently running | As a python code expert, you are capable of creating scripts from specifications. |
check whether a transfer is being stopped | Explain what the following Python 3 code does
def is_stopped(self, is_stopping=True):
''' check whether a transfer is stopped or is being stopped '''
if is_stopping:
return self._is_stopped or self._is_stopping
return self._is_stopped | You are a Python code architect, reviewing and designing scalable and efficient code |
def _modify_transfer(self, option, value=0):
''' call Apsera sdk modify an in progress eg pause/resume
allowed values defined in enumAsperaModifyTransfer class '''
_ret = False
try:
if self.is_running(True):
logger.info("ModifyTransfer called %d = %d" % (o... | Can you write a function in Python 3 where it
modifies an in progress eg pause or resume | As a python code expert, you are capable of creating scripts from specifications. |
send a stop transfer request to the Aspera sdk | Explain what the following Python 3 code does
def stop(self, free_resource=False):
''' send a stop transfer request to the Aspera sdk, can be done for:
cancel - stop an in progress transfer
free_resource - request to the Aspera sdk free resouces related to trasnfer_id
'''
... | As a python code expert, you are capable of creating scripts from specifications. |
call stop to free up resources | Here you have a function in Python 3, explain what it does
def free_resources(self):
''' call stop to free up resources '''
if not self.is_stopped():
logger.info("Freeing resources: %s" % self.get_transfer_id())
self.stop(True) | As a python code expert, you are capable of creating scripts from specifications. |
def extract_message_value(self, name):
''' search message to find and extract a named value '''
name += ":"
assert(self._message)
_start = self._message.find(name)
if _start >= 0:
_start += len(name) + 1
_end = self._message.find("\n", _start)
... | Can you write a function in Python 3 where it
searches message to find and extract a named value | You are a Python code analyst, evaluating scripts for potential improvements. |
set status of the aspera controller | Make a summary of the following Python 3 code
def _set_status(self, status, ex=None):
''' set session status - eg failed, success --
valid values contained in enumAsperaControllerStatus class '''
self._status = status
logger.debug("Set status(%s) for %s" % (self._status, self.session... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set_bytes_transferred(self, bytes_transferred):
''' set the number of bytes transferred - if it has changed return True '''
_changed = False
if bytes_transferred:
_changed = (self._bytes_transferred != int(bytes_transferred))
if _changed:
self._bytes_t... | Implement a Python 3 function for
setting the number of bytes transferred - return True if it has changed return False | You are a Python code analyst, evaluating scripts for potential improvements. |
def set_exception(self, exception):
''' set the exception message and set the status to failed '''
logger.error("%s : %s" % (exception.__class__.__name__, str(exception)))
self._set_status(enumAsperaControllerStatus.FAILED, exception) | Create a Python 3 function to
set the exception message and set the status to failed | You are a Python code architect, reviewing and designing scalable and efficient code |
wait for the status and exception to be set | Given the following Python 3 function, write the documentation
def wait(self):
''' wait for the done event to be set - no timeout'''
self._done_event.wait(MAXINT)
return self._status, self._exception | As a python code expert, you are capable of creating scripts from specifications. |
def cancel(self, msg='', exc_type=CancelledError):
"""Cancels the TransferFuture
:param msg: The message to attach to the cancellation
:param exc_type: The type of exception to set for the cancellation
"""
_ret = False
if not self.is_done():
self.notify_... | How would you code a function in Python 3 to
cancel the TransferFuture :param msg: The message to attach to the cancellation :param exc_type: The type of exception to set for the cancellation | You are a Python code generator, capable of creating scripts from specifications. |
def _update_session_count(self, type=0, actutal_session_count=0):
''' update the session/ascp count
0 : set the number of sessions being used to 1 or number specified in transfer config
-1: decrement the session count by one
1: set the session count to param value
''... | Write a Python 3 script for
updating the session count based on the type of session | As a Python code composer, you craft elegant and concise scripts. |
def result(self, raise_exception=True):
"""Waits until TransferFuture is done and returns the result
If the TransferFuture succeeded, it will return the result. If the
TransferFuture failed, it will raise the exception associated to the
failure.
"""
_status = None
... | Write a Python 3 script for
waiting until the TransferFuture is done and returns the result. If the TransferFuture failed it will raise an exception associated to the exception associated to the exception. If the TransferFuture failed it will raise an exception associated to the exception. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.