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
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_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 beautiful "human" representation. There's three modes of operation: context manager, callable handler and iterator metrics. 1. Use it like a context manager: The actual duration in seconds is available in: 2. You can also use it like a callable handler: Use the field `result` to get the outcome of the function. Or you mix and match both: 3. And you can count and, since we have duration, also measure the throughput of an iterator block, specially useful in generators, which do not have length, but you can use with any iterables: """ |
# 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 = Handle(timings)
if it is None:
# use as context manager.
if fn is None:
return context()
# use as callable handler.
with context():
result = fn()
return HandleResult(timings, result)
# use as counter/throughput iterator.
if fn is None or not callable(fn): # handles inversion of parameters.
raise UserWarning('use as about_time(callback, iterable) in counter/throughput mode.')
def counter():
i = -1
with context():
for i, elem in enumerate(it):
yield elem
fn(HandleStats(timings, i + 1))
return counter() |
<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.setLevel(logging.WARN)
elif level == "error":
self.logger.setLevel(logging.ERROR)
else:
# par défaut
self.logger.setLevel(logging.INFO) |
<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érence :return datetime """ |
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 référence :return datetime """ |
# 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 de référence :return datetime """ |
# 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 handler_list:
if self._sync_mode:
# grab results of all handlers
result = self._execute(handler, *args, **kargs)
if isinstance(result, tuple) and len(result) == 3 and isinstance(result[1], Exception):
# error occurred
one_res_tuple = (False, self._error(result), handler)
else:
one_res_tuple = (True, result, handler)
else:
# execute handlers in background, ignoring result
EventSystem._async_queue.put((handler, args, kargs))
one_res_tuple = (None, None, handler)
result_list.append(one_res_tuple)
# update statistics
time_secs_new = time.time()
self.duration_secs = time_secs_new - self._time_secs_old
self._time_secs_old = time_secs_new
return result_list |
<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 kill a thread with clean ressource releasing,
# a thread has to cooperate und behave nice...
# execution and killing a process would be possible, but has data corruption problems with queues
# and possible interprocess communication problems with given handler/callback function)
result = None
exc_info = None
try:
result = handler(*args, **kwargs)
except Exception:
exc_info = sys.exc_info()
if exc_info:
return exc_info
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 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, file_path)
fp = file(buster_file, 'r')
# TODO: may be store it somewhere to not load file every time
busters_json = json.loads(fp.read())
fp.close()
file_hash = busters_json.get("static/%s" % filename)
path = static(filename)
return "%s?%s" % (path, file_hash) if file_hash is not None else 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 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_%i' % (key, i), 'f4', ('time', 'yc_1', 'xc_1' ))[:] = value[i]
else:
nc.getvar(root, key, 'f4', ('time', 'yc_1', 'xc_1'))[:] = 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_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)
return object_pairs_hook(loader.construct_pairs(node))
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
with open(file_path, 'r') as f:
return yaml.load(f, OrderedLoader) |
<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,
data.items())
OrderedDumper.add_representer(OrderedDict, _dict_representer)
# Make directory for calibration file if does not exist
base_path, file_name = os.path.split(out_path)
try:
os.makedirs(base_path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(base_path):
pass
else: raise
# Write dictionary to YAML
with open(out_path, 'w') as f:
return yaml.dump(data, f, OrderedDumper, default_flow_style=False, **kwds) |
<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 selected by the grouping name Does not override existing groupings """ |
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_parameters)
return state_collection |
<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 is given, the lowest available integer becomes the group key If no grouping exists by the given name a new one will be created Replaces any group with the same grouping_name and the same 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_collection |
<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: collection2 overrides collection1 if there is a group_key conflict """ |
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 will send an email related to the grant.
No return value, raises ValueError.
'''
path = "/api/v3/publisher/user/access/grant"
# convert expire_date to gmt seconds
if expire_datetime:
expires_seconds = calendar.timegm(expires_datetime.timetuple())
else:
expires_seconds = calendar.timegm(datetime.datetime.now().timetuple()) + (60*60*24)
data = {
'api_token': self.api_token,
'aid': self.app_id,
'rid': rid,
'uid': uid,
'expire_date': expires_seconds,
'send_email': send_email,
}
r = requests.get( self.base_url + path, data=data )
if r.status_code != 200:
raise ValueError( path + ":" + r.reason ) |
<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 = {
'api_token': self.api_token,
'access_id': access_id,
}
r = requests.get( self.base_url + path, data=data )
if r.status_code != 200:
raise ValueError( path + ":" + r.reason ) |
<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,
warningCount=self.warningCounts) |
<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 item in fileResults:
count += 1
output += "#%s - %s - %s\n" % (count, item[0],
item[1]["warning_count"])
output += "\nWarnings Breakdown\n==================\n"
count = 0
warningCount = 0
warningResults = sorted(self.warningCounts.items(),
key=lambda x: x[1]["count"], reverse=True)
for item in warningResults:
warningCount += item[1]["count"]
for warning, winfo in warningResults:
count += 1
output += "#%s - %s - %s (%s%%) - %s\n" % (count, warning,
winfo["count"], int(winfo["count"] / warningCount * 100),
tools.cleanupMessage(warning, winfo))
return output |
<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 come from L{tools.parsePyLintWarnings}. @param warningCount: A L{dict} produced by this method previously, if you are adding to the warnings. @return: L{dict} of L{dict}s for the warnings. """ |
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("warning_message")
else:
warningCount[wID]["count"] += 1
return warningCount |
<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)
modes = modes.replace(':', '', 1).replace(':', '', 1)
modes = modes.replace('[', '').replace( \
']', '').replace('+', '')
list_[channel] = usercount, modes, topic
elif msg[0] == '321':
pass
elif msg[0] == '323':
break
return list_ |
<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. If match_all is True, then only return servers who have all of the given roles. Otherwise, return servers that have one or more of the given roles. """ |
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)
elif envmatches and not match_all and len(roles & instroles) > 0:
result.append(instance)
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 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 the environment must match as well. If match_all is True, then only return servers who have all of the given roles. Otherwise, return servers that have one or more of the given roles. """ |
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],
spellchecker_cache_path)
return (user_words, valid_words) |
<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].progress = event.initial_progress
elif isinstance(event, ReadEvent):
self._data[event.asin].progress += event.progress
elif isinstance(event, SetFinishedEvent):
self._data[event.asin].status = ReadingStatus.COMPLETED
else:
raise TypeError |
<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 the current snapshot reflecting the progress state of the `asin_to_progress` mapping. Functionally, this method generates `AddEvent`s and `ReadEvent`s from updated Kindle Library state. Args: asin_to_progress: A map of book asins to the integral representation of progress used in the current snapshot. Returns: A list of Event objects that account for the changes detected in the `asin_to_progress`. """ |
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:
change = new_progress - book_snapshot.progress
if change > 0:
new_events.append(ReadEvent(asin, change))
return new_events |
<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 token string. * Raises a ``ParseError`` exception if stream is empty or regex match fails. """ |
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 = common.from_utf8(token.strip())
raise ParseError(pattern.format(token_val, line_no))
return token |
<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`` Look ahead in stream up to a maximum number of tokens. Returns string token or ``None``. """ |
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 push the tokens back on the
# lexer stack so we don't consume them
while stack:
line_no, token = stack.pop()
if not next_token:
next_token = token
self._lexer.push_token(line_no, token)
return next_token |
<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 ``ParseError`` exception if token doesn't match `expected`. """ |
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}"
.format(common.from_utf8(token.strip()), expected,
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 _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 object. Returns boolean. """ |
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 use for the file. Returns boolean. """ |
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 ``None`` for non-block option. `name` Option name. `*values` String values for the option. * Raises a ``ValueError`` exception if `values` is empty, `name` is invalid, or `block` doesn't exist. """ |
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:
# block doesn't exist
if not block in self._block_map:
raise ValueError(u"Block '{0}' does not exist"
.format(common.from_utf8(block)))
# lookup block index and append
block_idx = self._block_map[block]
# 0: block name, 1: option_list
self._ast[2][block_idx][1].append([name, values])
else:
# non-block option
self._ast[1].append([name, values]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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` Option name to remove. * Raises a ``ValueError`` exception if `name` and/or `block` haven't been added. """ |
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._block_map[block]
for i, opt in enumerate(self._ast[2][block_idx][1]):
if opt[0] == name:
item_idx = i
break
else:
raise ValueError(u"Option '{0}' does not exist"
.format(common.from_utf8(name)))
# pop off the block option
options = self._ast[2][block_idx][1]
options.pop(item_idx)
else:
if not self._ast:
raise ValueError(u"Option '{0}' does not exist"
.format(common.from_utf8(name)))
# non-block option
for i, opt in enumerate(self._ast[1]):
if opt[0] == name:
item_idx = i
break
else:
raise ValueError(u"Option '{0}' does not exist"
.format(common.from_utf8(name)))
# pop off non-block option
self._ast[1].pop(item_idx) |
<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 matches value provided for `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)))
# add new block and index mapping
self._block_map[name] = len(self._ast[2]) # must come first
option_list = []
block = [name, option_list]
self._ast[2].append(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_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, URL used to connect to the database. The URL contains information with regards to the database engine, the host to connect to, the user and password and the database name. ie: <engine>://<user>:<password>@<host>/<dbname> :kwarg alembic_ini, path to the alembic ini file. This is necessary to be able to use alembic correctly, but not for the unit-tests. :kwarg debug, a boolean specifying wether we should have the verbose output of sqlalchemy or not. :return a session that can be used to query the database. """ |
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(engine, 'connect', _fk_pragma_on_connect)
if alembic_ini is not None: # pragma: no cover
# then, load the Alembic configuration and generate the
# version table, "stamping" it with the most recent rev:
from alembic.config import Config
from alembic import command
alembic_cfg = Config(alembic_ini)
command.stamp(alembic_cfg, "head")
scopedsession = scoped_session(sessionmaker(bind=engine))
return scopedsession |
<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 setup.py script """ |
# 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))
relative = os.path.relpath(full, folder)
packages.append(relative)
package_dir[relative] = full
# we use pprint because we want the order to always remain the same
return 'packages={0},\npackage_dir={1}'.format(sorted(packages), pprint.pformat(package_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 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
else:
self._entries.append(record)
self.sort()
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 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:
resource_records.append(record._etree)
return etree.tostring(root, encoding="utf-8",
pretty_print=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 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 hyphen
('-' by default, specifiable with :param separator:). The two numbers are
parsed as integers and returned in the same order as a tuple of two
integers.
Example:
.. code-block: python
parsePortSpec('12345') # -> (12345, 12345)
parsePortSpec('12345-56789') # -> (12345, 56789)
'''
x = list(map(lambda x: x.strip(), spec.split(separator)))
return tuple(map(int, x * (3 - len(x)))) |
<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 alone is larger than the max batch file
# size. In this case instead of splitting up the message across files
# which would greatly increase complexity we simply dump that message
# into a file of its own even though it will be larger than the max
# batch file size.
if self._batch_size + msg_size > self._max_batch_file_size \
and self._batch_size > 0:
self._startNewBatch()
# Write the time stamp and information on how to retrieve the message
# from the batch files (batch filename, byte offset, and byte size)
global getTime
index_file_entry = '{:},{:09d},{:},{:}\n'.format(
getTime(), self._batch_index, self._batch_size, msg_size)
if sys.version_info >= (3,):
self._index_file.write(index_file_entry.encode('utf-8'))
else:
self._index_file.write(index_file_entry)
# Dump the message itself to the current batch file
self._batch_file.write(msg)
self._batch_size += msg_size
# Increment message count
self._message_count += 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 api_server(connection, server_class):
""" Establishes an API Server on the supplied connection Arguments: - connection (xbahn.connection.Connection) - server_class (xbahn.api.Server) Returns: - server_class: server instance """ |
# 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 result
else:
result = {}
for token, node in nodes.items():
host_name = node.get('host_name')
if search in (token, host_name):
result[token] = node.data
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 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 overwrite it." % (node_name)
return result
else:
node.delete()
node = nago.core.Node()
node['host_name'] = node_name
for k, v in kwargs.items():
node[k] = v
node.save()
result['message'] = "node successfully saved"
result['node_data'] = node.data
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 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
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 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, simply return pong You can use the special nodenames "server" or "master" """ |
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:
address = socket.gethostbyname(token_or_hostname)
node = nago.core.Node()
node['host_name'] = token_or_hostname
node['address'] = address
node['access'] = 'node'
if token_or_hostname == nago.settings.get_option('server'):
node['access'] = 'master'
node.save()
except Exception:
raise Exception("'%s' was not found in list of known hosts, and does not resolve to a valid address" % token_or_hostname)
return node.send_command('nodes', 'ping') |
<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
node['address'] = address
node['access'] = 'node'
if token_or_hostname == nago.settings.get_option('server'):
node['access'] = 'master'
node.save()
except Exception:
raise Exception("'%s' was not found in list of known hosts, and does not resolve to a valid address" % remote_host)
ping_result = node.send_command('nodes', 'ping')
if 'Pong' in ping_result.get('result', ''):
return "Connection with %s ok" % remote_host
else:
return ping_result.get('result', ping_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 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
if encode:
return u'\x1b[1;{}m{}\x1b[0m'.format(colors[color], msg)
return '\x1b[1;{}m{}\x1b[0m'.format(colors[color], msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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:
self.die('Failed to create output directory "{}": {}'.format(output_dir, str(e)))
return open(self.output, '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 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 = {
'active': '{} since {}'.format(self._colorize('active (running)', 'green'), self.pid.birthday()[1]),
'inactive': 'inactive (dead)'
}
# Print the status message
print(status_dot, end=' ')
print('{}.service - LSB: {}'.format(self.name, self.desc))
print(' Loaded: loaded (/etc/init.d/{})'.format(self.name))
print(' Active: {}'.format(active_txt['active' if pid else 'inactive']))
# Extra information if running
if pid:
ps = self.pid.ps()
print(' Process: {}; [{}]'.format(pid, ps[0]))
if ps[1]:
for c in ps[1]:
print(' Child: {}'.format(c))
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 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
try:
controls[self.command]()
except KeyError:
self.write_stdout('Usage: {} {{start|stop|status|restart|reload}}'.format(self.name), 3)
exit(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 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 returns the string value. """ |
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 with gzip before being passed to csv.reader. If the filename is not a string, it is assumed to be a file-like object which will be passed directly to csv.reader. """ |
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.reader(rfile, *args, **kwargs)
yield list(reader)
else:
reader = csv.reader(self.filename, *args, **kwargs)
yield list(reader) |
<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,
required_type.__name__,
type(value).__name__,
value.__repr__())) |
<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": engine,
"description": description,
"content": content}
post_resp = requests.post(url, json=payload, cookies={"session": self.session})
if not post_resp.ok:
raise errors.ResourceError("config upload to slicing service failed")
self.description = description
self.location = post_resp.headers["Location"] |
<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 for tmp file. b64_data (str):
Content of the file encoded in base64. Returns: dict: ``{filename: ("FOUND", "virus type")}`` or blank dict. """ |
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 for one or more `pagure.io <https://pagure.io>`_ projects. Specify multiple projects by separating them with a comma ','. """ |
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/%s/' % proj.strip() in link:
valid = True
return valid |
<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 notifications for one or more `pagure.io <https://pagure.io>`_ projects having the specified tags. Specify multiple tags by separating them with a comma ','. """ |
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('pullrequest', {}).get('project', {}).get('tags', []))
project_tags.update(
message.get('commit', {}).get('repo', {}).get('tags', []))
valid = len(project_tags.intersection(set(tags))) > 0
return valid |
<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
uriparts.append(part)
uri = '/'.join(uriparts)
# If an id kwarg is present and there is no id to fill in in
# the list of uriparts, assume the id goes at the end.
id = kwargs.pop('id', None)
if id:
uri += "/%s" % (id)
return uri |
<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 single string
# warning below: Delta.text will be a list sometimes. always?
sd_dict['deltas']=[diff.Delta(d['slice']['a'],d['slice']['b'],d['replace']) for d in sd_dict['deltas']]
return SerialDiff(**sd_dict) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def 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 version=None. this is the load case as well as update.
return ['here',syncable.version(),syncable.generate()] # 'here' as in 'here, take this' or 'here you go'
elif syncable.version()==version: return ['ok',version]
elif syncable.version()<version: return ['upload',syncable.version()]
else: raise RuntimeError("shouldn't get here") |
<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 give clients a way to restrict that until there's a reason to.
childname=modelgb['row',modelclass].name
for childfield,cftype in modelclass.FIELDS:
if not isinstance(cftype,basestring) and inspect.isclass(cftype) and issubclass(cftype,syncschema.Syncable):
merge_null_missing(request,childname,childfield,pkeys)
elif childfield in modelclass.SENDRAW: merge_null_missing(request,childname,childfield,pkeys)
else: pass # intentional: ignore the field
return request # the in-place updated original |
<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'
' regions: {}.'.format(AWSUtilities.aws_regions))
parser.add_argument('-a', '--aws_profile', type=str, required=True, help='AWS profile name to use for aws cli commands')
parser.add_argument('-b', '--s3_bucket', type=str, required=True,
help='The aws_bucket of the profile to upload and save vmdk to')
parser.add_argument('-f', '--vmdk_upload_file', type=str, required=True,
help="The file to upload if executing ")
parser.add_argument('-n', '--ami_name', type=str, required=False, help='The name to give to the uploaded ami. '
'Defaults to the name of the file')
parser.add_argument('-d', '--directory', type=str, default=tempfile.mkdtemp(),
help='Directory to save temp aws config upload files')
args = parser.parse_args()
if not args.ami_name:
args.ami_name = os.path.basename(args.vmdk_upload_file)
validate_args(args)
return 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 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, 2, 2) """ |
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: array, shape (n, 3, 3) """ |
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 * cz + sx * sz
R[:, 2, 1] = cx * sy * sz + sx * cz
R[:, 2, 2] = cx * cy
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(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 dimensions, m=3 in 3 dimensions). Returns ------- R: array, shape (n, m, m) """ |
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:
return R_rot_3d(th)
else:
raise Exception('Rotation matrix not implemented in this dimension') |
<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-dimensional cartesian vectors, left unchanged. th: array, shape (n, m) Angles by which to rotate about each m rotational degree of freedom (m=1 in 2 dimensions, m=3 in 3 dimensions). Returns ------- ar: array, shape of a Rotated cartesian vectors. """ |
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 export csv action 'fields' is a list of tuples denoting the field and label to be exported. Labels make up the header row of the exported file if header=True. fields=[ ('field1', 'label1'), ('field2', 'label2'), ('field3', 'label3'), ] 'exclude' is a flat list of fields to exclude. If 'exclude' is passed, 'fields' will not be used. Either use 'fields' or 'exclude.' exclude=['field1', 'field2', field3] 'header' is whether or not to output the column names as the first row From: http://djangosnippets.org/snippets/2712/ Which is in turn based on: http://djangosnippets.org/snippets/2020/ """ |
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:
field_names = [v for v in field_names if v not in exclude]
elif fields:
field_names = [k for k, v in fields if k in field_names]
labels = [v for k, v in fields if k in field_names]
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = ('attachment; filename=%s.csv'
% unicode(opts).replace('.', '_'))
writer = csv.writer(response)
if header:
if labels:
writer.writerow(labels)
else:
writer.writerow(field_names)
for obj in queryset:
writer.writerow([unicode(getattr(obj, field)).encode('utf-8')
for field in field_names])
return response
export_as_csv.short_description = description
return export_as_csv |
<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 ?
response = self.env.from_string(
_template.content).render(context)
return response |
<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 = helm(
"upgrade",
"--install",
self.release,
"jupyterhub/jupyterhub",
namespace=self.namespace,
version=self.version,
input=secret_yaml
)
if out.returncode != 0:
print(out.stderr)
else:
print(out.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 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(
"delete",
"namespace",
self.namespace
)
if out.returncode != 0:
print(out.stderr)
else:
print(out.stdout) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.