text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_mapper(self, mapper):
""" Check that the mapper has valid signature. """ |
if not hasattr(mapper, 'parse') or not callable(mapper.parse):
raise ValueError('mapper must implement parse()')
if not hasattr(mapper, 'format') or not callable(mapper.format):
raise ValueError('mapper must implement format()') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup(self, cluster):
"""Deletes the inventory file used last recently used. :param cluster: cluster to clear up inventory file for :type cluster: :py:clas... |
if self._storage_path and os.path.exists(self._storage_path):
fname = '%s.%s' % (AnsibleSetupProvider.inventory_file_ending,
cluster.name)
inventory_path = os.path.join(self._storage_path, fname)
if os.path.exists(inventory_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 based_on(self, based_on):
"""Sets the based_on of this TaxRate. :param based_on: The based_on of this TaxRate. :type: str """ |
allowed_values = ["shippingAddress", "billingAddress"]
if based_on is not None and based_on not in allowed_values:
raise ValueError(
"Invalid value for `based_on` ({0}), must be one of {1}"
.format(based_on, allowed_values)
)
self._based_... |
<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_append_file_task(urllocation, filelocation):
"""Build a task to watch a specific remote url and append that data to the file. This method should be use... |
config = file_utils.get_celcius_config()
basename = filelocation.split('/')[-1]
tmp_filelocation = filelocation.replace(basename, 'tmp_'+basename)
new_filelocation = filelocation.replace(basename, 'new_'+basename)
if config['retrieve_command'] == 'curl':
download_cmd = curl.build_download... |
<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_memory_database_interface(self) -> GraphDatabaseInterface: """ Creates and returns the in-memory database interface the graph will use. """ |
Base = declarative_base()
engine = sqlalchemy.create_engine("sqlite://", poolclass=StaticPool)
Session = sessionmaker(bind=engine)
dbi: GraphDatabaseInterface = create_graph_database_interface(
sqlalchemy, Session(), Base, sqlalchemy.orm.relationship
)
Base... |
<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_node(self, index: int, name: str, external_id: Optional[str] = None) -> IGraphNode: """ Returns a new `IGraphNode` instance with the given index and n... |
return IGraphNode(graph=self._graph, index=index, name=name, external_id=external_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self):
"""Parse the table data string into records.""" |
self.parse_fields()
records = []
for line in self.t['data'].split('\n'):
if EMPTY_ROW.match(line):
continue
row = [self.autoconvert(line[start_field:end_field+1])
for start_field, end_field in self.fields]
records.append(tu... |
<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_fields(self):
"""Determine the start and end columns and names of the fields.""" |
rule = self.t['toprule'].rstrip() # keep leading space for correct columns!!
if not (rule == self.t['midrule'].rstrip() and rule == self.t['botrule'].rstrip()):
raise ParseError("Table rules differ from each other (check white space).")
names = self.t['fields'].split()
nfi... |
<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_arguments_compatibility(the_callable, argd):
""" Check if calling the_callable with the given arguments would be correct or not. ok failed Basically th... |
if not argd:
argd = {}
args, dummy, varkw, defaults = inspect.getargspec(the_callable)
tmp_args = list(args)
optional_args = []
args_dict = {}
if defaults:
defaults = list(defaults)
else:
defaults = []
while defaults:
arg = tmp_args.pop()
optional... |
<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(self, text, color=None, **kwargs):
"""print text with given color to terminal """ |
COLORS = {
'red': '\033[91m{}\033[00m',
'green': '\033[92m{}\033[00m',
'yellow': '\033[93m{}\033[00m',
'cyan': '\033[96m{}\033[00m'
}
_ = COLORS[color]
six.print_(_.format(text), **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 _is_unique(self, name, path):
"""verify if there is a project with given name or path on the database """ |
project = None
try:
project = Project.select().where(
(Project.name == name) |
(Project.path == path)
)[0]
except:
pass
return project is 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 add(self, name, path=None, **kwargs):
"""add new project with given name and path to database if the path is not given, current working directory will be tak... |
path = path or kwargs.pop('default_path', None)
if not self._path_is_valid(path):
return
if not self._is_unique(name, path):
p = Project.select().where(
(Project.name == name) |
(Project.path == path)
)[0]
self._p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self, **kwargs):
"""displays all projects on database """ |
projects = Project.select().order_by(Project.name)
if len(projects) == 0:
self._print('No projects available', 'yellow')
return
for project in projects:
project_repr = self._PROJECT_ITEM.format(project.name, project.path)
row = '- {}'.format(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 parent_tags(self):
"""Provides tags of all parent HTML elements.""" |
tags = set()
for addr in self._addresses:
if addr.attr == 'text':
tags.add(addr.element.tag)
tags.update(el.tag for el in addr.element.iterancestors())
tags.discard(HTMLFragment._root_tag)
return frozenset(tags) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def involved_tags(self):
"""Provides all HTML tags directly involved in this string.""" |
if len(self._addresses) < 2:
# there can't be a tag boundary if there's only 1 or 0 characters
return frozenset()
# creating 'parent_sets' mapping, where the first item in tuple
# is the address of character and the second is set
# of character's parent HTML ele... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse(self, html):
"""Parse given string as HTML and return it's etree representation.""" |
if self._has_body_re.search(html):
tree = lxml.html.document_fromstring(html).find('.//body')
self.has_body = True
else:
tree = lxml.html.fragment_fromstring(html,
create_parent=self._root_tag)
if tree.tag != ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _iter_texts(self, tree):
"""Iterates over texts in given HTML tree.""" |
skip = (
not isinstance(tree, lxml.html.HtmlElement) # comments, etc.
or tree.tag in self.skipped_tags
)
if not skip:
if tree.text:
yield Text(tree.text, tree, 'text')
for child in tree:
for text in self._iter_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 _analyze_tree(self, tree):
"""Analyze given tree and create mapping of indexes to character addresses. """ |
addresses = []
for text in self._iter_texts(tree):
for i, char in enumerate(text.content):
if char in whitespace:
char = ' '
addresses.append(CharAddress(char, text.element, text.attr, i))
# remove leading and trailing whitespace
... |
<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_index(self, index):
"""Validates given index, eventually raises errors.""" |
if isinstance(index, slice):
if index.step and index.step != 1:
raise IndexError('Step is not allowed.')
indexes = (index.start, index.stop)
else:
indexes = (index,)
for index in indexes:
if index is not None and index < 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 _find_pivot_addr(self, index):
"""Inserting by slicing can lead into situation where no addresses are selected. In that case a pivot address has to be chosen... |
if not self.addresses or index.start == 0:
return CharAddress('', self.tree, 'text', -1) # string beginning
if index.start > len(self.addresses):
return self.addresses[-1]
return self.addresses[index.start] |
<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_api_key(email, api_key):
"""Check the API key of the user.""" |
table = boto3.resource("dynamodb").Table(os.environ['people'])
user = table.get_item(Key={'email': email})
if not user:
return False
user = user.get("Item")
if api_key != user.get('api_key', None):
return False
return user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace(html, replacements=None):
"""Performs replacements on given HTML string.""" |
if not replacements:
return html # no replacements
html = HTMLFragment(html)
for r in replacements:
r.replace(html)
return unicode(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 _is_replacement_allowed(self, s):
"""Tests whether replacement is allowed on given piece of HTML text.""" |
if any(tag in s.parent_tags for tag in self.skipped_tags):
return False
if any(tag not in self.textflow_tags for tag in s.involved_tags):
return False
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 replace(self, html):
"""Perform replacements on given HTML fragment.""" |
self.html = html
text = html.text()
positions = []
def perform_replacement(match):
offset = sum(positions)
start, stop = match.start() + offset, match.end() + offset
s = self.html[start:stop]
if self._is_replacement_allowed(s):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_relative_file(filename, relative_to=None):
"""Returns contents of the given file, which path is supposed relative to this package.""" |
if relative_to is None:
relative_to = os.path.dirname(__file__)
with open(os.path.join(os.path.dirname(relative_to), filename)) as f:
return f.read() |
<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_events(self):
"""Get events from the cloud node.""" |
to_send = {'limit': 50}
response = self._send_data('POST', 'admin', 'get-events', to_send)
output = {'message': ""}
for event in response['events']:
desc = "Source IP: {ip}\n"
desc += "Datetime: {time}\n"
desc += "Indicator: {match}\n"
de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flush_events(self):
"""Flush events from the cloud node.""" |
response = self._send_data('DELETE', 'admin', 'flush-events', {})
if response['success']:
msg = "Events flushed"
else:
msg = "Flushing of events failed"
output = {'message': msg}
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 put(self):
"""Push the info represented by this ``Metric`` to CloudWatch.""" |
try:
self.cloudwatch.put_metric_data(
Namespace=self.namespace,
MetricData=[{
'MetricName': self.name,
'Value': self.value,
'Timestamp': self.timestamp
}]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log(self, message, level=logging.INFO, *args, **kwargs):
""" Send log entry :param str message: log message :param int level: `Logging level <https://docs.py... |
msg = "{}.{}: {}[{}]: {}".format(
self.__class__.__name__, self.status, self.__class__.path,
self.uuid, message
)
extra = kwargs.pop("extra", dict())
extra.update(dict(kmsg=Message(
self.uuid, entrypoint=self.__class__.path, params=self.params,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect(self):
""" Connect to a RabbitMQ instance :returns: Boolean corresponding to success of connection :rtype: bool """ |
logger.info("Connecting to rabbit")
for url in self._urls:
try:
self._connection = pika.BlockingConnection(pika.URLParameters(url))
self._channel = self._connection.channel()
self._declare()
if self._confirm_delivery:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _disconnect(self):
""" Cleanly close a RabbitMQ connection. :returns: None """ |
try:
self._connection.close()
logger.debug("Disconnected from rabbit")
except Exception:
logger.exception("Unable to close 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 publish_message(self, message, content_type=None, headers=None, mandatory=False, immediate=False):
""" Publish a response message to a RabbitMQ instance. :pa... |
logger.debug("Publishing message")
try:
self._connect()
return self._do_publish(mandatory=mandatory,
immediate=immediate,
content_type=content_type,
headers=headers,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit(folder, provenance_id, step_name, previous_step_id=None, config=None, db_url=None, is_organised=True):
"""Record all files from a folder into the datab... |
config = config if config else []
logging.info("Visiting %s", folder)
logging.info("-> is_organised=%s", str(is_organised))
logging.info("-> config=%s", str(config))
logging.info("Connecting to database...")
db_conn = connection.Connection(db_url)
step_id = _create_step(db_conn, step_nam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_sockets(self):
'''
Check for new messages on sockets and respond accordingly.
.. versionchanged:: 0.11.3
Update routes table by setting ``df_routes`` property of
:attr:`parent.canvas_slave`.
.. versionchanged:: 0.12
Update ``dynamic_electr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def follow_cf(save, Uspan, target_cf, nup, n_tot=5.0, slsp=None):
"""Calculates the quasiparticle weight in single site spin hamiltonian under with N degenerate ... |
if slsp == None:
slsp = Spinon(slaves=6, orbitals=3, avg_particles=n_tot,
hopping=[0.5]*6, populations = np.asarray([n_tot]*6)/6)
zet, lam, mu, mean_f = [], [], [], []
for co in Uspan:
print('U=', co, 'del=', target_cf)
res=root(targetpop, nup[-1],(co,targe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def targetpop(upper_density, coul, target_cf, slsp, n_tot):
"""restriction on finding the right populations that leave the crystal field same""" |
if upper_density < 0.503: return 0.
trypops=population_distri(upper_density, n_tot)
slsp.set_filling(trypops)
slsp.selfconsistency(coul,0)
efm_free = dos_bethe_find_crystalfield(trypops, slsp.param['hopping'])
orb_ener = slsp.param['lambda']+ slsp.quasiparticle_weight()*efm_free
obtained_cf... |
<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(self, filename=None):
"""Method was overriden to set spectrum.filename as well""" |
DataFile.load(self, filename)
self.spectrum.filename = filename |
<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_save_as(self, filename):
"""Saves spectrum back to FITS file.""" |
if len(self.spectrum.x) < 2:
raise RuntimeError("Spectrum must have at least two points")
if os.path.isfile(filename):
os.unlink(filename) # PyFITS does not overwrite file
hdu = self.spectrum.to_hdu()
overwrite_fits(hdu, filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matches():
"""This resource returns a list of the currently running WvW matches, with the participating worlds included in the result. Further details about ... |
wvw_matches = get_cached("wvw/matches.json", False).get("wvw_matches")
for match in wvw_matches:
match["start_time"] = parse_datetime(match["start_time"])
match["end_time"] = parse_datetime(match["end_time"])
return wvw_matches |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def objective_names(lang="en"):
"""This resource returns a list of the localized WvW objective names for the specified language. :param lang: The language to que... |
params = {"lang": lang}
cache_name = "objective_names.%(lang)s.json" % params
data = get_cached("wvw/objective_names.json", cache_name, params=params)
return dict([(objective["id"], objective["name"]) for objective in 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 _parse_data(self, data, charset):
""" Parse the xml data into dictionary. """ |
builder = TreeBuilder(numbermode=self._numbermode)
if isinstance(data,basestring):
xml.sax.parseString(data, builder)
else:
xml.sax.parse(data, builder)
return builder.root[self._root_element_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 _format_data(self, data, charset):
""" Format data into XML. """ |
if data is None or data == '':
return u''
stream = StringIO.StringIO()
xml = SimplerXMLGenerator(stream, charset)
xml.startDocument()
xml.startElement(self._root_element_name(), {})
self._to_xml(xml, data)
xml.endElement(self._root_element_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 _to_xml(self, xml, data, key=None):
""" Recursively convert the data into xml. This function was originally copied from the `Piston project <https://bitbucke... |
if isinstance(data, (list, tuple)):
for item in data:
elemname = self._list_item_element_name(key)
xml.startElement(elemname, {})
self._to_xml(xml, item)
xml.endElement(elemname)
elif isinstance(data, dict):
for ke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def startElement(self, name, attrs):
""" Initialize new node and store current node into stack. """ |
self.stack.append((self.current, self.chardata))
self.current = {}
self.chardata = [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def endElement(self, name):
""" End current xml element, parse and add to to parent node. """ |
if self.current:
# we have nested elements
obj = self.current
else:
# text only node
text = ''.join(self.chardata).strip()
obj = self._parse_node_data(text)
newcurrent, self.chardata = self.stack.pop()
self.current = self._elem... |
<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_node_data(self, data):
""" Parse the value of a node. Override to provide your own parsing. """ |
data = data or ''
if self.numbermode == 'basic':
return self._try_parse_basic_number(data)
elif self.numbermode == 'decimal':
return self._try_parse_decimal(data)
else:
return 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 _try_parse_basic_number(self, data):
""" Try to convert the data into ``int`` or ``float``. :returns: ``Decimal`` or ``data`` if conversion fails. """ |
# try int first
try:
return int(data)
except ValueError:
pass
# try float next
try:
return float(data)
except ValueError:
pass
# no luck, return data as it is
return 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 apize_raw(url, method='GET'):
""" Convert data and params dict -> json. """ |
def decorator(func):
def wrapper(*args, **kwargs):
elem = func(*args, **kwargs)
if type(elem) is not dict:
raise BadReturnVarType(func.__name__)
response = send_request(url, method,
elem.get('data', {}),
elem.get('args', {}),
elem.get('params', {}),
elem.get('headers', {}),
elem.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_version(path):
""" Reads the file at the specified path and returns the version contained in it. This is meant for reading the __init__.py file insid... |
# Regular expression for the version
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open(path + '__init__.py', 'r', encoding='utf-8') as f:
version = f.read()
if version:
version = _version_re.search(version)
if version:
version = version.group(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 _make_connect(module, args, kwargs):
""" Returns a function capable of making connections with a particular driver given the supplied credentials. """ |
# pylint: disable-msg=W0142
return functools.partial(module.connect, *args, **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 create_pool(module, max_conns, *args, **kwargs):
""" Create a connection pool appropriate to the driver module's capabilities. """ |
if not hasattr(module, 'threadsafety'):
raise NotSupported("Cannot determine driver threadsafety.")
if max_conns < 1:
raise ValueError("Minimum number of connections is 1.")
if module.threadsafety >= 2:
return Pool(module, max_conns, *args, **kwargs)
if module.threadsafety >= 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 transactional(wrapped):
""" A decorator to denote that the content of the decorated function or method is to be ran in a transaction. The following code is e... |
# pylint: disable-msg=C0111
def wrapper(*args, **kwargs):
with Context.current().transaction():
return wrapped(*args, **kwargs)
return functools.update_wrapper(wrapper, wrapped) |
<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(stmt, args=()):
""" Execute an SQL statement. Returns the number of affected rows. """ |
ctx = Context.current()
with ctx.mdr:
cursor = ctx.execute(stmt, args)
row_count = cursor.rowcount
_safe_close(cursor)
return row_count |
<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(stmt, args=(), factory=None):
""" Execute a query. This returns an iterator of the result set. """ |
ctx = Context.current()
factory = ctx.default_factory if factory is None else factory
with ctx.mdr:
return factory(ctx.execute(stmt, args), ctx.mdr) |
<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_row(stmt, args=(), factory=None):
""" Execute a query. Returns the first row of the result set, or `None`. """ |
for row in query(stmt, args, factory):
return row
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 query_value(stmt, args=(), default=None):
""" Execute a query, returning the first value in the first row of the result set. If the query returns no result s... |
for row in query(stmt, args, TupleFactory):
return row[0]
return default |
<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_proc(procname, args=()):
""" Execute a stored procedure. Returns the number of affected rows. """ |
ctx = Context.current()
with ctx.mdr:
cursor = ctx.execute_proc(procname, args)
row_count = cursor.rowcount
_safe_close(cursor)
return row_count |
<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_proc(procname, args=(), factory=None):
""" Execute a stored procedure. This returns an iterator of the result set. """ |
ctx = Context.current()
factory = ctx.default_factory if factory is None else factory
with ctx.mdr:
return factory(ctx.execute_proc(procname, args), ctx.mdr) |
<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_proc_row(procname, args=(), factory=None):
""" Execute a stored procedure. Returns the first row of the result set, or `None`. """ |
for row in query_proc(procname, args, factory):
return row
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 query_proc_value(procname, args=(), default=None):
""" Execute a stored procedure, returning the first value in the first row of the result set. If it return... |
for row in query_proc(procname, args, TupleFactory):
return row[0]
return default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_placeholders(seq, start=1):
""" Generate placeholders for the given sequence. """ |
if len(seq) == 0:
raise ValueError('Sequence must have at least one element.')
param_style = Context.current().param_style
placeholders = None
if isinstance(seq, dict):
if param_style in ('named', 'pyformat'):
template = ':%s' if param_style == 'named' else '%%(%s)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 make_file_object_logger(fh):
""" Make a logger that logs to the given file object. """ |
def logger_func(stmt, args, fh=fh):
"""
A logger that logs everything sent to a file object.
"""
now = datetime.datetime.now()
six.print_("Executing (%s):" % now.isoformat(), file=fh)
six.print_(textwrap.dedent(stmt), file=fh)
six.print_("Arguments:", file=fh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def current(cls, with_exception=True):
""" Returns the current database context. """ |
if with_exception and len(cls.stack) == 0:
raise NoContext()
return cls.stack.top() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transaction(self):
""" Sets up a context where all the statements within it are ran within a single database transaction. For internal use only. """ |
# The idea here is to fake the nesting of transactions. Only when
# we've gotten back to the topmost transaction context do we actually
# commit or rollback.
with self.mdr:
try:
self._depth += 1
yield self
self._depth -= 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 cursor(self):
""" Get a cursor for the current connection. For internal use only. """ |
cursor = self.mdr.cursor()
with self.transaction():
try:
yield cursor
if cursor.rowcount != -1:
self.last_row_count = cursor.rowcount
self.last_row_id = getattr(cursor, 'lastrowid', None)
except:
... |
<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, stmt, args):
""" Execute a statement, returning a cursor. For internal use only. """ |
self.logger(stmt, args)
with self.cursor() as cursor:
cursor.execute(stmt, args)
return cursor |
<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_proc(self, procname, args):
""" Execute a stored procedure, returning a cursor. For internal use only. """ |
self.logger(procname, args)
with self.cursor() as cursor:
cursor.callproc(procname, args)
return cursor |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
""" Close the connection this context wraps. """ |
self.logger = None
for exc in _EXCEPTIONS:
setattr(self, exc, None)
try:
self.mdr.close()
finally:
self.mdr = 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 connect(self):
""" Returns a context that uses this pool as a connection source. """ |
ctx = Context(self.module, self.create_mediator())
ctx.logger = self.logger
ctx.default_factory = self.default_factory
return ctx |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
""" Release all resources associated with this factory. """ |
if self.mdr is None:
return
exc = (None, None, None)
try:
self.cursor.close()
except:
exc = sys.exc_info()
try:
if self.mdr.__exit__(*exc):
exc = (None, None, None)
except:
exc = sys.exc_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 add_item(cls, item, **kwargs):
"""Add item. Add new item to the shopping cart. This method makes a synchronous HTTP request by default. To make an asynchrono... |
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._add_item_with_http_info(item, **kwargs)
else:
(data) = cls._add_item_with_http_info(item, **kwargs)
return 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 checkout(cls, order, **kwargs):
"""Checkout cart. Checkout cart, Making an order. This method makes a synchronous HTTP request by default. To make an asynchr... |
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._checkout_with_http_info(order, **kwargs)
else:
(data) = cls._checkout_with_http_info(order, **kwargs)
return 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 delete_item(cls, item_id, **kwargs):
"""Remove item. Remove item from shopping cart This method makes a synchronous HTTP request by default. To make an async... |
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_item_with_http_info(item_id, **kwargs)
else:
(data) = cls._delete_item_with_http_info(item_id, **kwargs)
return 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 empty(cls, **kwargs):
"""Empty cart. Empty the shopping cart. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, ... |
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._empty_with_http_info(**kwargs)
else:
(data) = cls._empty_with_http_info(**kwargs)
return 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(cls, **kwargs):
"""Get cart. Retrieve the shopping cart of the current session. This method makes a synchronous HTTP request by default. To make an async... |
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_with_http_info(**kwargs)
else:
(data) = cls._get_with_http_info(**kwargs)
return 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 update_item(cls, item_id, item, **kwargs):
"""Update cart. Update cart item. This method makes a synchronous HTTP request by default. To make an asynchronous... |
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_item_with_http_info(item_id, item, **kwargs)
else:
(data) = cls._update_item_with_http_info(item_id, item, **kwargs)
return 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_perm_names(cls, resource):
""" Return all permissions supported by the resource. This is used for auto-generating missing permissions rows into database ... |
return [cls.get_perm_name(resource, method) for method in cls.METHODS] |
<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_perm_name(cls, resource, method):
""" Compose permission name @param resource the resource @param method the request method (case doesn't matter). """ |
return '%s_%s_%s' % (
cls.PREFIX,
cls._get_resource_name(resource),
method.lower()) |
<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_perm(self, user, permission):
""" Check whether the user has the given permission @return True if user is granted with access, False if not. """ |
if user.is_superuser:
return True
if user.is_active:
perms = [perm.split('.')[1] for perm in user.get_all_permissions()]
return permission in perms
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 is_local_url(target):
"""Determine if URL is a local.""" |
ref_url = urlparse(cfg.get('CFG_SITE_SECURE_URL'))
test_url = urlparse(urljoin(cfg.get('CFG_SITE_SECURE_URL'), target))
return test_url.scheme in ('http', 'https') and \
ref_url.netloc == test_url.netloc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rewrite_to_secure_url(url, secure_base=None):
""" Rewrite URL to a Secure URL @param url URL to be rewritten to a secure URL. @param secure_base: Base URL of... |
if secure_base is None:
secure_base = cfg.get('CFG_SITE_SECURE_URL')
url_parts = list(urlparse(url))
url_secure_parts = urlparse(secure_base)
url_parts[0] = url_secure_parts[0]
url_parts[1] = url_secure_parts[1]
return urlunparse(url_parts) |
<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_html_link(urlbase, urlargd, link_label, linkattrd=None, escape_urlargd=True, escape_linkattrd=True, urlhash=None):
"""Creates a W3C compliant link. @p... |
attributes_separator = ' '
output = '<a href="' + \
create_url(urlbase, urlargd, escape_urlargd, urlhash) + '"'
if linkattrd:
output += ' '
if escape_linkattrd:
attributes = [escape(str(key), quote=True) + '="' +
escape(str(linkattrd[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 get_canonical_and_alternates_urls( url, drop_ln=True, washed_argd=None, quote_path=False):
""" Given an Invenio URL returns a tuple with two elements. The fi... |
dummy_scheme, dummy_netloc, path, dummy_params, query, fragment = urlparse(
url)
canonical_scheme, canonical_netloc = urlparse(cfg.get('CFG_SITE_URL'))[0:2]
parsed_query = washed_argd or parse_qsl(query)
no_ln_parsed_query = [(key, value)
for (key, value) in parsed_que... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def same_urls_p(a, b):
""" Compare two URLs, ignoring reorganizing of query arguments """ |
ua = list(urlparse(a))
ub = list(urlparse(b))
ua[4] = parse_qs(ua[4])
ub[4] = parse_qs(ub[4])
return ua == ub |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_user_agent_string(component=None):
""" Return a nice and uniform user-agent string to be used when Invenio act as a client in HTTP requests. """ |
ret = "Invenio-%s (+%s; \"%s\")" % (cfg.get('CFG_VERSION'),
cfg.get('CFG_SITE_URL'), cfg.get('CFG_SITE_NAME'))
if component:
ret += " %s" % component
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 make_invenio_opener(component=None):
""" Return an urllib2 opener with the useragent already set in the appropriate way. """ |
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', make_user_agent_string(component))]
return opener |
<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_Indico_request_url( base_url, indico_what, indico_loc, indico_id, indico_type, indico_params, indico_key, indico_sig, _timestamp=None):
""" Create a s... |
url = '/export/' + indico_what + '/'
if indico_loc:
url += indico_loc + '/'
if type(indico_id) in (list, tuple):
# dash separated list of values
indico_id = '-'.join([str(x) for x in indico_id])
url += indico_id + '.' + str(indico_type)
if hasattr(indico_params, '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 auto_version_url(file_path):
""" Appends modification time of the file to the request URL in order for the browser to refresh the cache when file changes @pa... |
file_md5 = ""
try:
file_md5 = md5(open(cfg.get('CFG_WEBDIR') +
os.sep + file_path).read()).hexdigest()
except IOError:
pass
return file_path + "?%s" % file_md5 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def function_arg_count(fn):
""" returns how many arguments a funciton has """ |
assert callable(fn), 'function_arg_count needed a callable function, not {0}'.format(repr(fn))
if hasattr(fn, '__code__') and hasattr(fn.__code__, 'co_argcount'):
return fn.__code__.co_argcount
else:
return 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 merge(left, right, how='inner', key=None, left_key=None, right_key=None, left_as='left', right_as='right'):
""" Performs a join using the union join function... |
return join(left, right, how, key, left_key, right_key,
join_fn=make_union_join(left_as, right_as)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _inner_join(left, right, left_key_fn, right_key_fn, join_fn=union_join):
""" Inner join using left and right key functions :param left: left iterable to be j... |
joiner = defaultdict(list)
for ele in right:
joiner[right_key_fn(ele)].append(ele)
joined = []
for ele in left:
for other in joiner[left_key_fn(ele)]:
joined.append(join_fn(ele, other))
return joined |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def group(iterable, key=lambda ele: ele):
""" Groups an iterable by a specified attribute, or using a specified key access function. Returns tuples of grouped el... |
if callable(key):
return _group(iterable, key)
else:
return _group(iterable, make_key_fn(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 trigger_keyphrases( text = None, # input text to parse keyphrases = None, # keyphrases for parsing input text response = None, # optional text response on tri... |
if any(pattern in text for pattern in keyphrases):
if confirm:
return confirmation(
prompt = confirmation_prompt,
feedback_confirm = confirmation_feedback_confirm,
feedback_deny = confirmation_feedback_deny,
function ... |
<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( text = None, humour = 75 ):
""" Parse input text using various triggers, some returning text and some for engaging functions. If triggered, a trigger ... |
triggers = []
# general
if humour >= 75:
triggers.extend([
trigger_keyphrases(
text = text,
keyphrases = [
"image"
],
response = "http://i.imgur.com/MiqrlTh.jpg"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multiparse( text = None, parsers = [parse], help_message = None ):
""" Parse input text by looping over a list of multiple parsers. If one trigger is trigger... |
responses = []
for _parser in parsers:
response = _parser(text = text)
if response is not False:
responses.extend(response if response is list else [response])
if not any(responses):
if help_message:
return help_message
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 run( self ):
""" Engage contained function with optional keyword arguments. """ |
if self._function and not self._kwargs:
return self._function()
if self._function and self._kwargs:
return self._function(**self._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 tax_class_based_on(self, tax_class_based_on):
"""Sets the tax_class_based_on of this TaxSettings. :param tax_class_based_on: The tax_class_based_on of this T... |
allowed_values = ["shippingAddress", "billingAddress"] # noqa: E501
if tax_class_based_on is not None and tax_class_based_on not in allowed_values:
raise ValueError(
"Invalid value for `tax_class_based_on` ({0}), must be one of {1}" # noqa: E501
.format(tax... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recurse_up(directory, filename):
""" Recursive walk a directory up to root until it contains `filename` """ |
directory = osp.abspath(directory)
while True:
searchfile = osp.join(directory, filename)
if osp.isfile(searchfile):
return directory
if directory == '/': break
else: directory = osp.dirname(directory)
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 etree_to_dict(tree):
"""Translate etree into dictionary. :param tree: etree dictionary object :type tree: <http://lxml.de/api/lxml.etree-module.html> """ |
d = {tree.tag.split('}')[1]: map(
etree_to_dict, tree.iterchildren()
) or tree.text}
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def finalize_download(url, download_to_file, content_type, request):
""" Finalizes the download operation by doing various checks, such as format type, size chec... |
# If format is given, a format check is performed.
if content_type and content_type not in request.headers['content-type']:
msg = 'The downloaded file is not of the desired format'
raise InvenioFileDownloadError(msg)
# Save the downloaded file to desired or generated location.
to_file ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.