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:class:`elasticluster.cluster.Cluster` """ |
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):
try:
os.unlink(inventory_path)
if self._storage_path_tmp:
if len(os.listdir(self._storage_path)) == 0:
shutil.rmtree(self._storage_path)
except OSError as ex:
log.warning(
"AnsibileProvider: Ignoring error while deleting "
"inventory file %s: %s", inventory_path, 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 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_on = based_on |
<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 used when you would like to keep all of the information stored on the local machine, but also append the new information found at the url. For instance, if the local file is: ``` foo ``` And the remote file is: ``` bar ``` The resulting file will contain: ``` foo bar ``` """ |
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_file_command(urllocation, tmp_filelocation)
elif config['retrieve_command'] == 'wget':
download_cmd = wget.build_download_file_command(urllocation, tmp_filelocation)
else:
print("Invalid retrieve command!")
sys.exit(1)
diff_cmd = diff.build_append_file_command(filelocation, tmp_filelocation)
compare_cmd = concat.build_and_concat_commands([download_cmd, diff_cmd])
redirect_cmd = redirect.redirect_output(compare_cmd, new_filelocation)
full_cmd = concat.concat_commands([touch.touch(filelocation).build_command(), redirect_cmd, rm.build_force_rm_command(tmp_filelocation).build_command(), rm.build_force_rm_command(filelocation).build_command(), mv.mv(new_filelocation, filelocation).build_command()])
return full_cmd |
<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.metadata.drop_all(engine)
Base.metadata.create_all(engine)
return dbi |
<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 name. Arguments: index (int):
The index of the node to create. name (str):
The name of the node to create. external_id (Optional[str]):
The external ID of the node. """ |
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(tuple(row))
self.records = records |
<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()
nfields = len(rule.split())
if nfields != len(names):
raise ParseError("number of field names (%d) does not match number of fields (%d)"
% (nfields, len(names)))
fields = [] # list of tuples (first,last) column of the field
ifield = 0
is_field = rule.startswith('=') # state
len_rule = len(rule)
start_field = 0
end_field = 0
for c in xrange(len_rule):
char = rule[c]
if not is_field and char == '=':
start_field = c
is_field = True
if is_field and (char == ' ' or c == len_rule-1):
# finished field
fields.append((start_field, c))
ifield += 1
is_field = False
self.names = names
self.fields = 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 check_arguments_compatibility(the_callable, argd):
""" Check if calling the_callable with the given arguments would be correct or not. ok failed Basically this function is simulating the call: but it only checks for the correctness of the arguments, without actually calling the_callable. :param the_callable: the callable to be analyzed. :type the_callable: function/callable :param argd: the arguments to be passed. :type argd: dict :raise ValueError: in case of uncompatibility """ |
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_args.append(arg)
args_dict[arg] = defaults.pop()
while tmp_args:
args_dict[tmp_args.pop()] = None
for arg, dummy_value in iteritems(argd):
if arg in args_dict:
del args_dict[arg]
elif not varkw:
raise ValueError(
'Argument %s not expected when calling callable '
'"%s" with arguments %s' % (
arg, get_callable_signature_as_string(the_callable), argd))
for arg in args_dict.keys():
if arg in optional_args:
del args_dict[arg]
if args_dict:
raise ValueError(
'Arguments %s not specified when calling callable '
'"%s" with arguments %s' % (
', '.join(args_dict.keys()),
get_callable_signature_as_string(the_callable),
argd)) |
<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 taken """ |
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._print(self._ERROR_PROJECT_EXISTS.format(name, p.path), 'red')
return
Project.create(name=name, path=path)
self._print(self._SUCCESS_PROJECT_ADDED.format(name), 'green') |
<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._PROJECT_ITEM.format(project.name, project.path))
six.print_(row) |
<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 elements
parent_sets = []
# meanwhile we are creatingalso a set of common parents so we can
# put them away later on (we're not interested in them as
# they're only some global wrappers)
common_parents = set()
for addr in self._addresses:
parents = set()
if addr.attr == 'text':
parents.add(addr.element)
parents.update(addr.element.iterancestors())
parent_sets.append((addr, parents))
if not common_parents:
common_parents = parents
else:
common_parents &= parents
# constructing final set of involved tags
involved_tags = set()
prev_addr = None
for addr, parents in parent_sets:
parents = parents - common_parents
involved_tags.update(p.tag for p in parents)
# hidden tags - sometimes there are tags without text which
# can hide between characters, but they actually break textflow
is_tail_of_hidden = (
prev_addr and
addr.attr == 'tail' and
prev_addr.element != addr.element
)
if is_tail_of_hidden:
involved_tags.add(addr.element)
prev_addr = addr
return frozenset(involved_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 _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 != self._root_tag:
# ensure the root element exists even if not really needed,
# so the tree has always the same structure
root = lxml.html.HtmlElement()
root.tag = self._root_tag
root.append(tree)
return root
return tree |
<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_texts(child):
yield text
if tree.tail:
yield Text(tree.tail, tree, 'tail') |
<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
while addresses and addresses[0].char == ' ':
del addresses[0]
while addresses and addresses[-1].char == ' ':
del addresses[-1]
return addresses |
<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:
raise IndexError('Negative indexes are not 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 _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 so we know where to add characters. """ |
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):
repl = match.expand(self.replacement)
self.html[start:stop] = repl
else:
repl = match.group() # no replacement takes place
positions.append(match.end())
return repl
while True:
if positions:
text = text[positions[-1]:]
text, n = self.pattern.subn(perform_replacement, text, count=1)
if not n: # all is already replaced
break |
<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"
desc += "Method: {method}\n"
desc += "URL: {url}\n"
desc += "Request Type: {type}\n"
desc += "User-Agent: {userAgent}\n"
desc += "Contact: {contact}\n"
desc += "\n"
output['message'] += desc.format(**event)
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 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
}]
)
except Exception:
logging.exception("Error pushing {0} to CloudWatch.".format(str(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 log(self, message, level=logging.INFO, *args, **kwargs):
""" Send log entry :param str message: log message :param int level: `Logging level <https://docs.python.org/3/library/logging.html#levels>`_ :param list args: log record arguments :param dict kwargs: log record key argument """ |
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,
metadata=self.metadata
).dump()))
return logger.log(
level=level, msg=msg, extra=extra, *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 _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:
self._channel.confirm_delivery()
logger.info("Enabled delivery confirmation")
logger.debug("Connected to rabbit")
return True
except pika.exceptions.AMQPConnectionError:
logger.exception("Unable to connect to rabbit")
continue
except Exception:
logger.exception("Unexpected exception connecting to rabbit")
continue
raise pika.exceptions.AMQPConnectionError |
<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. :param message: Response message :param content_type: Pika BasicProperties content_type value :param headers: Message header properties :param mandatory: The mandatory flag :param immediate: The immediate flag :returns: Boolean corresponding to the success of publishing :rtype: bool """ |
logger.debug("Publishing message")
try:
self._connect()
return self._do_publish(mandatory=mandatory,
immediate=immediate,
content_type=content_type,
headers=headers,
message=message)
except pika.exceptions.AMQPConnectionError:
logger.error("AMQPConnectionError occurred. Message not published.")
raise PublishMessageError
except NackError:
# raised when a message published in publisher-acknowledgments mode
# is returned via `Basic.Return` followed by `Basic.Ack`.
logger.error("NackError occurred. Message not published.")
raise PublishMessageError
except UnroutableError:
# raised when a message published in publisher-acknowledgments
# mode is returned via `Basic.Return` followed by `Basic.Ack`.
logger.error("UnroutableError occurred. Message not published.")
raise PublishMessageError
except Exception:
logger.exception("Unknown exception occurred. Message not published.")
raise PublishMessageError |
<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 database. Note: If a file has been copied from a previous processing step without any transformation, it will be detected and (e.g. a DICOM file) contains some meta-data, those will be stored in the DB. Arguments: :param folder: folder path. :param provenance_id: provenance label. :param step_name: Name of the processing step that produced the folder to visit. :param previous_step_id: (optional) previous processing step ID. If not defined, we assume this is the first processing step. :param config: List of flags: - boost: (optional) When enabled, we consider that all the files from a same folder share the same meta-data. When enabled, the processing is (about 2 times) faster. This option is enabled by default. - session_id_by_patient: Rarely, a data set might use study IDs which are unique by patient (not for the whole study). E.g.: LREN data. In such a case, you have to enable this flag. This will use PatientID + StudyID as a session ID. - visit_id_in_patient_id: Rarely, a data set might mix patient IDs and visit IDs. E.g. : LREN data. In such a case, you have to enable this flag. This will try to split PatientID into VisitID and PatientID. - visit_id_from_path: Enable this flag to get the visit ID from the folder hierarchy instead of DICOM meta-data (e.g. can be useful for PPMI). - repetition_from_path: Enable this flag to get the repetition ID from the folder hierarchy instead of DICOM meta-data (e.g. can be useful for PPMI). :param db_url: (optional) Database URL. If not defined, it looks for an Airflow configuration file. :param is_organised: (optional) Disable this flag when scanning a folder that has not been organised yet (should only affect nifti files). :return: return processing step ID. """ |
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_name, provenance_id, previous_step_id)
previous_files_hash = _get_files_hash_from_step(db_conn, previous_step_id)
checked = dict()
def process_file(file_path):
logging.debug("Processing '%s'" % file_path)
file_type = _find_type(file_path)
if "DICOM" == file_type:
is_copy = _hash_file(file_path) in previous_files_hash
leaf_folder = os.path.split(file_path)[0]
if leaf_folder not in checked or 'boost' not in config:
ret = dicom_import.dicom2db(file_path, file_type, is_copy, step_id, db_conn,
'session_id_by_patient' in config, 'visit_id_in_patient_id' in config,
'visit_id_in_patient_id' in config, 'repetition_from_path' in config)
try:
checked[leaf_folder] = ret['repetition_id']
except KeyError:
# TODO: Remove it when dicom2db will be more stable
logging.warning("Cannot find repetition ID !")
else:
dicom_import.extract_dicom(
file_path, file_type, is_copy, checked[leaf_folder], step_id)
elif "NIFTI" == file_type and is_organised:
is_copy = _hash_file(file_path) in previous_files_hash
nifti_import.nifti2db(file_path, file_type, is_copy, step_id, db_conn, 'session_id_by_patient' in config,
'visit_id_in_patient_id' in config)
elif file_type:
is_copy = _hash_file(file_path) in previous_files_hash
others_import.others2db(
file_path, file_type, is_copy, step_id, db_conn)
if sys.version_info.major == 3 and sys.version_info.minor < 5:
matches = []
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, '*'):
matches.append(os.path.join(root, filename))
for file_path in matches:
process_file(file_path)
else:
for file_path in glob.iglob(os.path.join(folder, "**/*"), recursive=True):
process_file(file_path)
logging.info("Closing database connection...")
db_conn.close()
return step_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 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_electrode_state_shapes`` layer of
:attr:`parent.canvas_slave` when dynamic electrode actuation states
change.
.. versionchanged:: 0.13
Update local global, electrode, and route command lists in response
to ``microdrop.command_plugin`` messages.
'''
try:
msg_frames = (self.command_socket
.recv_multipart(zmq.NOBLOCK))
except zmq.Again:
pass
else:
self.on_command_recv(msg_frames)
try:
msg_frames = (self.subscribe_socket
.recv_multipart(zmq.NOBLOCK))
source, target, msg_type, msg_json = msg_frames
if ((source == 'microdrop.device_info_plugin') and
(msg_type == 'execute_reply')):
msg = json.loads(msg_json)
if msg['content']['command'] == 'get_device':
data = decode_content_data(msg)
if data is not None:
self.parent.on_device_loaded(data)
elif ((source == 'microdrop.electrode_controller_plugin') and
(msg_type == 'execute_reply')):
msg = json.loads(msg_json)
if msg['content']['command'] in ('set_electrode_state',
'set_electrode_states'):
data = decode_content_data(msg)
if data is None:
print msg
else:
#self.emit('electrode-states-updated', data)
self.parent.on_electrode_states_updated(data)
elif msg['content']['command'] == 'get_channel_states':
data = decode_content_data(msg)
if data is None:
print msg
else:
#self.emit('electrode-states-set', data)
self.parent.on_electrode_states_set(data)
elif ((source == 'droplet_planning_plugin') and
(msg_type == 'execute_reply')):
msg = json.loads(msg_json)
if msg['content']['command'] in ('add_route', ):
self.execute_async('droplet_planning_plugin',
'get_routes')
elif msg['content']['command'] in ('get_routes', ):
data = decode_content_data(msg)
self.parent.canvas_slave.df_routes = data
elif ((source == 'microdrop.command_plugin') and
(msg_type == 'execute_reply')):
msg = json.loads(msg_json)
if msg['content']['command'] in ('get_commands',
'unregister_command',
'register_command'):
df_commands = decode_content_data(msg).set_index('namespace')
for group_i, df_i in df_commands.groupby('namespace'):
register = getattr(self.parent.canvas_slave,
'register_%s_command' % group_i,
None)
if register is None:
continue
else:
for j, command_ij in df_i.iterrows():
register(command_ij.command_name,
title=command_ij.title,
group=command_ij.plugin_name)
_L().debug('registered %s command: `%s`',
group_i, command_ij)
else:
self.most_recent = msg_json
except zmq.Again:
pass
except:
logger.error('Error processing message from subscription '
'socket.', exc_info=True)
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 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 half-filled orbitals """ |
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,target_cf,slsp, n_tot))
print(res.x)
if res.x>nup[-1]: break
nup.append(res.x)
slsp.param['populations']=population_distri(nup[-1])
mean_f.append(slsp.mean_field())
zet.append(slsp.quasiparticle_weight())
lam.append(slsp.param['lambda'])
mu.append(orbital_energies(slsp.param, zet[-1]))
# plt.plot(np.asarray(zet)[:,0], label='d={}, zl'.format(str(target_cf)))
# plt.plot(np.asarray(zet)[:,5], label='d={}, zh'.format(str(target_cf)))
case = save.createGroup('cf={}'.format(target_cf))
varis = st.setgroup(case)
st.storegroup(varis, Uspan[:len(zet)], zet, lam, mu, nup[1:],target_cf,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 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 = orb_ener[5] - orb_ener[0]
return target_cf - 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 a match can be requested using the ``match_details`` function. The response is a list of match objects, each of which contains the following properties: wvw_match_id (string):
The WvW match id. red_world_id (number):
The world id of the red world. blue_world_id (number):
The world id of the blue world. green_world_id (number):
The world id of the green world. start_time (datetime):
A timestamp of when the match started. end_time (datetime):
A timestamp of when the match ends. """ |
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 query the names for. :return: A dictionary mapping the objective Ids to the names. *Note that these are not the names displayed in the game, but rather the abstract type.* """ |
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())
xml.endDocument()
return stream.getvalue() |
<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://bitbucket.org/jespern/django-piston/>`_ It has been modified since. :param xml: the xml document :type xml: SimplerXMLGenerator :param data: data to be formatted :param key: name of the parent element (for root this is ``None``) """ |
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 key, value in data.iteritems():
xml.startElement(key, {})
self._to_xml(xml, value, key)
xml.endElement(key)
else:
xml.characters(smart_unicode(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 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._element_to_node(newcurrent, name, obj) |
<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.get('cookies', {}),
elem.get('timeout', 8),
elem.get('is_json', False),
elem.get('verify_cert', True)
)
return response
return wrapper
return decorator |
<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 inside a package, and so it expects a version field like: __version__ = '1.0.0' :param path: path to the Python file :return: the version inside the file """ |
# 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)
version = str(ast.literal_eval(version.rstrip()))
extracted = version
else:
extracted = None
else:
extracted = None
return extracted |
<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:
return DummyPool(module, *args, **kwargs)
raise ValueError("Bad threadsafety level: %d" % module.threadsafety) |
<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 equivalent to the example for :py:func:`dbkit.transaction`:: import sqlite3 import sys from dbkit import connect, transactional, query_value, execute with connect(sqlite3, '/path/to/my.db') as ctx: try: change_ownership(page_id, new_owner_id) catch ctx.IntegrityError: print >> sys.stderr, "Naughty!" @transactional def change_ownership(page_id, new_owner_id):
old_owner_id = query_value( "SELECT owner_id FROM pages WHERE page_id = ?", (page_id,)) execute( "UPDATE users SET owned = owned - 1 WHERE id = ?", (old_owner_id,)) execute( "UPDATE users SET owned = owned + 1 WHERE id = ?", (new_owner_id,)) execute( "UPDATE pages SET owner_id = ? WHERE page_id = ?", (new_owner_id, page_id)) """ |
# 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 set, a default value is returned, which is `None` by default. """ |
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 returns no result set, a default value is returned, which is `None` by default. """ |
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'
placeholders = (template % key
for key in six.iterkeys(seq))
elif isinstance(seq, (list, tuple)):
if param_style == 'numeric':
placeholders = (':%d' % i
for i in xrange(start, start + len(seq)))
elif param_style in ('qmark', 'format', 'pyformat'):
placeholders = itertools.repeat(
'?' if param_style == 'qmark' else '%s',
len(seq))
if placeholders is None:
raise NotSupported(
"Param style '%s' does not support sequence type '%s'" % (
param_style, seq.__class__.__name__))
return ', '.join(placeholders) |
<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)
pprint.pprint(args, fh)
return logger_func |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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
except self.mdr.OperationalError:
# We've lost the connection, so there's no sense in
# attempting to roll back back the transaction.
self._depth -= 1
raise
except:
self._depth -= 1
if self._depth == 0:
self.mdr.rollback()
raise
if self._depth == 0:
self.mdr.commit() |
<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:
self.last_row_count = None
self.last_row_id = None
_safe_close(cursor)
raise |
<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()
self.mdr = None
self.cursor = None
if exc != (None, None, None):
six.reraise(*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 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 asynchronous HTTP request, please pass async=True :param async bool :param LineItem item: Line item to add to cart (required) :return: ShoppingCart If the method is called asynchronously, returns the request thread. """ |
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 asynchronous HTTP request, please pass async=True :param async bool :param Order order: Required order details. (required) :return: Order If the method is called asynchronously, returns the request thread. """ |
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 asynchronous HTTP request, please pass async=True :param async bool :param str item_id: Item ID to delete. (required) :return: ShoppingCart If the method is called asynchronously, returns the request thread. """ |
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, please pass async=True :param async bool :return: ShoppingCart If the method is called asynchronously, returns the request thread. """ |
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 asynchronous HTTP request, please pass async=True :param async bool :return: ShoppingCart If the method is called asynchronously, returns the request thread. """ |
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 HTTP request, please pass async=True :param async bool :param str item_id: Item ID to update. (required) :param LineItem item: Line item to update. (required) :return: ShoppingCart If the method is called asynchronously, returns the request thread. """ |
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 in syncdb. """ |
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 secure site (defaults to CFG_SITE_SECURE_URL). """ |
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. @param urlbase: base url (e.g. config.CFG_SITE_URL/search) @param urlargd: dictionary of parameters. (e.g. p={'recid':3, 'of'='hb'}) @param link_label: text displayed in a browser (has to be already escaped) @param linkattrd: dictionary of attributes (e.g. a={'class': 'img'}) @param escape_urlargd: boolean indicating if the function should escape arguments (e.g. < becomes < or " becomes ") @param escape_linkattrd: boolean indicating if the function should escape attributes (e.g. < becomes < or " becomes ") @param urlhash: hash string to add at the end of the link """ |
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]), quote=True) + '"'
for key in linkattrd.keys()]
else:
attributes = [str(key) + '="' + str(linkattrd[key]) + '"'
for key in linkattrd.keys()]
output += attributes_separator.join(attributes)
output = wash_for_utf8(output)
output += '>' + wash_for_utf8(link_label) + '</a>'
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 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 first is the canonical URL, that is the original URL with CFG_SITE_URL prefix, and where the ln= argument stripped. The second element element is mapping, language code -> alternate URL @param quote_path: if True, the path section of the given C{url} is quoted according to RFC 2396 """ |
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_query if key != 'ln']
if drop_ln:
canonical_parsed_query = no_ln_parsed_query
else:
canonical_parsed_query = parsed_query
if quote_path:
path = urllib.quote(path)
canonical_query = urlencode(canonical_parsed_query)
canonical_url = urlunparse(
(canonical_scheme,
canonical_netloc,
path,
dummy_params,
canonical_query,
fragment))
alternate_urls = {}
for ln in cfg.get('CFG_SITE_LANGS'):
alternate_query = urlencode(no_ln_parsed_query + [('ln', ln)])
alternate_url = urlunparse(
(canonical_scheme,
canonical_netloc,
path,
dummy_params,
alternate_query,
fragment))
alternate_urls[ln] = alternate_url
return canonical_url, alternate_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 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 signed Indico request URL to access Indico HTTP Export APIs. See U{http://indico.cern.ch/ihelp/html/ExportAPI/index.html} for more information. Example: >> create_Indico_request_url("https://indico.cern.ch", "categ", "", [1, 7], "xml", {'onlypublic': 'yes', 'order': 'title', 'from': 'today', 'to': 'tomorrow'}, '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000') @param base_url: Service base URL of the Indico instance to query @param indico_what: element to export @type indico_what: one of the strings: C{categ}, C{event}, C{room}, C{reservation} @param indico_loc: location of the element(s) specified by ID (only used for some elements) @param indico_id: ID of the element to be exported @type indico_id: a string or a list/tuple of strings @param indico_type: output format @type indico_type: one of the strings: C{json}, C{jsonp}, C{xml}, C{html}, C{ics}, C{atom} @param indico_params: parameters of the query. See U{http://indico.cern.ch/ihelp/html/ExportAPI/common.html} @param indico_key: API key provided for the given Indico instance @param indico_sig: API secret key (signature) provided for the given Indico instance @param _timestamp: for testing purpose only (default: current timestamp) @return signed URL of the request (string) """ |
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'):
items = indico_params.items()
else:
items = list(indico_params)
if indico_key:
items.append(('apikey', indico_key))
if indico_sig and HASHLIB_IMPORTED:
if _timestamp:
items.append(('timestamp', str(_timestamp)))
else:
items.append(('timestamp', str(int(time.time()))))
items = sorted(items, key=lambda x: x[0].lower())
url_to_sign = '%s?%s' % (url, urlencode(items))
if sys.version_info < (2, 5):
# compatibility mode for Python < 2.5 and hashlib
my_digest_algo = _MySHA1(sha1())
else:
my_digest_algo = sha1
signature = hmac.new(indico_sig, url_to_sign,
my_digest_algo).hexdigest()
items.append(('signature', signature))
elif not HASHLIB_IMPORTED:
current_app.logger.warning(
"Module hashlib not installed. Please install it."
)
if not items:
return url
url = '%s%s?%s' % (base_url.strip('/'), url, urlencode(items))
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 @param file_path: path to the file, e.g js/foo.js @return: file_path with modification time appended to URL """ |
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 joined :param right: right iterable to be joined :param function left_key_fn: function that produces hashable value from left objects :param function right_key_fn: function that produces hashable value from right objects :param join_fn: function called on joined left and right iterable items to complete join :rtype: list """ |
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 elements. [(Dog('gatsby', 'Rruff!', 15), Dog('edward', 'hi', 15)), (Dog('william', 'roof', 12), )] :param iterable: iterable to be grouped :param key: a key-access function or attr name to be used as a group key """ |
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 trigger function = None, # optional function on trigger kwargs = None, # optional function keyword arguments confirm = False, # optional return of confirmation confirmation_prompt = "Do you want to continue? (y/n)", confirmation_feedback_confirm = "confirm", confirmation_feedback_deny = "deny" ):
""" Parse input text for keyphrases. If any keyphrases are found, respond with text or by seeking confirmation or by engaging a function with optional keyword arguments. Return text or True if triggered and return False if not triggered. If confirmation is required, a confirmation object is returned, encapsulating a function and its optional arguments. """ |
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 = function,
kwargs = kwargs
)
if function and not kwargs:
result = function()
elif function and kwargs:
result = function(**kwargs)
else:
result = None
if response:
return response
elif not response and result:
return str(result)
else:
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 parse( text = None, humour = 75 ):
""" Parse input text using various triggers, some returning text and some for engaging functions. If triggered, a trigger returns text or True if and if not triggered, returns False. If no triggers are triggered, return False, if one trigger is triggered, return the value returned by that trigger, and if multiple triggers are triggered, return a list of the values returned by those triggers. Options such as humour engage or disengage various triggers. """ |
triggers = []
# general
if humour >= 75:
triggers.extend([
trigger_keyphrases(
text = text,
keyphrases = [
"image"
],
response = "http://i.imgur.com/MiqrlTh.jpg"
),
trigger_keyphrases(
text = text,
keyphrases = [
"sup",
"hi"
],
response = "sup home bean"
),
trigger_keyphrases(
text = text,
keyphrases = [
"thanks",
"thank you"
],
response = "you're welcome, boo ;)"
)
])
# information
triggers.extend([
trigger_keyphrases(
text = text,
keyphrases = [
"where are you",
"IP",
"I.P.",
"IP address",
"I.P. address",
"ip address"
],
function = report_IP
),
trigger_keyphrases(
text = text,
keyphrases = [
"how are you",
"are you well",
"status"
],
function = report_system_status,
kwargs = {"humour": humour}
),
trigger_keyphrases(
text = text,
keyphrases = [
"heartbeat"
],
function = heartbeat_message
),
trigger_keyphrases(
text = text,
keyphrases = [
"METAR"
],
function = report_METAR,
kwargs = {"text": text}
),
trigger_keyphrases(
text = text,
keyphrases = [
"TAF"
],
response = report_TAF,
kwargs = {"text": text}
),
trigger_keyphrases(
text = text,
keyphrases = [
"rain"
],
response = report_rain_times,
kwargs = {"text": text}
)
])
# actions
triggers.extend([
trigger_keyphrases(
text = text,
keyphrases = [
"command",
"run command",
"engage command",
"execute command"
],
response = command()
),
trigger_keyphrases(
text = text,
keyphrases = [
"restart"
],
function = restart,
confirm = True,
confirmation_prompt = "Do you want to restart this "
"program? (y/n)",
confirmation_feedback_confirm = "confirm restart",
confirmation_feedback_deny = "deny restart"
)
])
if any(triggers):
responses = [response for response in triggers if response]
if len(responses) > 1:
return responses
else:
return responses[0]
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 multiparse( text = None, parsers = [parse], help_message = None ):
""" Parse input text by looping over a list of multiple parsers. If one trigger is triggered, return the value returned by that trigger, if multiple triggers are triggered, return a list of the values returned by those triggers. If no triggers are triggered, return False or an optional help message. """ |
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
else:
if len(responses) > 1:
return responses
else:
return responses[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 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 TaxSettings. :type: str """ |
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_class_based_on, allowed_values)
)
self._tax_class_based_on = tax_class_based_on |
<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 check etc. """ |
# 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 = open(download_to_file, 'w')
try:
try:
while True:
block = request.read(CFG_FILEUTILS_BLOCK_SIZE)
if not block:
break
to_file.write(block)
except Exception as e:
msg = "Error when downloading %s into %s: %s" % \
(url, download_to_file, e)
raise InvenioFileDownloadError(msg)
finally:
to_file.close()
# Check Size
filesize = os.path.getsize(download_to_file)
if filesize == 0:
raise InvenioFileDownloadError("%s seems to be empty" % (url,))
# download successful, return the new path
return download_to_file |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.