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 serialize(self, serialize_cell=None):
"""Returns a list of all rows, with serialize_cell or self.get_cell_value called on the cells of each. """ |
if serialize_cell is None:
serialize_cell = self.get_cell_value
return [[serialize_cell(cell) for cell in row] for row in self.rows] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def headers(self, serialize_cell=None):
"""Gets the first row of the data table, with serialize_cell or self.get_cell_value is called on each cell.""" |
if serialize_cell is None:
serialize_cell = self.get_cell_value
return [serialize_cell(cell) for cell in self.rows[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 trim_empty_rows(self):
"""Remove all trailing empty rows.""" |
if self.nrows != 0:
row_index = 0
for row_index, row in enumerate(reversed(self.rows)):
if not self.is_row_empty(row):
break
self.nrows = len(self.rows) - row_index
self.rows = self.rows[:self.nrows]
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trim_empty_columns(self):
"""Removes all trailing empty columns.""" |
if self.nrows != 0 and self.ncols != 0:
last_col = -1
for row in self.rows:
for i in range(last_col + 1, len(row)):
if not self.is_cell_empty(row[i]):
last_col = i
ncols = last_col + 1
self.rows = [row[:ncols] for row in self.rows]
self.ncols = ncols
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_values(self):
"""Cleans the values in each cell. Calls either the user provided clean_value, or the class defined clean value. """ |
for row in self.rows:
for index, cell in enumerate(row):
self.set_cell_value(row, index, self.clean_value(self.get_cell_value(cell)))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_value(self, value):
"""Cleans a value, using either the user provided clean_value, or cls.reduce_value.""" |
if self._clean_value:
return self._clean_value(value)
else:
return self.reduce_value(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 reduce_value(cls, value):
"""Cleans the value by either compressing it if it is a string, or reducing it if it is a number. """ |
if isinstance(value, str):
return to_compressed_string(value)
elif isinstance(value, bool):
return value
elif isinstance(value, Number):
return reduce_number(value)
else:
return 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 about_time(fn=None, it=None):
"""Measures the execution time of a block of code, and even counts iterations and the throughput of them, always with a beautif... |
# has to be here to be mockable.
if sys.version_info >= (3, 3):
timer = time.perf_counter
else: # pragma: no cover
timer = time.time
@contextmanager
def context():
timings[0] = timer()
yield handle
timings[1] = timer()
timings = [0.0, 0.0]
handle ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def method(value, arg):
"""Method attempts to see if the value has a specified method. Usage: {% load custom_filters %} {% if foo|method:"has_access" %} """ |
if hasattr(value, str(arg)):
return getattr(value, str(arg))
return "[%s has no method %s]" % (value, arg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setLevel(self, level):
""" Changement du niveau du Log """ |
if isinstance(level, int):
self.logger.setLevel(level)
return
# level en tant que string
level = level.lower()
if level == "debug":
self.logger.setLevel(logging.DEBUG)
elif level == "info":
self.logger.setLevel(logging.INFO)
elif level == "warning" or level == "warning":
self.logger.setLe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info(self, text):
""" Ajout d'un message de log de type INFO """ |
self.logger.info("{}{}".format(self.message_prefix, text)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debug(self, text):
""" Ajout d'un message de log de type DEBUG """ |
self.logger.debug("{}{}".format(self.message_prefix, text)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error(self, text):
""" Ajout d'un message de log de type ERROR """ |
self.logger.error("{}{}".format(self.message_prefix, text)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" Fonctionnement du thread """ |
if self.debug:
print("Starting " + self.name)
# Lancement du programme du thread
if isinstance(self.function, str):
globals()[self.function](*self.args, **self.kwargs)
else:
self.function(*self.args, **self.kwargs)
if self.debug:
print("Exiting " + 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 convert(self, date_from=None, date_format=None):
""" Retourne la date courante ou depuis l'argument au format datetime :param: :date_from date de référ... |
try:
if date_format is None:
# on détermine la date avec dateutil
return dateutil.parser.parse(date_from)
# il y a un format de date prédéfini
return datetime.strptime(date_from, date_format)
except:
# échec, on prend la date courante
return datetime.now() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yesterday(self, date_from=None, date_format=None):
""" Retourne la date d'hier depuis maintenant ou depuis une date fournie :param: :date_from date de ... |
# date d'hier
return self.delta(date_from=date_from, date_format=date_format, days=-1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tomorrow(self, date_from=None, date_format=None):
""" Retourne la date de demain depuis maintenant ou depuis une date fournie :param: :date_from date d... |
# date de demain
return self.delta(date_from=date_from, date_format=date_format, days=1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fire(self, *args, **kargs):
""" collects results of all executed handlers """ |
self._time_secs_old = time.time()
# allow register/unregister while execution
# (a shallowcopy should be okay.. https://docs.python.org/2/library/copy.html )
with self._hlock:
handler_list = copy.copy(self._handler_list)
result_list = []
for handler in handl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _execute(self, handler, *args, **kwargs):
""" executes one callback function """ |
# difference to Axel Events: we don't use a timeout and execute all handlers in same thread
# FIXME: =>possible problem:
# blocking of event firing when user gives a long- or infinitly-running callback function
# (in Python it doesn't seem possible to forcefully ki... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bridge(filename):
""" Add hash to filename for cache invalidation. Uses gulp-buster for cache invalidation. Adds current file hash as url arg. """ |
if not hasattr(settings, 'BASE_DIR'):
raise Exception("You must provide BASE_DIR in settings for bridge")
file_path = getattr(settings, 'BUSTERS_FILE', os.path.join('static',
'busters.json'))
buster_file = os.path.join(settings.BASE_DIR... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calibrate(filename):
""" Append the calibration parameters as variables of the netcdf file. Keyword arguments: filename -- the name of a netcdf file. """ |
params = calibration_to(filename)
with nc.loader(filename) as root:
for key, value in params.items():
nc.getdim(root, 'xc_1', 1)
nc.getdim(root, 'yc_1', 1)
if isinstance(value, list):
for i in range(len(value)):
nc.getvar(root, '%s... |
<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_yaml(file_path, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
'''Read YAML file and return as python dictionary'''
# http://stackoverflow.com/a/21912744/943773
class OrderedLoader(Loader):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
ret... |
<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_yaml(data, out_path, Dumper=yaml.Dumper, **kwds):
'''Write python dictionary to YAML'''
import errno
import os
class OrderedDumper(Dumper):
pass
def _dict_representer(dumper, data):
return dumper.represent_mapping(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG... |
<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_grouping(state_collection, grouping_name, loaded_processes, overriding_parameters=None):
""" Adds a grouping to a state collection by using the process s... |
if (
grouping_name not in state_collection.groupings and
loaded_processes != None and
loaded_processes["grouping_selector"].get(grouping_name) != None
):
state_collection = loaded_processes["grouping_selector"][grouping_name].process_function(state_collection,overriding_paramete... |
<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_group_to_grouping(state_collection, grouping_name, group, group_key=None):
""" Adds a group to the named grouping, with a given group key If no group key... |
if state_collection.groupings.get(grouping_name) is None:
state_collection.groupings[grouping_name]= {}
if group_key is None:
group_key= _next_lowest_integer(state_collection.groupings[grouping_name].keys())
state_collection.groupings[grouping_name][group_key]= group
return state_collec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _combined_grouping_values(grouping_name,collection_a,collection_b):
""" returns a dict with values from both collections for a given grouping name Warning: c... |
new_grouping= collection_a.groupings.get(grouping_name,{}).copy()
new_grouping.update(collection_b.groupings.get(grouping_name,{}))
return new_grouping |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _next_lowest_integer(group_keys):
""" returns the lowest available integer in a set of dict keys """ |
try: #TODO Replace with max default value when dropping compatibility with Python < 3.4
largest_int= max([ int(val) for val in group_keys if _is_int(val)])
except:
largest_int= 0
return largest_int + 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def grant_user_access( self, uid, rid, expire_datetime = None, send_email=False ):
'''
Takes a user id and resource id and records a grant of access to that reseource for the user.
If no expire_date is set, we'll default to 24 hours.
If send_email is set to True, Tinypass wil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def revoke_user_access( self, access_id ):
'''
Takes an access_id, probably obtained from the get_access_list structure, and revokes that access.
No return value, but may raise ValueError.
'''
path = "/api/v3/publisher/user/access/revoke"
data = {
'a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self):
""" Process the warnings. """ |
for filename, warnings in self.warnings.iteritems():
self.fileCounts[filename] = {}
fc = self.fileCounts[filename]
fc["warning_count"] = len(warnings)
fc["warning_breakdown"] = self._warnCount(warnings)
self.warningCounts = self._warnCount(warnings,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deliverTextResults(self):
""" Deliver the results in a pretty text output. @return: Pretty text output! """ |
output = "=======================\ntxctools Hotspot Report\n"\
"=======================\n\n"
fileResults = sorted(self.fileCounts.items(),
key=lambda x: x[1]["warning_count"], reverse=True)
output += "Warnings per File\n=================\n"
count = 0
for ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _warnCount(self, warnings, warningCount=None):
""" Calculate the count of each warning, being given a list of them. @param warnings: L{list} of L{dict}s that... |
if not warningCount:
warningCount = {}
for warning in warnings:
wID = warning["warning_id"]
if not warningCount.get(wID):
warningCount[wID] = {}
warningCount[wID]["count"] = 1
warningCount[wID]["message"] = warning.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 list_(self):
""" Gets a list of channels on the server. """ |
with self.lock:
self.send('LIST')
list_ = {}
while self.readable():
msg = self._recv(expected_replies=('322', '321', '323'))
if msg[0] == '322':
channel, usercount, modes, topic = msg[2].split(' ', 3)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def servers_with_roles(self, roles, env=None, match_all=False):
""" Get servers with the given roles. If env is given, then the environment must match as well. I... |
result = []
roles = set(roles)
for instance in self.server_details():
instroles = set(instance['roles'])
envmatches = (env is None) or (instance['environment'] == env)
if envmatches and match_all and roles <= instroles:
result.append(instance)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ips_with_roles(self, roles, env=None, match_all=False):
""" Returns a function that, when called, gets servers with the given roles. If env is given, then th... |
def func():
return [s['external_ip'] for s in self.servers_with_roles(roles, env, match_all)]
return func |
<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(spellchecker_cache_path):
"""Create a Dictionary at spellchecker_cache_path with valid words.""" |
user_dictionary = os.path.join(os.getcwd(), "DICTIONARY")
user_words = read_dictionary_file(user_dictionary)
valid_words = Dictionary(valid_words_set(user_dictionary, user_words),
"valid_words",
[user_dictionary],
spell... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_event(self, event):
"""Apply an event to the snapshot instance """ |
if not isinstance(event, KindleEvent):
pass
elif isinstance(event, AddEvent):
self._data[event.asin] = BookSnapshot(event.asin)
elif isinstance(event, SetReadingEvent):
self._data[event.asin].status = ReadingStatus.CURRENT
self._data[event.asin].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 calc_update_events(self, asin_to_progress):
"""Calculate and return an iterable of `KindleEvent`s which, when applied to the current snapshot, result in the ... |
new_events = []
for asin, new_progress in asin_to_progress.iteritems():
try:
book_snapshot = self.get_book(asin)
except KeyError:
new_events.append(AddEvent(asin))
else:
if book_snapshot.status == ReadingStatus.CURRENT:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reset(self):
""" Rebuilds structure for AST and resets internal data. """ |
self._filename = None
self._block_map = {}
self._ast = []
self._ast.append(None) # header
self._ast.append([]) # options list
self._ast.append([]) |
<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_token(self, regex=None):
""" Consumes the next token in the token stream. `regex` Validate against the specified `re.compile()` regex instance. Returns ... |
item = self._lexer.get_token()
if not item:
raise ParseError(u'Unexpected end of file')
else:
line_no, token = item
if regex and not regex.match(token):
pattern = u"Unexpected format in token '{0}' on line {1}"
token_val = co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _lookahead_token(self, count=1):
""" Peeks into the token stream up to the specified number of tokens without consuming any tokens from the stream. ``count``... |
stack = []
next_token = None
# fetch the specified number of tokens ahead in stream
while count > 0:
item = self._lexer.get_token()
if not item:
break
stack.append(item)
count -= 1
# store the latest token and pu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _expect_token(self, expected):
""" Compares the next token in the stream to the specified token. `expected` Expected token string to match. * Raises a ``Pars... |
item = self._lexer.get_token()
if not item:
raise ParseError(u'Unexpected end of file')
else:
line_no, token = item
if token != expected:
raise ParseError(u"Unexpected token '{0}', "
u"expecting '{1}' on line {2}"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _expect_empty(self):
""" Checks if the token stream is empty. * Raises a ``ParseError` exception if a token is found. """ |
item = self._lexer.get_token()
if item:
line_no, token = item
raise ParseError(u"Unexpected token '{0}' on line {1}"
.format(common.from_utf8(token.strip()), line_no)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readstream(self, stream):
""" Reads the specified stream and parses the token elements generated from tokenizing the input data. `stream` ``File``-like objec... |
self._reset()
try:
# tokenize input stream
self._lexer = SettingLexer()
self._lexer.readstream(stream)
# parse tokens into AST
self._parse()
return True
except IOError:
self._reset()
return False |
<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, filename, header=None):
""" Writes the AST as a configuration file. `filename` Filename to save configuration file to. `header` Header string to ... |
origfile = self._filename
try:
with open(filename, 'w') as _file:
self.writestream(_file, header)
self._filename = filename
return True
except IOError:
self._filename = origfile
return False |
<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_option(self, block, name, *values):
""" Adds an option to the AST, either as a non-block option or for an existing block. `block` Block name. Set to ``No... |
if not self.RE_NAME.match(name):
raise ValueError(u"Invalid option name '{0}'"
.format(common.from_utf8(name)))
if not values:
raise ValueError(u"Must provide a value")
else:
values = list(values)
if block:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_option(self, block, name):
""" Removes first matching option that exists from the AST. `block` Block name. Set to ``None`` for non-block option. `name... |
if block:
# block doesn't exist
if not self._ast or not block in self._block_map:
raise ValueError(u"Block '{0}' does not exist"
.format(common.from_utf8(block)))
# lookup block index and remove
block_idx = self.... |
<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_block(self, name):
""" Adds a new block to the AST. `name` Block name. * Raises a ``ValueError`` exception if `name` is invalid or an existing block name... |
if not self.RE_NAME.match(name):
raise ValueError(u"Invalid block name '{0}'"
.format(common.from_utf8(name)))
if name in self._block_map:
raise ValueError(u"Block '{0}' already exists"
.format(common.from_utf8(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 remove_block(self, name):
""" Removes an existing block from the AST. `name` Block name. * Raises a ``ValueError`` exception if `name` hasn't been added. """ |
if not self._ast or not name in self._block_map:
raise ValueError(u"Block '{0}' does not exist"
.format(common.from_utf8(name)))
block_idx = self._block_map[name]
# remove block
self._ast[2].pop(block_idx)
del self._block_map[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(db_url, alembic_ini=None, debug=False, create=False):
""" Create the tables in the database using the information from the url obtained. :arg db_url, UR... |
engine = create_engine(db_url, echo=debug)
if create:
BASE.metadata.create_all(engine)
# This... "causes problems"
#if db_url.startswith('sqlite:'):
# def _fk_pragma_on_connect(dbapi_con, con_record):
# dbapi_con.execute('pragma foreign_keys=ON')
# sa.event.listen(eng... |
<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_producer(*args, **kwargs):
""" Returns a random hash for a confirmation secret. """ |
return hashlib.md5(six.text_type(uuid.uuid4()).encode('utf-8')).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 validate_code_path(valid_paths, code_path, **kw):
""" Raise an exception if code_path is not one of our whitelisted valid_paths. """ |
root, name = code_path.split(':', 1)
if name not in valid_paths[root]:
raise ValueError("%r is not a valid code_path" % code_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hlp_source_under(folder):
""" this function finds all the python packages under a folder and write the 'packages' and 'package_dir' entries for a python setu... |
# walk the folder and find the __init__.py entries for packages.
packages = []
package_dir = dict()
for root, dirs, files in os.walk(folder):
for file in files:
if file != '__init__.py':
continue
full = os.path.dirname(os.path.join(root, file))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show(self):
"""This could use some love, it's currently here as reference""" |
for entry in self._entries:
print "{'%s': %s, 'records': %s}" % (
entry._record_type, entry.host, entry.records)
print |
<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_record(self, record):
"""Add or update a given DNS record""" |
rec = self.get_record(record._record_type, record.host)
if rec:
rec = record
for i,r in enumerate(self._entries):
if r._record_type == record._record_type \
and r.host == record.host:
self._entries[i] = record
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diff_record(self, record):
"""Return the removed and added diffs""" |
rec = self.get_record(record._record_type, record.host)
if rec is not None and record is not None:
return {'removed': tuple(set(rec.results) - set(record.results)),
'added': tuple(set(record.results) - set(rec.recults))}
else:
return False |
<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_record(self, dns_record_type, host):
"""Fetch a DNS record""" |
record_list = self._entries
for record in record_list:
if record._record_type == dns_record_type \
and record.host == host:
return record
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_record(self, dns_record_type, host):
"""Remove a DNS record""" |
rec = self.get_record(dns_record_type, host)
if rec:
self._entries = list(set(self._entries) - set([rec]))
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config(self):
"""Create the finalized configuration""" |
root = etree.Element("xml")
resource_records = etree.SubElement(root, "resource_records")
# Append SOA and NS records
resource_records.append(SOARecord()._etree)
resource_records.append(NSRecord()._etree)
# Append the rest
for record in self._entries:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def parsePortSpec(spec, separator='-'):
'''
Parses a port specification in two forms into the same form.
In the first form the specification is just an integer. In this case a
tuple is returned containing the same integer twice.
In the second form the specification is two numbers separated by a hy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dump(self, msg):
'''
Dumps the provided message to this dump.
'''
msg_size = len(msg)
# We start a new batch if the resulting batch file is larger than the
# max batch file size. However, if the current batch file size is zero
# then that means the message al... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def api_server(connection, server_class):
""" Establishes an API Server on the supplied connection Arguments: - connection (xbahn.connection.Connection) - server... |
# run api server on connection
return server_class(
link=xbahn.connection.link.Link(
# use the connection to receive messages
receive=connection,
# use the connection to respond to received messages
respond=connection
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_nodes(search="unsigned"):
""" List all connected nodes """ |
nodes = nago.core.get_nodes()
if search == "all":
return map(lambda x: {x[0]: x[1].data}, nodes.items())
elif search == 'unsigned':
result = {}
for token, node in nodes.items():
if node.get('access') is None:
result[token] = node.data
return resul... |
<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(node_name, **kwargs):
""" Create a new node and generate a token for it """ |
result = {}
kwargs = kwargs.copy()
overwrite = kwargs.pop('overwrite', False)
node = nago.core.get_node(node_name)
if not node:
node = nago.core.Node()
elif not overwrite:
result['status'] = 'error'
result['message'] = "node %s already exists. add argument overwrite=1 to... |
<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(node_name):
""" Delete a specific node """ |
result = {}
node = nago.core.get_node(node_name)
if not node:
result['status'] = 'error'
result['message'] = "node not found."
else:
node.delete()
result['status'] = 'success'
result['message'] = 'node deleted.'
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sign(node=None):
""" Sign a specific node to grant it access you can specify "all" to sign all nodes returns the nodes that were signed """ |
if not node:
raise Exception("Specify either 'all' your specify token/host_name of node to sign. ")
if node == 'all':
node = 'unsigned'
nodes = list_nodes(search=node)
result = {}
for token, i in nodes.items():
i['access'] = 'node'
i.save()
result[token] = 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 set_attribute(token_or_hostname, **kwargs):
""" Change the attributes of a connected node """ |
node = nago.core.get_node(token_or_hostname) or {}
if not kwargs:
return "No changes made"
for k, v in kwargs.items():
node[k] = v
node.save()
return "Saved %s changes" % len(kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ping(token_or_hostname=None):
""" Send an echo request to a nago host. Arguments: token_or_host_name -- The remote node to ping If node is not provided, simp... |
if not token_or_hostname:
return "Pong!"
node = nago.core.get_node(token_or_hostname)
if not node and token_or_hostname in ('master', 'server'):
token_or_hostname = nago.settings.get_option('server')
node = nago.core.get_node(token_or_hostname)
if not node:
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(remote_host):
""" Connect to remote host and show our status """ |
if remote_host in ('master', 'server'):
remote_host = nago.settings.get_option('server')
node = nago.core.get_node(remote_host)
if not node:
try:
address = socket.gethostbyname(remote_host)
node = nago.core.Node()
node['host_name'] = remote_host
... |
<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_environ(inherit=True, append={}):
""" Helper method for passing environment variables to the subprocess. """ |
_environ = {} if not inherit else environ
for k,v in append.iteritems():
_environ[k] = v
return _environ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _colorize(self, msg, color=None, encode=False):
""" Colorize a string. """ |
# Valid colors
colors = {
'red': '31',
'green': '32',
'yellow': '33'
}
# No color specified or unsupported color
if not color or not color in colors:
return msg
# The colorized string
... |
<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_running(self):
""" Check if the service is running. """ |
try:
kill(int(self.pid.get()), 0)
return True
# Process not running, remove PID/lock file if it exists
except:
self.pid.remove()
self.lock.remove()
return False |
<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):
""" Set the output for the service command. """ |
if not self.output:
return open(devnull, 'w')
# Get the output file path
output_dir = dirname(self.output)
# Make the path exists
if not isdir(output_dir):
try:
makedirs(output_dir)
except Exception as 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 do_status(self):
""" Get the status of the service. """ |
# Get the PID of the service
pid = self.pid.get()
# Status color / attributes
status_color = 'green' if pid else 'red'
status_dot = self._colorize(UNICODE['dot'], status_color, encode=True)
# Active text
active_txt = {
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interface(self):
""" Public method for handling service command argument. """ |
# Possible control arguments
controls = {
'start': self.do_start,
'stop': self.do_stop,
'status': self.do_status,
'restart': self.do_restart,
'reload': self.do_restart
}
# Process the control argument
... |
<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_cell(self, cell, coords, cell_mode=CellMode.cooked):
"""Tries to convert the value first to an int, then a float and if neither is successful it return... |
try:
return int(cell)
except ValueError:
pass
try:
return float(cell)
except ValueError:
pass
# TODO Check for dates?
return cell |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterate_sheets(self, *args, **kwargs):
"""Opens self.filename and reads it with a csv reader. If self.filename ends with .gz, the file will be decompressed w... |
if isinstance(self.filename, str):
if self.filename.endswith(".gz") or self.is_gzipped:
with gzip.open(self.filename, "rt") as rfile:
reader = csv.reader(rfile, *args, **kwargs)
yield list(reader)
else:
with open(self.filename, "r") as rfile:
reader = csv.r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def time_methods(obj, methods, prefix=None):
""" Patch obj so calls to given methods are timed 'ok' 'ok' """ |
if prefix:
prefix = prefix + '.'
else:
prefix = ''
for method in methods:
current_method = getattr(obj, method)
new_method = timed(prefix)(current_method)
setattr(obj, method, new_method) |
<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_fields(self, **kwargs):
""" ensures that all incoming fields are the types that were specified """ |
for field in self.fields:
value = kwargs[field]
required_type = self.fields[field]
if type(value) != required_type:
raise TypeError('{}.{} needs to be a {}, recieved: {}({})'.format(
self.name,
field,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(self, path, engine, description=None):
"""Create a new config resource in the slicing service and upload the path contents to it""" |
if description is None:
head, tail = ntpath.split(path)
description = tail or ntpath.basename(head)
url = "http://quickslice.{}/config/raw/".format(self.config.host)
with open(path) as config_file:
content = config_file.read()
payload = {"engine":... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, path):
"""downloads a config resource to the path""" |
service_get_resp = requests.get(self.location, cookies={"session": self.session})
payload = service_get_resp.json()
download_get_resp = requests.get(payload["content"])
with open(path, "wb") as config_file:
config_file.write(download_get_resp.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 save_and_scan(filename, b64_data):
""" Save `b64_data` to temporary file and scan it for viruses. Args: filename (str):
Name of the file - used as basename ... |
with NTFile(suffix="_"+os.path.basename(filename), mode="wb") as ifile:
ifile.write(
b64decode(b64_data)
)
ifile.flush()
os.chmod(ifile.name, 0755)
return scan_file(ifile.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 pagure_specific_project_filter(config, message, project=None, *args, **kw):
""" Particular pagure projects Adding this rule allows you to get notifications f... |
if not pagure_catchall(config, message):
return False
project = kw.get('project', project)
link = fedmsg.meta.msg2link(message, **config)
if not link:
return False
project = project.split(',') if project else []
valid = False
for proj in project:
if '://pagure.io... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pagure_specific_project_tag_filter(config, message, tags=None, *args, **kw):
""" Particular pagure project tags Adding this rule allows you to get notificati... |
if not pagure_catchall(config, message):
return False
tags = tags.split(',') if tags else []
tags = [tag.strip() for tag in tags if tag and tag.strip()]
project_tags = set()
project_tags.update(message.get('project', {}).get('tags', []))
project_tags.update(
message.get('pull... |
<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_uri(orig_uriparts, kwargs):
""" Build the URI from the original uriparts and kwargs. Modifies kwargs. """ |
uriparts = []
for uripart in orig_uriparts:
# If this part matches a keyword argument (starting with _), use
# the supplied value. Otherwise, just use the part.
if uripart.startswith("_"):
part = (str(kwargs.pop(uripart, uripart)))
else:
part = uripart
... |
<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(path):
"""Load |path| and recursively expand any includes.""" |
with open(path) as rfile:
steps = MODEL.parse(rfile.read())
new_steps = []
for step in steps:
new_steps += expand_includes(step, path)
return new_steps |
<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_serialdiff(sd_dict):
"helper for translate_check"
if isinstance(sd_dict,list):
if len(sd_dict)!=2 or sd_dict[0]!='checkstale': raise NotImplementedError(sd_dict[0],len(sd_dict))
return CheckStale(sd_dict[1])
if isinstance(sd_dict['deltas'],list): # i.e. for VHString the whole deltas field is a s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def translate_update(blob):
"converts JSON parse output to self-aware objects"
# note below: v will be int or null
return {translate_key(k):parse_serialdiff(v) for k,v in blob.items()} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def process_check(pool,model,field,version):
"helper for do_check. version is an integer or null. returns ..."
try: syncable=model[field]
except pg.FieldError: return ['?field']
if not isinstance(syncable,syncschema.Syncable): return ['here',None,syncable]
if syncable.version()>version: # this includes versio... |
<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_missing_children(models,request,include_children_for,modelgb):
"helper for do_check. mutates request"
for (nombre,pkey),model in models.items():
for modelclass,pkeys in model.refkeys(include_children_for.get(nombre,())).items():
# warning: this is defaulting to all fields of child object. don't gi... |
<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_args():
""" Argument parser and validator """ |
parser = argparse.ArgumentParser(description="Uploads specified VMDK file to AWS s3 bucket, and converts to AMI")
parser.add_argument('-r', '--aws_regions', type=str, nargs='+', required=True,
help='list of AWS regions where uploaded ami should be copied. Available'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def R_rot_2d(th):
"""Return a 2-dimensional rotation matrix. Parameters th: array, shape (n, 1) Angles about which to rotate. Returns ------- R: array, shape (n,... |
s, = np.sin(th).T
c, = np.cos(th).T
R = np.empty((len(th), 2, 2), dtype=np.float)
R[:, 0, 0] = c
R[:, 0, 1] = -s
R[:, 1, 0] = s
R[:, 1, 1] = c
return R |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def R_rot_3d(th):
"""Return a 3-dimensional rotation matrix. Parameters th: array, shape (n, 3) Angles about which to rotate along each axis. Returns ------- R: ... |
sx, sy, sz = np.sin(th).T
cx, cy, cz = np.cos(th).T
R = np.empty((len(th), 3, 3), dtype=np.float)
R[:, 0, 0] = cy * cz
R[:, 0, 1] = -cy * sz
R[:, 0, 2] = sy
R[:, 1, 0] = sx * sy * cz + cx * sz
R[:, 1, 1] = -sx * sy * sz + cx * cz
R[:, 1, 2] = -sx * cy
R[:, 2, 0] = -cx * sy * ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def R_rot(th):
"""Return a rotation matrix. Parameters th: array, shape (n, m) Angles by which to rotate about each m rotational degree of freedom (m=1 in 2 dime... |
try:
dof = th.shape[-1]
# If th is a python float
except AttributeError:
dof = 1
th = np.array([th])
except IndexError:
dof = 1
th = np.array([th])
# If th is a numpy float, i.e. 0d array
if dof == 1:
return R_rot_2d(th)
elif dof == 3:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotate(a, th):
"""Return cartesian vectors, after rotation by specified angles about each degree of freedom. Parameters a: array, shape (n, d) Input d-dimens... |
return np.sum(a[..., np.newaxis] * R_rot(th), axis=-2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export_select_fields_csv_action( description="Export selected objects as CSV file", fields=None, exclude=None, header=True):
""" This function returns an exp... |
def export_as_csv(modeladmin, request, queryset):
"""
Generic csv export admin action.
based on http://djangosnippets.org/snippets/1697/
"""
opts = modeladmin.model._meta
field_names = [field.name for field in opts.fields]
labels = []
if exclude:
... |
<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, name=None, template=None, context={}):
''''Render Template meta from jinja2 templates.
'''
if isinstance(template, Template):
_template = template
else:
_template = Template.objects.get(name=name)
# Maybe cache or save local ?
r... |
<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):
"""Get specific information about this hub.""" |
output = helm("get", self.release)
if output.returncode != 0:
print("Something went wrong!")
print(output.stderr)
else:
print(output.stdout) |
<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(self):
"""Create a single instance of notebook.""" |
# Point to chart repo.
out = helm(
"repo",
"add",
"jupyterhub",
self.helm_repo
)
out = helm("repo", "update")
# Get token to secure Jupyterhub
secret_yaml = self.get_security_yaml()
# Get Jupyterhub.
out =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Delete a Jupyterhub.""" |
# Delete the Helm Release
out = helm(
"delete",
self.release,
"--purge"
)
if out.returncode != 0:
print(out.stderr)
else:
print(out.stdout)
# Delete the Kubernetes namespace
out = kubectl(
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.