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 download_local_file(filename, download_to_file):
""" Copies a local file to Invenio's temporary directory. @param filename: the name of the file to copy @typ... |
# Try to copy.
try:
path = urllib2.urlparse.urlsplit(urllib.unquote(filename))[2]
if os.path.abspath(path) != path:
msg = "%s is not a normalized path (would be %s)." \
% (path, os.path.normpath(path))
raise InvenioFileCopyError(msg)
allowed_pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def safe_mkstemp(suffix, prefix='filedownloadutils_'):
"""Create a temporary filename that don't have any '.' inside a part from the suffix.""" |
tmpfd, tmppath = tempfile.mkstemp(
suffix=suffix,
prefix=prefix,
dir=current_app.config['CFG_TMPSHAREDDIR']
)
# Close the file and leave the responsability to the client code to
# correctly open/close it.
os.close(tmpfd)
if '.' not in suffix:
# Just in case form... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_url(url, headers=None):
""" Opens a URL. If headers are passed as argument, no check is performed and the URL will be opened. @param url: the URL to ope... |
request = urllib2.Request(url)
if headers:
for key, value in headers.items():
request.add_header(key, value)
return URL_OPENER.open(request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def get_json(self, url, timeout=30, astext=False, exceptions=False):
"""Get URL and parse JSON from text.""" |
try:
with async_timeout.timeout(timeout):
res = await self._aio_session.get(url)
if res.status != 200:
_LOGGER.error("QSUSB returned %s [%s]", res.status, url)
return None
res_text = await res.text()
exc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Stop listening.""" |
self._running = False
if self._sleep_task:
self._sleep_task.cancel()
self._sleep_task = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def _async_listen(self, callback=None):
"""Listen loop.""" |
while True:
if not self._running:
return
try:
packet = await self.get_json(
URL_LISTEN.format(self._url), timeout=30, exceptions=True)
except asyncio.TimeoutError:
continue
except aiohttp.client... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attowiki_distro_path():
"""return the absolute complete path where attowiki is located .. todo:: use pkg_resources ? """ |
attowiki_path = os.path.abspath(__file__)
if attowiki_path[-1] != '/':
attowiki_path = attowiki_path[:attowiki_path.rfind('/')]
else:
attowiki_path = attowiki_path[:attowiki_path[:-1].rfind('/')]
return attowiki_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 build_command(self):
"""Build out the crontab command""" |
return cron_utils.cronify("crontab -l | {{ cat; echo \"{} {} {} {} {} CJOBID='{}' MAILTO='' {}\"; }} | crontab - > /dev/null".format(self._minute, self._hour, self._day_of_month, self._month_of_year, self._day_of_week, self._jobid, self._command)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def infer_format(filename:str) -> str: """Return extension identifying format of given filename""" |
_, ext = os.path.splitext(filename)
return ext |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reversed_graph(graph:dict) -> dict: """Return given graph reversed""" |
ret = defaultdict(set)
for node, succs in graph.items():
for succ in succs:
ret[succ].add(node)
return dict(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 have_cycle(graph:dict) -> frozenset: """Perform a topologic sort to detect any cycle. Return the set of unsortable nodes. If at least one item, then there is ... |
# topological sort
walked = set() # walked nodes
nodes = frozenset(it.chain(it.chain.from_iterable(graph.values()), graph.keys())) # all nodes of the graph
preds = reversed_graph(graph) # succ: preds
last_walked_len = -1
while last_walked_len != len(walked):
last_walked_len = len(wal... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_lines(bblfile:str) -> iter: """Yield lines found in given file""" |
with open(bblfile) as fd:
yield from (line.rstrip() for line in fd if line.rstrip()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def line_type(line:str) -> str: """Give type of input line, as defined in LINE_TYPES 'IN' 'EMPTY' """ |
for regex, ltype in LINE_TYPES.items():
if re.fullmatch(regex, line):
return ltype
raise ValueError("Input line \"{}\" is not bubble formatted".format(line)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def line_data(line:str) -> tuple: """Return groups found in given line ('IN', 'a', 'b') () """ |
for regex, _ in LINE_TYPES.items():
match = re.fullmatch(regex, line)
if match:
return match.groups()
raise ValueError("Input line \"{}\" is not bubble formatted".format(line)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _initBuffer(self, bufferColorMode, bufferSize):
"""! \~english Initialize the buffer object instance, use PIL Image as for buffer @param bufferColorMode: "RG... |
# super(SSScreenBase)._initBuffer(bufferColorMode, bufferSize)
self._buffer_color_mode = bufferColorMode
#create screen image buffer and canvas
if bufferSize==None:
self._buffer = Image.new( bufferColorMode , self._display_size )
else:
self._buffer = Ima... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clearCanvas(self, fillColor = 0 ):
"""! \~engliash Clear up canvas and fill color at same time @param fillColor: a color value @note The fillColor value rang... |
self.Canvas.rectangle((0, 0, self._display_size[0], self._display_size[1]), outline=0, fill=fillColor) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resize(self, newWidth = 0, newHeight = 0):
"""! \~english Resize width and height of rectangles @param newWidth: new width value @param newHeight: new height... |
self.height = newHeight
self.width = newWidth |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotateDirection(self, displayDirection):
"""! \~english rotate screen direction @param displayDirection: Screen Direction. value can be chosen: 0, 90, 180, 2... |
if self._needSwapWH(self._display_direction, displayDirection):
self._display_size = ( self._display_size[1], self._display_size[0] )
if self.redefineBuffer( { "size":self._display_size, "color_mode":self._buffer_color_mode } ):
self.View.resize(self._display_size[0], se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autodiscover_modules(packages, related_name_re='.+', ignore_exceptions=False):
"""Autodiscover function follows the pattern used by Celery. :param packages: ... |
warnings.warn('autodiscover_modules has been deprecated. '
'Use Flask-Registry instead.', DeprecationWarning)
global _RACE_PROTECTION
if _RACE_PROTECTION:
return []
_RACE_PROTECTION = True
modules = []
try:
tmp = [find_related_modules(pkg, related_name_re, ign... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_related_modules(package, related_name_re='.+', ignore_exceptions=False):
"""Find matching modules using a package and a module name pattern.""" |
warnings.warn('find_related_modules has been deprecated.',
DeprecationWarning)
package_elements = package.rsplit(".", 1)
try:
if len(package_elements) == 2:
pkg = __import__(package_elements[0], globals(), locals(), [
package_elements[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 import_related_module(package, pkg_path, related_name, ignore_exceptions=False):
"""Import module from given path.""" |
try:
imp.find_module(related_name, pkg_path)
except ImportError:
return
try:
return getattr(
__import__('%s' % (package), globals(), locals(), [related_name]),
related_name
)
except Exception as e:
if ignore_exceptions:
curren... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ansi(string, *args):
""" Convenience function to chain multiple ColorWrappers to a string """ |
ansi = ''
for arg in args:
arg = str(arg)
if not re.match(ANSI_PATTERN, arg):
raise ValueError('Additional arguments must be ansi strings')
ansi += arg
return ansi + string + colorama.Style.RESET_ALL |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def puts(*args, **kwargs):
""" Full feature printing function featuring trimming and padding for both files and ttys """ |
# parse kwargs
trim = kwargs.pop('trim', False)
padding = kwargs.pop('padding', None)
stream = kwargs.pop('stream', sys.stdout)
# HACK: check if stream is IndentedFile
indent = getattr(stream, 'indent', 0)
# stringify args
args = [str(i) for i in args]
# helpers
def trimstr(ansi, width):
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 char_between(lower, upper, func_name):
'''return current char and step if char is between lower and upper, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
function = register_function(func_na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def char_in(string, func_name):
'''return current char and step if char is in string, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
function = register_function(func_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 update_version(self, version, step=1):
"Compute an new version and write it as a tag"
# update the version based on the flags passed.
if self.config.patch:
version.patch += step
if self.config.minor:
version.minor += step
if self.config.major:
... |
<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_id(self):
"""Getter because using the id property from within was not working""" |
ret = None
row = self.row
if row:
ret = row["id"]
return 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 time_pipeline(iterable, *steps):
'''
This times the steps in a pipeline. Give it an iterable to test against
followed by the steps of the pipeline seperated in individual functions.
Example Usage:
```
from random import choice, randint
l = [randint(0,50) for i in range(100)]
step1 = lambda iterab... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def runs_per_second(generator, seconds=3):
'''
use this function as a profiler for both functions and generators
to see how many iterations or cycles they can run per second
Example usage for timing simple operations/functions:
```
print(runs_per_second(lambda:1+2))
# 2074558
print(runs_per_second(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fermion_avg(efermi, norm_hopping, func):
"""calcules for every slave it's average over the desired observable""" |
if func == 'ekin':
func = bethe_ekin_zeroT
elif func == 'ocupation':
func = bethe_filling_zeroT
return np.asarray([func(ef, tz) for ef, tz in zip(efermi, norm_hopping)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spinflipandhop(slaves):
"""Calculates the interaction term of a spin flip and pair hopping""" |
Sdw = [csr_matrix(spin_gen(slaves, i, 0)) for i in range(slaves)]
Sup = [mat.T for mat in Sdw]
sfh = np.zeros_like(Sup[0])
orbitals = slaves//2
for n in range(orbitals):
for m in range(n+1, orbitals):
sfh += Sup[2*n ] * Sdw[2*n + 1] * Sup[2*m + 1] * Sdw[2*m ]
sfh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spin_z_op(param, oper):
"""Generates the required Sz operators, given the system parameter setup and the operator dictionary""" |
slaves = param['slaves']
oper['Sz'] = np.array([spin_z(slaves, spin) for spin in range(slaves)])
oper['Sz+1/2'] = oper['Sz'] + 0.5*np.eye(2**slaves)
oper['sumSz2'] = oper['Sz'].sum(axis=0)**2 # because Sz is diagonal
Sz_mat_shape = oper['Sz'].reshape(param['orbitals'], 2, 2**slaves, 2**slaves)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spin_gen_op(oper, gauge):
"""Generates the generic spin matrices for the system""" |
slaves = len(gauge)
oper['O'] = np.array([spin_gen(slaves, i, c) for i, c in enumerate(gauge)])
oper['O_d'] = np.transpose(oper['O'], (0, 2, 1))
oper['O_dO'] = np.einsum('...ij,...jk->...ik', oper['O_d'], oper['O'])
oper['Sfliphop'] = spinflipandhop(slaves) |
<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_filling(self, populations):
"""Sets the orbital enenergies for on the reference of the free case. By setting the desired local populations on every orbit... |
populations = np.asarray(populations)
#
# self.param['orbital_e'] -= bethe_findfill_zeroT( \
# self.param['avg_particles'],
# self.param['orbital_e'],
# self.param['hopping'])
efe... |
<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, populations, lag, mu, u_int, j_coup, mean_f):
"""Resets the system into the last known state as given by the input values""" |
self.set_filling(populations)
self.param['lambda'] = lag
self.param['orbital_e'] = mu
self.selfconsistency(u_int, j_coup, mean_f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_H(self, mean_field, l):
"""Updates the spin hamiltonian and recalculates its eigenbasis""" |
self.H_s = self.spin_hamiltonian(mean_field, l)
try:
self.eig_energies, self.eig_states = diagonalize(self.H_s)
except np.linalg.linalg.LinAlgError:
np.savez('errorhamil', H=self.H_s, fiel=mean_field, lamb=l)
raise
except ValueError:
np.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 spin_hamiltonian(self, h, l):
"""Constructs the single site spin Hamiltonian""" |
h_spin = np.einsum('i,ijk', h[1], self.oper['O'])
h_spin += np.einsum('i,ijk', h[0], self.oper['O_d'])
h_spin += np.einsum('i,ijk', l, self.oper['Sz+1/2'])
h_spin += self.oper['Hint']
return h_spin |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inter_spin_hamiltonian(self, u_int, J_coup):
"""Calculates the interaction Hamiltonian. The Hund coupling is a fraction of the coulom interaction""" |
J_coup *= u_int
h_int = (u_int - 2*J_coup)/2.*self.oper['sumSz2']
h_int += J_coup*self.oper['sumSz-sp2']
h_int -= J_coup/2.*self.oper['sumSz-or2']
h_int -= J_coup*self.oper['Sfliphop']
return h_int |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expected(self, observable, beta=1e5):
"""Wrapper to the expected_value function to fix the eigenbasis""" |
return expected_value(observable,
self.eig_energies,
self.eig_states,
beta) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quasiparticle_weight(self):
"""Calculates quasiparticle weight""" |
return np.array([self.expected(op)**2 for op in self.oper['O']]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mean_field(self):
"""Calculates mean field""" |
mean_field = []
for sp_oper in [self.oper['O'], self.oper['O_d']]:
avgO = np.array([self.expected(op) for op in sp_oper])
avgO[abs(avgO) < 1e-10] = 0.
mean_field.append(avgO*self.param['ekin'])
return np.array(mean_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 selfconsistency(self, u_int, J_coup, mean_field_prev=None):
"""Iterates over the hamiltonian to get the stable selfcosistent one""" |
if mean_field_prev is None:
mean_field_prev = np.array([self.param['ekin']]*2)
hlog = [mean_field_prev]
self.oper['Hint'] = self.inter_spin_hamiltonian(u_int, J_coup)
converging = True
half_fill = (self.param['populations'] == 0.5).all()
while converging:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restriction(self, lam, mean_field):
"""Lagrange multiplier in lattice slave spin""" |
self.update_H(mean_field, lam)
restric = np.array([self.expected(op) - n for op, n in zip(self.oper['Sz+1/2'], self.param['populations'])])
return restric |
<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_cmd(cmd, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command :param list cmd: Command to run. :param str out: Output file :param str e... |
logger.debug(' '.join(cmd))
with open(out, 'w') as hout:
proc = subprocess.Popen(cmd, stdout=hout, stderr=subprocess.PIPE)
err_msg = proc.communicate()[1].decode()
with open(err, 'w') as herr:
herr.write(str(err_msg))
msg = '({}) {}'.format(' '.join(cmd), err_msg)
if proc.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 run_cmd_if_file_missing(cmd, fname, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command if file is absent. :param list cmd: Command to run... |
if fname is None or not os.path.exists(fname):
run_cmd(cmd, out, err)
return True
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 merge_files(sources, destination):
"""Copy content of multiple files into a single file. :param list(str) sources: source file names (paths) :param str desti... |
with open(destination, 'w') as hout:
for f in sources:
if os.path.exists(f):
with open(f) as hin:
shutil.copyfileobj(hin, hout)
else:
logger.warning('File is missing: {}'.format(f)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_path(self, path):
""" Adds a new path to the list of searchable paths :param path: new path """ |
if os.path.exists(path):
self.paths.add(path)
return path
else:
#logger.debug('Path {} doesn\'t exist'.format(path))
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, name):
""" Looks for a name in the path. :param name: file name :return: path to the file """ |
for d in self.paths:
if os.path.exists(d) and name in os.listdir(d):
return os.path.join(d, name)
logger.debug('File not found {}'.format(name))
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __handle_request(self, request, *args, **kw):
""" Intercept the request and response. This function lets `HttpStatusCodeError`s fall through. They are caught... |
self._authenticate(request)
self._check_permission(request)
method = self._get_method(request)
data = self._get_input_data(request)
data = self._clean_input_data(data, request)
response = self._exec_method(method, request, data, *args, **kw)
return self._process... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _exec_method(self, method, request, data, *args, **kw):
""" Execute appropriate request handler. """ |
if self._is_data_method(request):
return method(data, request, *args, **kw)
else:
return method(request, *args, **kw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_response(self, request, response):
""" Format response using appropriate datamapper. Take the devil response and turn it into django response, ready ... |
res = datamapper.format(request, response, self)
# data is now formatted, let's check if the status_code is set
if res.status_code is 0:
res.status_code = 200
# apply headers
self._add_resposne_headers(res, response)
return res |
<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_resposne_headers(self, django_response, devil_response):
""" Add response headers. Add HTTP headers from devil's response to django's response. """ |
try:
headers = devil_response.headers
except AttributeError:
# ok, there was no devil_response
pass
else:
for k, v in headers.items():
django_response[k] = v
return django_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_input_data(self, request):
""" If there is data, parse it, otherwise return None. """ |
# only PUT and POST should provide data
if not self._is_data_method(request):
return None
content = [row for row in request.read()]
content = ''.join(content) if content else None
return self._parse_input_data(content, request) if content else None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clean_input_data(self, data, request):
""" Clean input data. """ |
# sanity check
if not self._is_data_method(request):
# this is not PUT or POST -> return
return data
# do cleaning
try:
if self.representation:
# representation defined -> perform validation
self._validate_input_data(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_input_validator(self, request):
""" Return appropriate input validator. For POST requests, ``self.post_representation`` is returned if it is present, ``... |
method = request.method.upper()
if method != 'POST':
return self.representation
elif self.post_representation:
return self.post_representation
else:
return self.representation |
<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_input_data(self, data, request):
""" Validate input data. :param request: the HTTP request :param data: the parsed data :return: if validation is p... |
validator = self._get_input_validator(request)
if isinstance(data, (list, tuple)):
return map(validator.validate, data)
else:
return validator.validate(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_output_data( self, original_res, serialized_res, formatted_res, request):
""" Validate the response data. :param response: ``HttpResponse`` :param ... |
validator = self.representation
# when not to validate...
if not validator:
return
try:
if isinstance(serialized_res, (list, tuple)):
map(validator.validate, serialized_res)
else:
validator.validate(serialized_res)
... |
<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_object(self, data, request):
""" Create a python object from the given data. This will use ``self.factory`` object's ``create()`` function to create ... |
if request.method.upper() == 'POST' and self.post_factory:
fac_func = self.post_factory.create
else:
fac_func = self.factory.create
if isinstance(data, (list, tuple)):
return map(fac_func, data)
else:
return fac_func(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serialize_object(self, response_data, request):
""" Create a python datatype from the given python object. This will use ``self.factory`` object's ``seriali... |
if not self.factory:
return response_data
if isinstance(response_data, (list, tuple)):
return map(
lambda item: self.factory.serialize(item, request),
response_data)
else:
return self.factory.serialize(response_data, request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_unknown_error_response(self, request, exc):
""" Generate HttpResponse for unknown exceptions. todo: this should be more informative.. """ |
logging.getLogger('devil').error(
'while doing %s on %s with [%s], devil caught: %s' % (
request.method, request.path_info, str(request.GET), str(exc)), exc_info=True)
if settings.DEBUG:
raise
else:
return HttpResponse(status=codes.INTERNAL_... |
<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_error_response(self, exc):
""" Generate HttpResponse based on the HttpStatusCodeError. """ |
if exc.has_code(codes.UNAUTHORIZED):
return self._get_auth_challenge(exc)
else:
if exc.has_code(codes.INTERNAL_SERVER_ERROR):
logging.getLogger('devil').error('devil caught http error: ' + str(exc), exc_info=True)
else:
logging.getLogg... |
<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_auth_challenge(self, exc):
""" Returns HttpResponse for the client. """ |
response = HttpResponse(content=exc.content, status=exc.get_code_num())
response['WWW-Authenticate'] = 'Basic realm="%s"' % REALM
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_method(self, request):
""" Figure out the requested method and return the callable. """ |
methodname = request.method.lower()
method = getattr(self, methodname, None)
if not method or not callable(method):
raise errors.MethodNotAllowed()
return 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 _authenticate(self, request):
""" Perform authentication. """ |
def ensure_user_obj():
""" Make sure that request object has user property.
If `request.user` is not present or is `None`, it is
created and initialized with `AnonymousUser`.
"""
try:
if request.user:
return
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_item_callback(item):
"""Print an item callback, used by &listen.""" |
print('&listen [{}, {}={}]'.format(
item.get('cmd', ''),
item.get('id', ''),
item.get('data', ''))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Quick test for QSUsb class.""" |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--url', help='QSUSB URL [http://127.0.0.1:2020]',
default='http://127.0.0.1:2020')
parser.add_argument('--file', help='a test file from /&devices')
parser.add_argument('--test_ids', help='List of test ID... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self):
"""Called to get the asset values and if it is valid """ |
with self._lock:
now = datetime.now()
active = []
for i, vef in enumerate(self.futures):
# has expired
if (vef[1] or datetime.max) <= now:
self.futures.pop(i)
continue
# in future
... |
<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(node, **kwds):
"""add_node from Sphinx """ |
nodes._add_node_class_names([node.__name__])
for key, val in kwds.iteritems():
try:
visit, depart = val
except ValueError:
raise ValueError('Value for key %r must be a '
'(visit, depart) function tuple' % key)
if key == 'html':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retrieve(self, *args, **kwargs):
"""Retrieve the permsission function for the provided things. """ |
lookup, key = self._lookup(*args, **kwargs)
return lookup[key] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_rabf_motif(self):
"""Checks if the sequence has enough RabF motifs within the G domain If there exists more than one G domain in the sequence enough RabF... |
if self.rabf_motifs:
for gdomain in self.gdomain_regions:
beg, end = map(int, gdomain.split('-'))
motifs = [x for x in self.rabf_motifs if x[1] >= beg and x[2] <= end]
if motifs:
matches = int(pairwise2.align.globalxx('12345', ''.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summarize(self):
""" G protein annotation summary in a text format :return: A string summary of the annotation :rtype: str """ |
data = [
['Sequence ID', self.seqrecord.id],
['G domain', ' '.join(self.gdomain_regions) if self.gdomain_regions else None],
['E-value vs rab db', self.evalue_bh_rabs],
['E-value vs non-rab db', self.evalue_bh_non_rabs],
['RabF motifs', ' '.join(map(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 write(self):
"""Write sequences predicted to be Rabs as a fasta file. :return: Number of written sequences :rtype: int """ |
rabs = [x.seqrecord for x in self.gproteins.values() if x.is_rab()]
return SeqIO.write(rabs, self.tmpfname + '.phase2', 'fasta') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self):
""" Check if data and third party tools, necessary to run the classification, are available :raises: RuntimeError """ |
pathfinder = Pathfinder(True)
if pathfinder.add_path(pathfinder['superfamily']) is None:
raise RuntimeError("'superfamily' data directory is missing")
for tool in ('hmmscan', 'phmmer', 'mast', 'blastp', 'ass3.pl', 'hmmscan.pl'):
if not pathfinder.exists(tool):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_(*permissions, **kwargs):
""" Constructs a clause to filter all bearers or targets for a given berarer or target. """ |
bearer = kwargs['bearer']
target = kwargs.get('target')
bearer_cls = type_for(bearer)
# We need a query object. There are many ways to get one, Either we can
# be passed one, or we can make one from the session. We can either be
# passed the session, or we can grab the session from the bear... |
<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_app(application, request_class=Request):
""" Create a WSGI application out of the given Minion app. Arguments: application (Application):
a minion ap... |
def wsgi(environ, start_response):
response = application.serve(
request=request_class(environ),
path=environ.get("PATH_INFO", ""),
)
start_response(
response.status, [
(name, b",".join(values))
for name, values in respons... |
<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_documentation(self, request, *args, **kw):
""" Generate the documentation. """ |
ret = dict()
ret['resource'] = self.name()
ret['urls'] = self._get_url_doc()
ret['description'] = self.__doc__
ret['representation'] = self._get_representation_doc()
ret['methods'] = self._get_method_doc()
return 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 _serialize_object(self, response_data, request):
""" Override to not serialize doc responses. """ |
if self._is_doc_request(request):
return response_data
else:
return super(DocumentedResource, self)._serialize_object(
response_data, request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_output_data( self, original_res, serialized_res, formatted_res, request):
""" Override to not validate doc output. """ |
if self._is_doc_request(request):
return
else:
return super(DocumentedResource, self)._validate_output_data(
original_res, serialized_res, formatted_res, request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_method(self, request):
""" Override to check if this is a documentation request. """ |
if self._is_doc_request(request):
return self.get_documentation
else:
return super(DocumentedResource, self)._get_method(request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_representation_doc(self):
""" Return documentation for the representation of the resource. """ |
if not self.representation:
return 'N/A'
fields = {}
for name, field in self.representation.fields.items():
fields[name] = self._get_field_doc(field)
return fields |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_field_doc(self, field):
""" Return documentation for a field in the representation. """ |
fieldspec = dict()
fieldspec['type'] = field.__class__.__name__
fieldspec['required'] = field.required
fieldspec['validators'] = [{validator.__class__.__name__: validator.__dict__} for validator in field.validators]
return fieldspec |
<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_url_doc(self):
""" Return a list of URLs that map to this resource. """ |
resolver = get_resolver(None)
possibilities = resolver.reverse_dict.getlist(self)
urls = [possibility[0] for possibility in possibilities]
return urls |
<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_method_doc(self):
""" Return method documentations. """ |
ret = {}
for method_name in self.methods:
method = getattr(self, method_name, None)
if method:
ret[method_name] = method.__doc__
return 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 create_process(self, command, shell=True, stdout=None, stderr=None, env=None):
""" Execute a process using subprocess.Popen, setting the backend's DISPLAY ""... |
env = env if env is not None else dict(os.environ)
env['DISPLAY'] = self.display
return subprocess.Popen(command, shell=shell,
stdout=stdout, stderr=stderr,
env=env) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pause(self, instance_id, keep_provisioned=True):
"""shuts down the instance without destroying it. The AbstractCloudProvider class uses 'stop' to refer to de... |
try:
if self._paused:
log.debug("node %s is already paused", instance_id)
return
self._paused = True
post_shutdown_action = 'Stopped' if keep_provisioned else \
'StoppedDeallocated'
result = self._subscription._sms.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restart(self, instance_id):
"""restarts a paused instance. :param str instance_id: instance identifier :return: None """ |
try:
if not self._paused:
log.debug("node %s is not paused, can't restart", instance_id)
return
self._paused = False
result = self._subscription._sms.start_role(
service_name=self._cloud_service._name,
deploymen... |
<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_or_update(self):
"""Save or update the private state needed by the cloud provider. """ |
with self._resource_lock:
if not self._config or not self._config._storage_path:
raise Exception("self._config._storage path is undefined")
if not self._config._base_name:
raise Exception("self._config._base_name is undefined")
if not os.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 get_path(root, path, default=_UNSET):
"""Retrieve a value from a nested object via a tuple representing the lookup path. 3 The path format is intentionally c... |
if isinstance(path, basestring):
path = path.split('.')
cur = root
try:
for seg in path:
try:
cur = cur[seg]
except (KeyError, IndexError) as exc:
raise PathAccessError(exc, seg, path)
except TypeError as exc:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __query(p, k, v, accepted_keys=None, required_values=None, path=None, exact=True):
""" Query function given to visit method :param p: visited path in tuple f... |
# if not k:
# print '__query p k:', p, k
# print p, k, accepted_keys, required_values, path, exact
def as_values_iterable(v):
if isinstance(v, dict):
return v.values()
elif isinstance(v, six.string_types):
return [v]
else:
# assume is alr... |
<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_image_url(self, image_id):
"""Gets the url for the specified image. Unfortunatly this only works for images uploaded by the user. The images provided by... |
gce = self._connect()
filter = "name eq %s" % image_id
request = gce.images().list(project=self._project_id, filter=filter)
response = self._execute_request(request)
response = self._wait_until_done(response)
image_url = None
if "items" in 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 execute(self):
""" Load the cluster and build a GC3Pie configuration snippet. """ |
creator = make_creator(self.params.config,
storage_path=self.params.storage)
cluster_name = self.params.cluster
try:
cluster = creator.load_cluster(cluster_name)
except (ClusterNotFound, ConfigurationError) as ex:
log.error("Listing... |
<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_xml(self, outfile, encoding="UTF-8"):
"""Write the Media RSS Feed's XML representation to the given file.""" |
# we add the media namespace if we see any media items
if any([key for item in self.items for key in vars(item) if
key.startswith('media_') and getattr(item, key)]):
self.rss_attrs["xmlns:media"] = "http://search.yahoo.com/mrss/"
self.generator = _generator_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 _add_attribute(self, name, value, allowed_values=None):
"""Add an attribute to the MediaContent element.""" |
if value and value != 'none':
if isinstance(value, (int, bool)):
value = str(value)
if allowed_values and value not in allowed_values:
raise TypeError(
"Attribute '" + name + "' must be one of " + str(
allowed... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_complicance(self):
"""Check compliance with Media RSS Specification, Version 1.5.1. see http://www.rssboard.org/media-rss Raises AttributeError on erro... |
# check Media RSS requirement: one of the following elements is
# required: media_group | media_content | media_player | media_peerLink
# | media_location. We do the check only if any media_... element is
# set to allow non media feeds
if(any([ma for ma in vars(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 publish_extensions(self, handler):
"""Publish the Media RSS Feed elements as XML.""" |
if isinstance(self.media_content, list):
[PyRSS2Gen._opt_element(handler, "media:content", mc_element) for
mc_element in self.media_content]
else:
PyRSS2Gen._opt_element(handler, "media:content",
self.media_content)
if has... |
<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_conversations(self):
""" Returns list of Conversation objects """ |
cs = self.data["data"]
res = []
for c in cs:
res.append(Conversation(c))
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _accumulate(iterable, func=(lambda a,b:a+b)): # this was from the itertools documentation
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
try:
total = next(it)
except StopIteration:
... |
<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_methods(methods_to_add):
''' use this to bulk add new methods to Generator '''
for i in methods_to_add:
try:
Generator.add_method(*i)
except Exception as ex:
raise Exception('issue adding {} - {}'.format(repr(i), ex)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dirsize_get(l_filesWithoutPath, **kwargs):
""" Sample callback that determines a directory size. """ |
str_path = ""
for k,v in kwargs.items():
if k == 'path': str_path = v
d_ret = {}
l_size = []
size = 0
for f in l_filesWithoutPath:
str_f = '%s/%s' % (str_path, f)
if not os.path.islink(str_f):
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 inputReadCallback(self, *args, **kwargs):
""" Test for inputReadCallback This method does not actually "read" the input files, but simply returns the passed ... |
b_status = True
filesRead = 0
for k, v in kwargs.items():
if k == 'l_file': l_file = v
if k == 'path': str_path = v
if len(args):
at_data = args[0]
str_path = at_data[0]
l_file = at_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.