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 check_args(args):
""" Parse arguments and check if the arguments are valid """ |
if not os.path.exists(args.fd):
print("Not a valid path", args.fd, file=ERROR_LOG)
return [], [], False
if args.fl is not None:
# we already ensure the file can be opened and opened the file
file_line = args.fl.readline()
amr_ids = file_line.strip().split()
elif args... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_csv(filename, csv_data, mode="w"):
""" Create a CSV file with the given data and store it in the file with the given name. :param filename: name of th... |
with open(filename, mode) as f:
csv_data.replace("_", r"\_")
f.write(csv_data) |
<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_metric_index(self, data_source):
""" This function will return the elasticsearch index for a corresponding data source. It chooses in between the default... |
if data_source in self.index_dict:
index = self.index_dict[data_source]
else:
index = self.class2index[self.ds2class[data_source]]
return Index(index_name=index) |
<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_sec_overview(self):
""" Generate the "overview" section of the report. """ |
logger.debug("Calculating Overview metrics.")
data_path = os.path.join(self.data_dir, "overview")
if not os.path.exists(data_path):
os.makedirs(data_path)
overview_config = {
"activity_metrics": [],
"author_metrics": [],
"bmi_metrics": ... |
<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_sec_project_activity(self):
""" Generate the "project activity" section of the report. """ |
logger.debug("Calculating Project Activity metrics.")
data_path = os.path.join(self.data_dir, "activity")
if not os.path.exists(data_path):
os.makedirs(data_path)
for ds in self.data_sources:
metric_file = self.ds2class[ds]
metric_index = self.get_... |
<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_sec_project_community(self):
""" Generate the "project community" section of the report. """ |
logger.debug("Calculating Project Community metrics.")
data_path = os.path.join(self.data_dir, "community")
if not os.path.exists(data_path):
os.makedirs(data_path)
project_community_config = {
"author_metrics": [],
"people_top_metrics": [],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_csv_fig_from_df(self, data_frames=[], filename=None, headers=[], index_label=None, fig_type=None, title=None, xlabel=None, ylabel=None, xfont=10, yfont... |
if not data_frames:
logger.error("No dataframes provided to create CSV")
sys.exit(1)
assert(len(data_frames) == len(headers))
dataframes = []
for index, df in enumerate(data_frames):
df = df.rename(columns={"value": headers[index].replace("_", "")})... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_tables(database):
'''Create all tables in the given database'''
logging.getLogger(__name__).debug("Creating missing database tables")
database.connect()
database.create_tables([User,
Group,
UserToGroup,
GroupT... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def populate_with_defaults():
'''Create user admin and grant him all permission
If the admin user already exists the function will simply return
'''
logging.getLogger(__name__).debug("Populating with default users")
if not User.select().where(User.name == 'admin').exists():
admin = User.cre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def init_db(dbURL, pwd_salt_size=None, pwd_rounds=None):
'''Initialize users database
initialize database and create necessary tables
to handle users oprations.
:param dbURL: database url, as described in :func:`init_proxy`
'''
if not dbURL:
dbURL = 'sqlite:///:memory:'
logging.get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize(s, replace_spaces=True):
"""Normalize non-ascii characters to their closest ascii counterparts """ |
whitelist = (' -' + string.ascii_letters + string.digits)
if type(s) == six.binary_type:
s = six.text_type(s, 'utf-8', 'ignore')
table = {}
for ch in [ch for ch in s if ch not in whitelist]:
if ch not in table:
try:
replacement = unicodedata.normalize('NFKD... |
<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_robot_variables():
"""Return list of Robot Framework -compatible cli-variables parsed from ROBOT_-prefixed environment variable """ |
prefix = 'ROBOT_'
variables = []
def safe_str(s):
if isinstance(s, six.text_type):
return s
else:
return six.text_type(s, 'utf-8', 'ignore')
for key in os.environ:
if key.startswith(prefix) and len(key) > len(prefix):
variables.append(safe_st... |
<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(self):
"""Initiate one-shot conversion. The current settings are used, with the exception of continuous mode.""" |
c = self.config
c &= (~MCP342x._continuous_mode_mask & 0x7f) # Force one-shot
c |= MCP342x._not_ready_mask # Convert
logger.debug('Convert ' + hex(self.address) + ' config: ' + bin(c))
self.bus.write_byte(self.address, c) |
<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_query_range(cls, date_field, start=None, end=None):
""" Create a filter dict with date_field from start to end dates. :param date_field: field with the... |
if not start and not end:
return ''
start_end = {}
if start:
start_end["gte"] = "%s" % start.isoformat()
if end:
start_end["lte"] = "%s" % end.isoformat()
query_range = {date_field: start_end}
return query_range |
<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_query_basic(cls, date_field=None, start=None, end=None, filters={}):
""" Create a es_dsl query object with the date range and filters. :param date_fiel... |
query_basic = Search()
query_filters = cls.__get_query_filters(filters)
for f in query_filters:
query_basic = query_basic.query(f)
query_filters_inverse = cls.__get_query_filters(filters, inverse=True)
# Here, don't forget the '~'. That is what makes this an invers... |
<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_query_agg_terms(cls, field, agg_id=None):
""" Create a es_dsl aggregation object based on a term. :param field: field to be used to aggregate :return: ... |
if not agg_id:
agg_id = cls.AGGREGATION_ID
query_agg = A("terms", field=field, size=cls.AGG_SIZE, order={"_count": "desc"})
return (agg_id, query_agg) |
<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_query_agg_max(cls, field, agg_id=None):
""" Create an es_dsl aggregation object for getting the max value of a field. :param field: field from which th... |
if not agg_id:
agg_id = cls.AGGREGATION_ID
query_agg = A("max", field=field)
return (agg_id, query_agg) |
<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_query_agg_avg(cls, field, agg_id=None):
""" Create an es_dsl aggregation object for getting the average value of a field. :param field: field from whic... |
if not agg_id:
agg_id = cls.AGGREGATION_ID
query_agg = A("avg", field=field)
return (agg_id, query_agg) |
<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_query_agg_cardinality(cls, field, agg_id=None):
""" Create an es_dsl aggregation object for getting the approximate count of distinct values of a field... |
if not agg_id:
agg_id = cls.AGGREGATION_ID
query_agg = A("cardinality", field=field, precision_threshold=cls.ES_PRECISION)
return (agg_id, query_agg) |
<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_bounds(cls, start=None, end=None):
""" Return a dict with the bounds for a date_histogram agg. :param start: date from for the date_histogram agg, shou... |
bounds = {}
if start or end:
# Extend bounds so we have data until start and end
start_ts = None
end_ts = None
if start:
# elasticsearch is unable to convert date with microseconds into long
# format for processing, hence w... |
<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_query_agg_ts(cls, field, time_field, interval=None, time_zone=None, start=None, end=None, agg_type='count', offset=None):
""" Create an es_dsl aggregat... |
""" Time series for an aggregation metric """
if not interval:
interval = '1M'
if not time_zone:
time_zone = 'UTC'
if not field:
field_agg = ''
else:
if agg_type == "cardinality":
agg_id, field_agg = cls.__get_quer... |
<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_count(cls, date_field=None, start=None, end=None, filters={}):
""" Build the DSL query for counting the number of items. :param date_field: field with th... |
""" Total number of items """
query_basic = cls.__get_query_basic(date_field=date_field,
start=start, end=end,
filters=filters)
# size=0 gives only the count and not the hits
query = query_basic.extr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_fields(self, fields, force_refetch=False):
""" Makes sure we fetched the fields, and populate them if not. """ |
# We fetched with fields=None, we should have fetched them all
if self._fetched_fields is None or self._initialized_with_doc:
return
if force_refetch:
missing_fields = fields
else:
missing_fields = [f for f in fields if f not in self._fetched_fields... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refetch_fields(self, missing_fields):
""" Refetches a list of fields from the DB """ |
db_fields = self.mongokat_collection.find_one({"_id": self["_id"]}, fields={k: 1 for k in missing_fields})
self._fetched_fields += tuple(missing_fields)
if not db_fields:
return
for k, v in db_fields.items():
self[k] = v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unset_fields(self, fields):
""" Removes this list of fields from both the local object and the DB. """ |
self.mongokat_collection.update_one({"_id": self["_id"]}, {"$unset": {
f: 1 for f in fields
}})
for f in fields:
if f in self:
del self[f] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_partial(self, data=None, allow_protected_fields=False, **kwargs):
""" Saves just the currently set fields in the database. """ |
# Backwards compat, deprecated argument
if "dotnotation" in kwargs:
del kwargs["dotnotation"]
if data is None:
data = dotdict(self)
if "_id" not in data:
raise KeyError("_id must be set in order to do a save_partial()")
del data... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_default_args(tool_name):
""" Read default argument values for a given tool :param tool_name: Name of the script to read the default arguments for :retur... |
global opinel_arg_dir
profile_name = 'default'
# h4ck to have an early read of the profile name
for i, arg in enumerate(sys.argv):
if arg == '--profile' and len(sys.argv) >= i + 1:
profile_name = sys.argv[i + 1]
#if not os.path.isdir(opinel_arg_dir):
# os.makedirs(op... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prompt(test_input = None):
""" Prompt function that works for Python2 and Python3 :param test_input: Value to be returned when testing :return: Value typed b... |
if test_input != None:
if type(test_input) == list and len(test_input):
choice = test_input.pop(0)
elif type(test_input) == list:
choice = ''
else:
choice = test_input
else:
# Coverage: 4 missed statements
try:
choice = raw... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prompt_4_mfa_code(activate = False, input = None):
""" Prompt for an MFA code :param activate: Set to true when prompting for the 2nd code when activating a ... |
while True:
if activate:
prompt_string = 'Enter the next value: '
else:
prompt_string = 'Enter your MFA code (or \'q\' to abort): '
mfa_code = prompt_4_value(prompt_string, no_confirm = True, input = input)
try:
if mfa_code == 'q':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prompt_4_mfa_serial(input = None):
""" Prompt for an MFA serial number :param input: Used for unit testing :return: The MFA serial number """ |
return prompt_4_value('Enter your MFA serial:', required = False, regex = re_mfa_serial_format, regex_format = mfa_serial_format, input = 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 prompt_4_overwrite(filename, force_write, input = None):
""" Prompt whether the file should be overwritten :param filename: Name of the file about to be writ... |
if not os.path.exists(filename) or force_write:
return True
return prompt_4_yes_no('File \'{}\' already exists. Do you want to overwrite it'.format(filename), input = 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 get_feed_renderer(engines, name):
""" From engine name, load the engine path and return the renderer class Raise 'FeedparserError' if any loading error """ |
if name not in engines:
raise FeedparserError("Given feed name '{}' does not exists in 'settings.FEED_RENDER_ENGINES'".format(name))
renderer = safe_import_module(engines[name])
return renderer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def clear_line(mode=2):
''' Clear the current line.
Arguments:
mode: | 0 | 'forward' | 'right' - Clear cursor to end of line.
| 1 | 'backward' | 'left' - Clear cursor to beginning of line.
| 2 | 'full' - Clear entire line.
Note:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def wait_key(keys=None):
''' Waits for a keypress at the console and returns it.
"Where's the any key?"
Arguments:
keys - if passed, wait for this specific key, e.g. ESC.
may be a tuple.
Returns:
char or ESC - depending on key hit.
None... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_region_list(service, chosen_regions = [], partition_name = 'aws'):
""" Build the list of target region names :param service: :param chosen_regions: :pa... |
service = 'ec2containerservice' if service == 'ecs' else service # Of course things aren't that easy...
# Get list of regions from botocore
regions = Session().get_available_regions(service, partition_name = partition_name)
if len(chosen_regions):
return list((Counter(regions) & Counter(chosen_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_service(service, credentials, region_name = None, config = None, silent = False):
""" Instantiates an AWS API client :param service: :param credentia... |
api_client = None
try:
client_params = {}
client_params['service_name'] = service.lower()
session_params = {}
session_params['aws_access_key_id'] = credentials['AccessKeyId']
session_params['aws_secret_access_key'] = credentials['SecretAccessKey']
session_params[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_truncated_response(callback, params, entities):
""" Handle truncated responses :param callback: :param params: :param entities: :return: """ |
results = {}
for entity in entities:
results[entity] = []
while True:
try:
marker_found = False
response = callback(**params)
for entity in entities:
if entity in response:
results[entity] = results[entity] + response[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 pdftojpg(filehandle, meta):
"""Converts a PDF to a JPG and places it back onto the FileStorage instance passed to it as a BytesIO object. Optional meta argum... |
resolution = meta.get('resolution', 300)
width = meta.get('width', 1080)
bgcolor = Color(meta.get('bgcolor', 'white'))
stream = BytesIO()
with Image(blob=filehandle.stream, resolution=resolution) as img:
img.background_color = bgcolor
img.alpha_channel = False
img.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 change_filename(filehandle, meta):
"""Changes the filename to reflect the conversion from PDF to JPG. This method will preserve the original filename in the ... |
filename = secure_filename(meta.get('filename', filehandle.filename))
basename, _ = os.path.splitext(filename)
meta['original_filename'] = filehandle.filename
filehandle.filename = filename + '.jpg'
return filehandle |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def pdf_saver(filehandle, *args, **kwargs):
"Uses werkzeug.FileStorage instance to save the converted image."
fullpath = get_save_path(filehandle.filename)
filehandle.save(fullpath, buffer_size=kwargs.get('buffer_size', 16384)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_data(data_file, key_name = None, local_file = False, format = 'json'):
""" Load a JSON data file :param data_file: :param key_name: :param local_file: :... |
if local_file:
if data_file.startswith('/'):
src_file = data_file
else:
src_dir = os.getcwd()
src_file = os.path.join(src_dir, data_file)
else:
src_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')
if not os.path.isdir(sr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_ip_ranges(filename, local_file = True, ip_only = False, conditions = []):
""" Returns the list of IP prefixes from an ip-ranges file :param filename: :p... |
targets = []
data = load_data(filename, local_file = local_file)
if 'source' in data:
# Filtered IP ranges
conditions = data['conditions']
local_file = data['local_file'] if 'local_file' in data else False
data = load_data(data['source'], local_file = local_file, key_name = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_app(self, app):
"""Configure a Flask application to use this ZODB extension.""" |
assert 'zodb' not in app.extensions, \
'app already initiated for zodb'
app.extensions['zodb'] = _ZODBState(self, app)
app.teardown_request(self.close_db) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close_db(self, exception):
"""Added as a `~flask.Flask.teardown_request` to applications to commit the transaction and disconnect ZODB if it was used during ... |
if self.is_connected:
if exception is None and not transaction.isDoomed():
transaction.commit()
else:
transaction.abort()
self.connection.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connection(self):
"""Request-bound database connection.""" |
assert flask.has_request_context(), \
'tried to connect zodb outside request'
if not self.is_connected:
connector = flask.current_app.extensions['zodb']
flask._request_ctx_stack.top.zodb_connection = connector.db.open()
transaction.begin()
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 add_user_to_group(iam_client, user, group, quiet = False):
""" Add an IAM user to an IAM group :param iam_client: :param group: :param user: :param user_info... |
if not quiet:
printInfo('Adding user to group %s...' % group)
iam_client.add_user_to_group(GroupName = group, UserName = user) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_virtual_mfa_device(iam_client, mfa_serial):
""" Delete a vritual MFA device given its serial number :param iam_client: :param mfa_serial: :return: """ |
try:
printInfo('Deleting MFA device %s...' % mfa_serial)
iam_client.delete_virtual_mfa_device(SerialNumber = mfa_serial)
except Exception as e:
printException(e)
printError('Failed to delete MFA device %s' % mfa_serial)
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 init_group_category_regex(category_groups, category_regex_args):
""" Initialize and compile regular expression for category groups :param category_regex_args... |
category_regex = []
authorized_empty_regex = 1
if len(category_regex_args) and len(category_groups) != len(category_regex_args):
printError('Error: you must provide as many regex as category groups.')
return None
for regex in category_regex_args:
if len(regex) < 1:
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 _get_extended_palette_entry(self, name, index, is_hex=False):
''' Compute extended entry, once on the fly. '''
values = None
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'extended' in self._palette_support: # build entry
if is_hex:
index = str(find_near... |
<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_true_palette_entry(self, name, digits):
''' Compute truecolor entry, once on the fly.
values must become sequence of decimal int strings: ('1', '2', '3')
'''
values = None
type_digits = type(digits)
is_fbterm = (env.TERM == 'fbterm') # sigh
if 'tru... |
<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_to_ansi_values(self, index):
''' Converts an palette index to the corresponding ANSI color.
Arguments:
index - an int (from 0-15)
Returns:
index as str in a list for compatibility with values.
'''
if self.__class__.__name__[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 _create_entry(self, name, values, fbterm=False):
''' Render first values as string and place as first code,
save, and return attr.
'''
if fbterm:
attr = _PaletteEntryFBTerm(self, name.upper(), ';'.join(values))
else:
attr = _PaletteEntry(self, name... |
<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, data):
''' This could be a bit less clumsy. '''
if data == '\n': # print does this
return self.stream.write(data)
else:
bytes_ = 0
for line in data.splitlines(True):
nl = ''
if line.endswith('\n'): # mv nl to 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 set_output(self, outfile):
''' Set's the output file, currently only useful with context-managers.
Note:
This function is experimental and may not last.
'''
if self._orig_stdout: # restore Usted
sys.stdout = self._orig_stdout
self._stream = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _render(self):
''' Standard rendering of bar graph. '''
cm_chars = self._comp_style(self.icons[_ic] * self._num_complete_chars)
em_chars = self._empt_style(self.icons[_ie] * self._num_empty_chars)
return f'{self._first}{cm_chars}{em_chars}{self._last} {self._lbl}' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _render_internal_label(self):
''' Render with a label inside the bar graph. '''
ncc = self._num_complete_chars
bar = self._lbl.center(self.iwidth)
cm_chars = self._comp_style(bar[:ncc])
em_chars = self._empt_style(bar[ncc:])
return f'{self._first}{cm_chars}{em_chars}{... |
<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_ncc(self, width, ratio):
''' Get the number of complete chars.
This one figures the remainder for the partial char as well.
'''
sub_chars = round(width * ratio * self.partial_chars_len)
ncc, self.remainder = divmod(sub_chars, self.partial_chars_len)
return n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _render(self):
''' figure partial character '''
p_char = ''
if not self.done and self.remainder:
p_style = self._comp_style
if self.partial_char_extra_style:
if p_style is str:
p_style = self.partial_char_extra_style
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def thread_work(targets, function, params = {}, num_threads = 0):
""" Generic multithreading helper :param targets: :param function: :param params: :param num_th... |
q = Queue(maxsize=0)
if not num_threads:
num_threads = len(targets)
for i in range(num_threads):
worker = Thread(target=function, args=(q, params))
worker.setDaemon(True)
worker.start()
for target in targets:
q.put(target)
q.join() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def threaded_per_region(q, params):
""" Helper for multithreading on a per-region basis :param q: :param params: :return: """ |
while True:
try:
params['region'] = q.get()
method = params['method']
method(params)
except Exception as e:
printException(e)
finally:
q.task_done() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def location(self, x=None, y=None):
''' Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!')
'''
stream = self._stream
stream.write(self.save_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 fullscreen(self):
''' Context Manager that enters full-screen mode and restores normal
mode on exit.
::
with screen.fullscreen():
print('Hello, world!')
'''
stream = self._stream
stream.write(self.alt_screen_enable)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hidden_cursor(self):
''' Context Manager that hides the cursor and restores it on exit.
::
with screen.hidden_cursor():
print('Clandestine activity…')
'''
stream = self._stream
stream.write(self.hide_cursor)
stream.flush()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def undecorated(o):
"""Remove all decorators from a function, method or class""" |
# class decorator
if type(o) is type:
return o
try:
# python2
closure = o.func_closure
except AttributeError:
pass
try:
# python3
closure = o.__closure__
except AttributeError:
return
if closure:
for cell in closure:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assume_role(role_name, credentials, role_arn, role_session_name, silent = False):
""" Assume role and save credentials :param role_name: :param credentials: ... |
external_id = credentials.pop('ExternalId') if 'ExternalId' in credentials else None
# Connect to STS
sts_client = connect_service('sts', credentials, silent = silent)
# Set required arguments for assume role call
sts_args = {
'RoleArn': role_arn,
'RoleSessionName': role_session_name
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_password(length=16):
""" Generate a password using random characters from uppercase, lowercase, digits, and symbols :param length: Length of the pas... |
chars = string.ascii_letters + string.digits + '!@#$%^&*()_+-=[]{};:,<.>?|'
modulus = len(chars)
pchars = os.urandom(16)
if type(pchars) == str:
return ''.join(chars[i % modulus] for i in map(ord, pchars))
else:
return ''.join(chars[i % modulus] for i in pchars) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_sts_session(profile_name, credentials, duration = 28800, session_name = None, save_creds = True):
""" Fetch STS credentials :param profile_name: :param ... |
# Set STS arguments
sts_args = {
'DurationSeconds': duration
}
# Prompt for MFA code if MFA serial present
if 'SerialNumber' in credentials and credentials['SerialNumber']:
if not credentials['TokenCode']:
credentials['TokenCode'] = prompt_4_mfa_code()
if cre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_creds_from_aws_credentials_file(profile_name, credentials_file = aws_credentials_file):
""" Read credentials from AWS config file :param profile_name: :... |
credentials = init_creds()
profile_found = False
try:
# Make sure the ~.aws folder exists
if not os.path.exists(aws_config_dir):
os.makedirs(aws_config_dir)
with open(credentials_file, 'rt') as cf:
for line in cf:
profile_line = re_profile_nam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_creds_from_csv(filename):
""" Read credentials from a CSV file :param filename: :return: """ |
key_id = None
secret = None
mfa_serial = None
secret_next = False
with open(filename, 'rt') as csvfile:
for i, line in enumerate(csvfile):
values = line.split(',')
for v in values:
if v.startswith('AKIA'):
key_id = v.strip()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_creds_from_environment_variables():
""" Read credentials from environment variables :return: """ |
creds = init_creds()
# Check environment variables
if 'AWS_ACCESS_KEY_ID' in os.environ and 'AWS_SECRET_ACCESS_KEY' in os.environ:
creds['AccessKeyId'] = os.environ['AWS_ACCESS_KEY_ID']
creds['SecretAccessKey'] = os.environ['AWS_SECRET_ACCESS_KEY']
if 'AWS_SESSION_TOKEN' in os.envir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_profile_from_environment_variables():
""" Read profiles from env :return: """ |
role_arn = os.environ.get('AWS_ROLE_ARN', None)
external_id = os.environ.get('AWS_EXTERNAL_ID', None)
return role_arn, external_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 read_profile_from_aws_config_file(profile_name, config_file = aws_config_file):
""" Read profiles from AWS config file :param profile_name: :param config_fil... |
role_arn = None
source_profile = 'default'
mfa_serial = None
profile_found = False
external_id = None
try:
with open(config_file, 'rt') as config:
for line in config:
profile_line = re_profile_name.match(line)
if profile_line:
... |
<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_creds_to_aws_credentials_file(profile_name, credentials, credentials_file = aws_credentials_file):
""" Write credentials to AWS config file :param prof... |
profile_found = False
profile_ever_found = False
session_token_written = False
security_token_written = False
mfa_serial_written = False
expiration_written = False
# Create the .aws folder if needed
if not os.path.isdir(aws_config_dir):
os.mkdir(aws_config_dir)
# Create an 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 complete_profile(f, credentials, session_token_written, mfa_serial_written):
""" Append session token and mfa serial if needed :param f: :param credentials: ... |
session_token = credentials['SessionToken'] if 'SessionToken' in credentials else None
mfa_serial = credentials['SerialNumber'] if 'SerialNumber' in credentials else None
if session_token and not session_token_written:
f.write('aws_session_token = %s\n' % session_token)
if mfa_serial and not mf... |
<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_stackset_ready_accounts(credentials, account_ids, quiet=True):
""" Verify which AWS accounts have been configured for CloudFormation stack set by attempt... |
api_client = connect_service('sts', credentials, silent=True)
configured_account_ids = []
for account_id in account_ids:
try:
role_arn = 'arn:aws:iam::%s:role/AWSCloudFormationStackSetExecutionRole' % account_id
api_client.assume_role(RoleArn=role_arn, RoleSessionName='opine... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, url):
""" Get the feed content using 'requests' """ |
try:
r = requests.get(url, timeout=self.timeout)
except requests.exceptions.Timeout:
if not self.safe:
raise
else:
return None
# Raise 404/500 error if any
if r and not self.safe:
r.raise_for_status... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, content):
""" Parse the fetched feed content Feedparser returned dict contain a 'bozo' key which can be '1' if the feed is malformed. Return None... |
if content is None:
return None
feed = feedparser.parse(content)
# When feed is malformed
if feed['bozo']:
# keep track of the parsing error exception but as string
# infos, not an exception object
exception_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 _hash_url(self, url):
""" Hash the URL to an md5sum. """ |
if isinstance(url, six.text_type):
url = url.encode('utf-8')
return hashlib.md5(url).hexdigest() |
<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(self, url, expiration):
""" Fetch the feed if no cache exist or if cache is stale """ |
# Hash url to have a shorter key and add it expiration time to avoid clash for
# other url usage with different expiration
cache_key = self.cache_key.format(**{
'id': self._hash_url(url),
'expire': str(expiration)
})
# Get feed from cache if any... |
<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_context(self, url, expiration):
""" Build template context with formatted feed content """ |
self._feed = self.get(url, expiration)
return {
self.feed_context_name: self.format_feed_content(self._feed),
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, url, template=None, expiration=0):
""" Render feed template """ |
template = template or self.default_template
return render_to_string(template, self.get_context(url, expiration)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def is_ansi_capable():
''' Check to see whether this version of Windows is recent enough to
support "ANSI VT"" processing.
'''
BUILD_ANSI_AVAIL = 10586 # Win10 TH2
CURRENT_VERS = sys.getwindowsversion()[:3]
if CURRENT_VERS[2] > BUILD_ANSI_AVAIL:
result = True
else:
resu... |
<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_color(name, stream=STD_OUTPUT_HANDLE):
''' Returns current colors of console.
https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo
Arguments:
name: one of ('background', 'bg', 'foreground', 'fg')
stream: Handle to stdout, stderr, etc.
... |
<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_position(stream=STD_OUTPUT_HANDLE):
''' Returns current position of cursor, starts at 1. '''
stream = kernel32.GetStdHandle(stream)
csbi = CONSOLE_SCREEN_BUFFER_INFO()
kernel32.GetConsoleScreenBufferInfo(stream, byref(csbi))
pos = csbi.dwCursorPosition
# zero based, add ones for compati... |
<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_position(x, y, stream=STD_OUTPUT_HANDLE):
''' Sets current position of the cursor. '''
stream = kernel32.GetStdHandle(stream)
value = x + (y << 16)
kernel32.SetConsoleCursorPosition(stream, c_long(value)) |
<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_title():
''' Returns console title string.
https://docs.microsoft.com/en-us/windows/console/getconsoletitle
'''
MAX_LEN = 256
buffer_ = create_unicode_buffer(MAX_LEN)
kernel32.GetConsoleTitleW(buffer_, MAX_LEN)
log.debug('%s', buffer_.value)
return buffer_.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_header(self):
"""Read the header of a MPQ archive.""" |
def read_mpq_header(offset=None):
if offset:
self.file.seek(offset)
data = self.file.read(32)
header = MPQFileHeader._make(
struct.unpack(MPQFileHeader.struct_format, data))
header = header._asdict()
if header['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 read_table(self, table_type):
"""Read either the hash or block table of a MPQ archive.""" |
if table_type == 'hash':
entry_class = MPQHashTableEntry
elif table_type == 'block':
entry_class = MPQBlockTableEntry
else:
raise ValueError("Invalid table type.")
table_offset = self.header['%s_table_offset' % table_type]
table_entries = se... |
<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_hash_table_entry(self, filename):
"""Get the hash table entry corresponding to a given filename.""" |
hash_a = self._hash(filename, 'HASH_A')
hash_b = self._hash(filename, 'HASH_B')
for entry in self.hash_table:
if (entry.hash_a == hash_a and entry.hash_b == hash_b):
return entry |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_file(self, filename, force_decompress=False):
"""Read a file from the MPQ archive.""" |
def decompress(data):
"""Read the compression type and decompress file data."""
compression_type = ord(data[0:1])
if compression_type == 0:
return data
elif compression_type == 2:
return zlib.decompress(data[1:], 15)
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 extract(self):
"""Extract all the files inside the MPQ archive in memory.""" |
if self.files:
return dict((f, self.read_file(f)) for f in self.files)
else:
raise RuntimeError("Can't extract whole archive without listfile.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_to_disk(self):
"""Extract all files and write them to disk.""" |
archive_name, extension = os.path.splitext(os.path.basename(self.file.name))
if not os.path.isdir(os.path.join(os.getcwd(), archive_name)):
os.mkdir(archive_name)
os.chdir(archive_name)
for filename, data in self.extract().items():
f = open(filename, 'wb')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_files(self, *filenames):
"""Extract given files from the archive to disk.""" |
for filename in filenames:
data = self.read_file(filename)
f = open(filename, 'wb')
f.write(data or b'')
f.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _hash(self, string, hash_type):
"""Hash a string using MPQ's hash function.""" |
hash_types = {
'TABLE_OFFSET': 0,
'HASH_A': 1,
'HASH_B': 2,
'TABLE': 3
}
seed1 = 0x7FED7FED
seed2 = 0xEEEEEEEE
for ch in string.upper():
if not isinstance(ch, int): ch = ord(ch)
value = self.encryption_tabl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decrypt(self, data, key):
"""Decrypt hash or block table or a sector.""" |
seed1 = key
seed2 = 0xEEEEEEEE
result = BytesIO()
for i in range(len(data) // 4):
seed2 += self.encryption_table[0x400 + (seed1 & 0xFF)]
seed2 &= 0xFFFFFFFF
value = struct.unpack("<I", data[i*4:i*4+4])[0]
value = (value ^ (seed1 + seed2))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_encryption_table():
"""Prepare encryption table for MPQ hash function.""" |
seed = 0x00100001
crypt_table = {}
for i in range(256):
index = i
for j in range(5):
seed = (seed * 125 + 3) % 0x2AAAAB
temp1 = (seed & 0xFFFF) << 0x10
seed = (seed * 125 + 3) % 0x2AAAAB
temp2 = (seed & 0x... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def key_for_request(self, method, url, **kwargs):
""" Return a cache key from a given set of request parameters. Default behavior is to return a complete URL for... |
if method != 'get':
return None
return requests.Request(url=url, params=kwargs.get('params', {})).prepare().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 request(self, method, url, **kwargs):
""" Override, wraps Session.request in caching. Cache is only used if key_for_request returns a valid key and should_ca... |
# short circuit if cache isn't configured
if not self.cache_storage:
resp = super(CachingSession, self).request(method, url, **kwargs)
resp.fromcache = False
return resp
resp = None
method = method.lower()
request_key = self.key_for_request(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_destination_callable(dest):
"""Creates a callable out of the destination. If it's already callable, the destination is returned. Instead, if the object... |
if callable(dest):
return dest
elif hasattr(dest, 'write') or isinstance(dest, string_types):
return _use_filehandle_to_save(dest)
else:
raise TypeError("Destination must be a string, writable or callable object.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate(self, filehandle, metadata, catch_all_errors=False):
"""Runs all attached validators on the provided filehandle. In the base implmentation of Trans... |
errors = []
DEFAULT_ERROR_MSG = '{0!r}({1!r}, {2!r}) returned False'
for validator in self._validators:
try:
if not validator(filehandle, metadata):
msg = DEFAULT_ERROR_MSG.format(validator, filehandle, metadata)
raise UploadE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.