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 __visit_index_model_instance(self, models, p, k, v):
""" Called during model research on merged data """ |
# print 'model visit {} on {}'.format(model, v)
cp = p + (k,)
for model in models:
try:
if model.validator(v):
if cp in self.path_index:
# if self.path_index[cp].val != v:
# raise ValueError('unexpected value change at path_index[{}]'.format(cp))
self.path_index[cp].add_model(model, v)
else:
# The object should already be in the index but don't complain for now.
self.path_index[cp] = PathCacheObject(val=v, path=cp, regs=[model])
except:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_edge_reduction(self) -> float: """Compute the edge reduction. Costly computation""" |
nb_init_edge = self.init_edge_number()
nb_poweredge = self.edge_number()
return (nb_init_edge - nb_poweredge) / (nb_init_edge) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_edge_number(self) -> int: """Return the number of edges present in the non-compressed graph""" |
return len(frozenset(frozenset(edge) for edge in self.initial_edges())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assert_powernode(self, name:str) -> None or ValueError: """Do nothing if given name refers to a powernode in given graph. Raise a ValueError in any other case. """ |
if name not in self.inclusions:
raise ValueError("Powernode '{}' does not exists.".format(name))
if self.is_node(name):
raise ValueError("Given name '{}' is a node.".format(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 powernode_data(self, name:str) -> Powernode: """Return a Powernode object describing the given powernode""" |
self.assert_powernode(name)
contained_nodes = frozenset(self.nodes_in(name))
return Powernode(
size=len(contained_nodes),
contained=frozenset(self.all_in(name)),
contained_pnodes=frozenset(self.powernodes_in(name)),
contained_nodes=contained_nodes,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node_number(self, *, count_pnode=True) -> int: """Return the number of node""" |
return (sum(1 for n in self.nodes())
+ (sum(1 for n in self.powernodes()) if count_pnode else 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 write_bubble(self, filename:str):
"""Write in given filename the lines of bubble describing this instance""" |
from bubbletools import converter
converter.tree_to_bubble(self, 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 from_bubble_file(bblfile:str, oriented:bool=False, symmetric_edges:bool=True) -> 'BubbleTree': """Extract data from given bubble file, then call from_bubble_data method """ |
return BubbleTree.from_bubble_data(utils.data_from_bubble(bblfile),
oriented=bool(oriented),
symmetric_edges=symmetric_edges) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_from_tree(root:str, graph:dict) -> frozenset: """Return a recursive structure describing given tree""" |
Node = namedtuple('Node', 'id succs')
succs = graph[root]
if succs:
return (len(succs), sorted(tuple(set_from_tree(succ, graph) for succ in succs)))
else:
return 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 get_suitable_vis_classes(obj):
"""Retuns a list of Vis classes that can handle obj.""" |
ret = []
for class_ in classes_vis():
if isinstance(obj, class_.input_classes):
ret.append(class_)
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 get_suitable_vis_list_classes(objs):
"""Retuns a list of VisList classes that can handle a list of objects.""" |
from f311 import explorer as ex
ret = []
for class_ in classes_vis():
if isinstance(class_, ex.VisList):
flag_can = True
for obj in objs:
if not isinstance(obj, class_.item_input_classes):
flag_can = False
break
if flag_can:
ret.append(class_)
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 _get_programs_dict():
""" Builds and returns programs dictionary This will have to import the packages in COLLABORATORS_S in order to get their absolute path. Returns: "packagename" examples: "f311.explorer", "numpy" """ |
global __programs_dict
if __programs_dict is not None:
return __programs_dict
d = __programs_dict = OrderedDict()
for pkgname in COLLABORATORS_S:
try:
package = importlib.import_module(pkgname)
except ImportError:
# I think it is better to be silent when a collaborator package is not installed
continue
path_ = os.path.join(os.path.split(package.__file__)[0], "scripts")
bulk = a99.get_exe_info(path_, flag_protected=True)
d[pkgname] = {"description": a99.get_obj_doc0(package), "exeinfo": bulk}
return __programs_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_url(*args, **kwargs) -> str: """ Return a valid url. """ |
resource_url = API_RESOURCES_URLS
for key in args:
resource_url = resource_url[key]
if kwargs:
resource_url = resource_url.format(**kwargs)
return urljoin(URL, resource_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 _get(url:str, headers:dict) -> dict: """ Make a GET call. """ |
response = requests.get(url, headers=headers)
data = response.json()
if response.status_code != 200:
raise GoogleApiError({"status_code": response.status_code,
"error": data.get("error", "")})
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 _post(url:str, params:dict, headers:dict) -> dict: """ Make a POST call. """ |
response = requests.post(url, params=params, headers=headers)
data = response.json()
if response.status_code != 200 or "error" in data:
raise GoogleApiError({"status_code": response.status_code,
"error": data.get("error", "")})
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 dims_knight(self, move):
'''Knight on the rim is dim'''
if self.board.piece_type_at(move.from_square) == chess.KNIGHT:
rim = SquareSet(
chess.BB_RANK_1 | \
chess.BB_RANK_8 | \
chess.BB_FILE_A | \
chess.BB_FILE_H)
return move.to_square in rim |
<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_comment_collection(cmt_id):
""" Extract the collection where the comment is written """ |
query = """SELECT id_bibrec FROM "cmtRECORDCOMMENT" WHERE id=%s"""
recid = run_sql(query, (cmt_id,))
record_primary_collection = guess_primary_collection_of_a_record(
recid[0][0])
return record_primary_collection |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_collection_moderators(collection):
""" Return the list of comment moderators for the given collection. """ |
from invenio_access.engine import acc_get_authorized_emails
res = list(
acc_get_authorized_emails(
'moderatecomments',
collection=collection))
if not res:
return [CFG_WEBCOMMENT_DEFAULT_MODERATOR, ]
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_reply_order_cache_data(comid):
""" Prepare a representation of the comment ID given as parameter so that it is suitable for byte ordering in MySQL. """ |
return "%s%s%s%s" % (chr((comid >> 24) % 256), chr((comid >> 16) % 256),
chr((comid >> 8) % 256), chr(comid % 256)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_attached_files_to_storage(attached_files, recID, comid):
""" Move the files that were just attached to a new comment to their final location. :param attached_files: the mappings of desired filename to attach and path where to find the original file :type attached_files: dict {filename, filepath} :param recID: the record ID to which we attach the files :param comid: the comment ID to which we attach the files """ |
for filename, filepath in iteritems(attached_files):
dest_dir = os.path.join(CFG_COMMENTSDIR, str(recID), str(comid))
try:
os.makedirs(dest_dir)
except:
# Dir most probably already existed
pass
shutil.move(filepath,
os.path.join(dest_dir, 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 subscribe_user_to_discussion(recID, uid):
""" Subscribe a user to a discussion, so the she receives by emails all new new comments for this record. :param recID: record ID corresponding to the discussion we want to subscribe the user :param uid: user id """ |
query = """INSERT INTO "cmtSUBSCRIPTION" (id_bibrec, id_user, creation_time)
VALUES (%s, %s, %s)"""
params = (recID, uid, convert_datestruct_to_datetext(time.localtime()))
try:
run_sql(query, params)
except:
return 0
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 unsubscribe_user_from_discussion(recID, uid):
""" Unsubscribe users from a discussion. :param recID: record ID corresponding to the discussion we want to unsubscribe the user :param uid: user id :return 1 if successful, 0 if not """ |
query = """DELETE FROM "cmtSUBSCRIPTION"
WHERE id_bibrec=%s AND id_user=%s"""
params = (recID, uid)
try:
res = run_sql(query, params)
except:
return 0
if res > 0:
return 1
return 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 get_users_subscribed_to_discussion(recID, check_authorizations=True):
""" Returns the lists of users subscribed to a given discussion. Two lists are returned: the first one is the list of emails for users who can unsubscribe from the discussion, the second list contains the emails of users who cannot unsubscribe (for eg. author of the document, etc). Users appear in only one list. If a user has manually subscribed to a discussion AND is an automatic recipients for updates, it will only appear in the second list. :param recID: record ID for which we want to retrieve subscribed users :param check_authorizations: if True, check again if users are authorized to view comment :return tuple (emails1, emails2) """ |
subscribers_emails = {}
# Get users that have subscribed to this discussion
query = """SELECT id_user FROM "cmtSUBSCRIPTION" WHERE id_bibrec=%s"""
params = (recID,)
res = run_sql(query, params)
for row in res:
uid = row[0]
if check_authorizations:
user_info = UserInfo(uid)
(auth_code, auth_msg) = check_user_can_view_comments(
user_info, recID)
else:
# Don't check and grant access
auth_code = False
if auth_code:
# User is no longer authorized to view comments.
# Delete subscription
unsubscribe_user_from_discussion(recID, uid)
else:
email = User.query.get(uid).email
if '@' in email:
subscribers_emails[email] = True
# Get users automatically subscribed, based on the record metadata
collections_with_auto_replies = CFG_WEBCOMMENT_EMAIL_REPLIES_TO.keys()
for collection in collections_with_auto_replies:
if recID in get_collection_reclist(collection):
fields = CFG_WEBCOMMENT_EMAIL_REPLIES_TO[collection]
for field in fields:
emails = get_fieldvalues(recID, field)
for email in emails:
if not '@' in email:
# Is a group: add domain name
subscribers_emails[
email +
'@' +
CFG_SITE_SUPPORT_EMAIL.split('@')[1]] = False
else:
subscribers_emails[email] = False
return ([email for email, can_unsubscribe_p
in iteritems(subscribers_emails) if can_unsubscribe_p],
[email for email, can_unsubscribe_p
in iteritems(subscribers_emails) if not can_unsubscribe_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 get_record_status(recid):
""" Returns the current status of the record, i.e. current restriction to apply for newly submitted comments, and current commenting round. The restriction to apply can be found in the record metadata, in field(s) defined by config CFG_WEBCOMMENT_RESTRICTION_DATAFIELD. The restriction is empty string "" in cases where the restriction has not explicitely been set, even if the record itself is restricted. :param recid: the record id :type recid: int :return tuple(restriction, round_name), where 'restriction' is empty string when no restriction applies :rtype (string, int) """ |
collections_with_rounds = CFG_WEBCOMMENT_ROUND_DATAFIELD.keys()
commenting_round = ""
for collection in collections_with_rounds:
# Find the first collection defines rounds field for this
# record
if recid in get_collection_reclist(collection):
commenting_rounds = get_fieldvalues(
recid,
CFG_WEBCOMMENT_ROUND_DATAFIELD.get(
collection,
""))
if commenting_rounds:
commenting_round = commenting_rounds[0]
break
collections_with_restrictions = CFG_WEBCOMMENT_RESTRICTION_DATAFIELD.keys()
restriction = ""
for collection in collections_with_restrictions:
# Find the first collection that defines restriction field for
# this record
if recid in get_collection_reclist(collection):
restrictions = get_fieldvalues(
recid,
CFG_WEBCOMMENT_RESTRICTION_DATAFIELD.get(
collection,
""))
if restrictions:
restriction = restrictions[0]
break
return (restriction, commenting_round) |
<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_comments_by_round(comments, ranking=0):
""" Group comments by the round to which they belong """ |
comment_rounds = {}
ordered_comment_round_names = []
for comment in comments:
comment_round_name = ranking and comment[11] or comment[7]
if comment_round_name not in comment_rounds:
comment_rounds[comment_round_name] = []
ordered_comment_round_names.append(comment_round_name)
comment_rounds[comment_round_name].append(comment)
return [(comment_round_name, comment_rounds[comment_round_name])
for comment_round_name in ordered_comment_round_names] |
<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_mini_reviews(recid, ln=CFG_SITE_LANG):
""" Returns the web controls to add reviews to a record from the detailed record pages mini-panel. :param recid: the id of the displayed record :param ln: the user's language """ |
if CFG_WEBCOMMENT_ALLOW_SHORT_REVIEWS:
action = 'SUBMIT'
else:
action = 'DISPLAY'
reviews = query_retrieve_comments_or_remarks(recid, ranking=1)
return webcomment_templates.tmpl_mini_review(
recid,
ln,
action=action,
avg_score=calculate_avg_score(reviews),
nb_comments_total=len(reviews)) |
<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_user_can_view_comments(user_info, recid):
"""Check if the user is authorized to view comments for given recid. Returns the same type as acc_authorize_action """ |
# Check user can view the record itself first
(auth_code, auth_msg) = check_user_can_view_record(user_info, recid)
if auth_code:
return (auth_code, auth_msg)
# Check if user can view the comments
# But first can we find an authorization for this case action,
# for this collection?
record_primary_collection = guess_primary_collection_of_a_record(recid)
return acc_authorize_action(
user_info,
'viewcomment',
authorized_if_no_roles=True,
collection=record_primary_collection) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_user_can_view_comment(user_info, comid, restriction=None):
"""Check if the user is authorized to view a particular comment, given the comment restriction. Note that this function does not check if the record itself is restricted to the user, which would mean that the user should not see the comment. You can omit 'comid' if you already know the 'restriction' :param user_info: the user info object :param comid: the comment id of that we want to check :param restriction: the restriction applied to given comment (if known. Otherwise retrieved automatically) :return: the same type as acc_authorize_action """ |
if restriction is None:
comment = query_get_comment(comid)
if comment:
restriction = comment[11]
else:
return (1, 'Comment %i does not exist' % comid)
if restriction == "":
return (0, '')
return acc_authorize_action(
user_info, 'viewrestrcomment', status=restriction) |
<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_user_can_send_comments(user_info, recid):
"""Check if the user is authorized to comment the given recid. This function does not check that user can view the record or view the comments Returns the same type as acc_authorize_action """ |
# First can we find an authorization for this case, action + collection
record_primary_collection = guess_primary_collection_of_a_record(recid)
return acc_authorize_action(
user_info,
'sendcomment',
authorized_if_no_roles=True,
collection=record_primary_collection) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_user_can_attach_file_to_comments(user_info, recid):
"""Check if the user is authorized to attach a file to comments for given recid. This function does not check that user can view the comments or send comments. Returns the same type as acc_authorize_action """ |
# First can we find an authorization for this case action, for
# this collection?
record_primary_collection = guess_primary_collection_of_a_record(recid)
return acc_authorize_action(
user_info,
'attachcommentfile',
authorized_if_no_roles=False,
collection=record_primary_collection) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user_collapsed_comments_for_record(uid, recid):
""" Get the comments collapsed for given user on given recid page """ |
# Collapsed state is not an attribute of cmtRECORDCOMMENT table
# (vary per user) so it cannot be found when querying for the
# comment. We must therefore provide a efficient way to retrieve
# the collapsed state for a given discussion page and user.
query = """SELECT "id_cmtRECORDCOMMENT" from "cmtCOLLAPSED" WHERE id_user=%s and id_bibrec=%s"""
params = (uid, recid)
return [res[0] for res in run_sql(query, 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 is_comment_deleted(comid):
""" Return True of the comment is deleted. Else False :param comid: ID of comment to check """ |
query = """SELECT status from "cmtRECORDCOMMENT" WHERE id=%s"""
params = (comid,)
res = run_sql(query, params)
if res and res[0][0] != 'ok':
return True
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 _fix_time(self, dt):
"""Stackdistiller converts all times to utc. We store timestamps as utc datetime. However, the explicit UTC timezone on incoming datetimes causes comparison issues deep in sqlalchemy. We fix this by converting all datetimes to naive utc timestamps """ |
if dt.tzinfo is not None:
dt = dt.replace(tzinfo=None)
return dt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip_leading_comments(text):
"""Strips the leading whitespaces and % from the given text. Adapted from textwrap.dedent """ |
# Look for the longest leading string of spaces and tabs common to
# all lines.
margin = None
text = _whitespace_only_re.sub('', text)
indents = _leading_whitespace_re.findall(text)
for indent in indents:
if margin is None:
margin = indent
# Current line more deeply indented than previous winner:
# no change (previous winner is still on top).
elif indent.startswith(margin):
pass
# Current line consistent with and no deeper than previous winner:
# it's the new winner.
elif margin.startswith(indent):
margin = indent
# Current line and previous winner have no common whitespace:
# there is no margin.
else:
margin = ""
break
# sanity check (testing/debugging only)
if 0 and margin:
for line in text.split("\n"):
assert not line or line.startswith(margin), \
"line = %r, margin = %r" % (line, margin)
if margin:
text = re.sub(r'(?m)^' + margin, '', text)
return 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 parse(target, trace=False, **kwargs):
"""Parse the given target. If it is a file-like object, then parse its contents. If given a string, perform one of the following actions - If the string is a valid file path, then open and parse it - If the string is a valid directory path, then recursively look for files ending in .ly or .ily - Otherwise parse the string directly. """ |
# Beware! This function, that actually is the core of all the
# business, is written to minimize the responsibilities of each
# chunk of code, keeping things simple. Performance may degrade
# because of this, but without actual measurements the simplest
# choice is the best one.
if hasattr(target, 'read'):
# It's a file-like object
file_content = target.read()
return parse(file_content, trace, **kwargs)
if os.path.isfile(target):
if target.endswith(".ily") or target.endswith(".ly"):
console.display("Parsing", target)
with io.open(target, "r", encoding="utf-8") as fp:
return parse(fp, trace, filename=target, **kwargs)
else:
return []
if os.path.isdir(target):
docs = []
logging.info("Parsing directory {}", target)
for root, _, files in os.walk(target):
for f in files:
fname = os.path.join(root, f)
file_docs = parse(fname, trace, **kwargs)
docs.extend(file_docs)
return docs
# We were given a text, so parse it directly
metrics = kwargs.get("metrics", None)
if metrics is not None:
metrics.record_file(target)
docs = []
parser = LilyParser(parseinfo=True)
try:
parser.parse(target,
'lilypond',
semantics=DocumentationSemantics(docs),
filename=kwargs.get("filename", None),
trace=trace)
except FailedParse as err:
logging.warn(err)
if metrics is not None:
metrics.record_error(err)
except RuntimeError as err:
logging.warn(err)
if metrics is not None:
metrics.record_error(err)
return docs |
<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(name, app=None, components=None, raw=False):
""" Discover any named attributes, modules, or packages and coalesces the results. Looks in any module or package declared in the the 'COMPONENTS' key in the application config. Order of found results are persisted from the order that the component was declared in. @param[in] components An array of components; overrides any setting in the application config. @param[in] raw If True then no processing is done on the found items. """ |
if components is None:
if app is None:
from flask import current_app as app
components = app.config.get('COMPONENTS', [])
items = []
for key in components:
# Attempt to import the component and access the specified name
# as an attribute.
module = import_module(key)
item = getattr(module, name, None)
if item is None:
# Attempt to import a module or package in the component
# with the specified name.
try:
item = import_module('.'.join((key, name)))
except ImportError:
# Assume this component has nothing under the specified name.
continue
if not raw:
if isinstance(item, types.ModuleType):
all_ = getattr(item, '__all__', None)
if all_:
item = {n: getattr(item, n) for n in all_}
else:
item = vars(item)
items.append(item)
return 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_clear_shopping_cart(self, auto_clear_shopping_cart):
"""Sets the auto_clear_shopping_cart of this CartSettings. :param auto_clear_shopping_cart: The auto_clear_shopping_cart of this CartSettings. :type: str """ |
allowed_values = ["never", "orderCreated", "orderCompleted"] # noqa: E501
if auto_clear_shopping_cart is not None and auto_clear_shopping_cart not in allowed_values:
raise ValueError(
"Invalid value for `auto_clear_shopping_cart` ({0}), must be one of {1}" # noqa: E501
.format(auto_clear_shopping_cart, allowed_values)
)
self._auto_clear_shopping_cart = auto_clear_shopping_cart |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getView(self, lv):
"""Determine the detector view starting with a G4LogicalVolume""" |
view = None
if str(lv.GetName())[-1] == 'X':
return 'X'
elif str(lv.GetName())[-1] == 'Y':
return 'Y'
self.log.error('Cannot determine view for %s', lv.GetName())
raise 'Cannot determine view for %s' % lv.GetName()
return view |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def RenderWidget(self):
"""Returns a QWidget subclass instance. Exact class depends on self.type""" |
t = self.type
if t == int:
ret = QSpinBox()
ret.setMaximum(999999999)
ret.setValue(self.value)
elif t == float:
ret = QLineEdit()
ret.setText(str(self.value))
elif t == bool:
ret = QCheckBox()
ret.setChecked(self.value)
else: # str, list left
ret = QLineEdit()
ret.setText(str(self.value))
if self.toolTip is not None:
ret.setToolTip(self.toolTip)
self.widget = ret
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 ScreenGenerator(nfft, r0, nx, ny):
"""Generate an infinite series of rectangular phase screens Uses an FFT screen generator to make a large screen and then returns non-overlapping subsections of it""" |
while 1:
layers = GenerateTwoScreens(nfft, r0)
for iLayer in range(2):
for iy in range(int(nfft/ny)):
for ix in range(int(nfft/nx)):
yield layers[iLayer][iy*ny:iy*ny+ny, ix*nx:ix*nx+nx] |
<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_dates(d, default='today'):
""" Parses one or more dates from d """ |
if default == 'today':
default = datetime.datetime.today()
if d is None:
return default
elif isinstance(d, _parsed_date_types):
return d
elif is_number(d):
# Treat as milliseconds since 1970
d = d if isinstance(d, float) else float(d)
return datetime.datetime.utcfromtimestamp(d)
elif not isinstance(d, STRING_TYPES):
if hasattr(d, '__iter__'):
return [parse_dates(s, default) for s in d]
else:
return default
elif len(d) == 0:
# Behaves like dateutil.parser < version 2.5
return default
else:
try:
return parser.parse(d)
except (AttributeError, ValueError):
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 load_with_classes(filename, classes):
"""Attempts to load file by trial-and-error using a given list of classes. Arguments: filename -- full path to file classes -- list of classes having a load() method Returns: DataFile object if loaded successfully, or None if not. Note: it will stop at the first successful load. Attention: this is not good if there is a bug in any of the file readers, because *all exceptions will be silenced!* """ |
ok = False
for class_ in classes:
obj = class_()
try:
obj.load(filename)
ok = True
# # cannot let IOError through because pyfits raises IOError!!
# except IOError:
# raise
# # also cannot let OSError through because astropy.io.fits raises OSError!!
# except OSError:
# raise
except FileNotFoundError:
raise
except Exception as e: # (ValueError, NotImplementedError):
# Note: for debugging, switch the below to True
if a99.logging_level == logging.DEBUG:
a99.get_python_logger().exception("Error trying with class \"{0!s}\"".format(
class_.__name__))
pass
if ok:
break
if ok:
return obj
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 load_any_file(filename):
""" Attempts to load filename by trial-and-error Returns: file: A DataFile descendant, whose specific class depends on the file format detected, or None if the file canonot be loaded """ |
import f311
# Splits attempts using ((binary X text) file) criterion
if a99.is_text_file(filename):
return load_with_classes(filename, f311.classes_txt())
else:
return load_with_classes(filename, f311.classes_bin()) |
<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_spectrum(filename):
""" Attempts to load spectrum as one of the supported types. Returns: a Spectrum, or None """ |
import f311
f = load_with_classes(filename, f311.classes_sp())
if f:
return f.spectrum
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 load_spectrum_fits_messed_x(filename, sp_ref=None):
"""Loads FITS file spectrum that does not have the proper headers. Returns a Spectrum""" |
import f311.filetypes as ft
# First tries to load as usual
f = load_with_classes(filename, (ft.FileSpectrumFits,))
if f is not None:
ret = f.spectrum
else:
hdul = fits.open(filename)
hdu = hdul[0]
if not hdu.header.get("CDELT1"):
hdu.header["CDELT1"] = 1 if sp_ref is None else sp_ref.delta_lambda
if not hdu.header.get("CRVAL1"):
hdu.header["CRVAL1"] = 0 if sp_ref is None else sp_ref.x[0]
ret = ft.Spectrum()
ret.from_hdu(hdu)
ret.filename = filename
original_shape = ret.y.shape # Shape of data before squeeze
# Squeezes to make data of shape e.g. (1, 1, 122) into (122,)
ret.y = ret.y.squeeze()
if len(ret.y.shape) > 1:
raise RuntimeError(
"Data contains more than 1 dimension (shape is {0!s}), "
"FITS file is not single spectrum".format(original_shape))
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 get_filetypes_info(editor_quote="`", flag_leaf=True):
""" Reports available data types Args: editor_quote: character to enclose the name of the editor script between. flag_leaf: see tabulate_filetypes_rest() Returns: list: list of FileTypeInfo """ |
NONE_REPL = ""
import f311
data = [] # [FileTypeInfo, ...]
for attr in f311.classes_file(flag_leaf):
description = a99.get_obj_doc0(attr)
def_ = NONE_REPL if attr.default_filename is None else attr.default_filename
ee = attr.editors
if ee is None:
ee = NONE_REPL
else:
# Example: "``mained.py``, ``x.py``"
ee = ", ".join(["{0}{1}{0}".format(editor_quote, x, editor_quote) for x in ee])
data.append({"description": description, "default_filename": def_, "classname": attr.__name__,
"editors": ee, "class": attr, "txtbin": "text" if attr.flag_txt else "binary"})
data.sort(key=lambda x: x["description"])
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 tabulate_filetypes_rest(attrnames=None, header=None, flag_wrap_description=True, description_width=40, flag_leaf=True):
""" Generates a reST multirow table Args: attrnames: list of attribute names (keys of FILE_TYPE_INFO_ATTRS). Defaults to all attributes header: list of strings containing headers. If not passed, uses default names flag_wrap_description: whether to wrap the description text description_width: width to wrap the description text (effective only if flag_wrap_description is True) flag_leaf: returns only classes that do not have subclasses ("leaf" nodes as in a class tree graph) """ |
infos = get_filetypes_info(editor_quote="``", flag_leaf=flag_leaf)
rows, header = filetypes_info_to_rows_header(infos, attrnames, header, flag_wrap_description,
description_width)
ret = a99.rest_table(rows, header)
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 return_action(self, return_action):
"""Sets the return_action of this ReturnSettings. :param return_action: The return_action of this ReturnSettings. :type: str """ |
allowed_values = ["refund", "storeCredit"] # noqa: E501
if return_action is not None and return_action not in allowed_values:
raise ValueError(
"Invalid value for `return_action` ({0}), must be one of {1}" # noqa: E501
.format(return_action, allowed_values)
)
self._return_action = return_action |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_config(config):
"""Show the current configuration.""" |
print("\nCurrent Configuration:\n")
for k, v in sorted(config.config.items()):
print("{0:15}: {1}".format(k, v)) |
<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_cloud_user(cfg, args):
"""Attempt to create the user on the cloud node.""" |
url = cfg['api_server'] + "admin/add-user"
params = {'user_email': args.user_email, 'user_name': args.user_name,
'user_role': args.user_role, 'email': cfg['email'],
'api_key': cfg['api_key']}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=json.dumps(params),
headers=headers)
if response.status_code not in range(200, 299):
raise Exception("Errors contacting the cloud node: %s" % (response.content))
loaded = json.loads(response.content)
return loaded |
<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_store(name, min_length=4, **kwargs):
"""\ Creates a store with a reasonable keygen. .. deprecated:: 2.0.0 Instantiate stores directly e.g. ``shorten.MemoryStore(min_length=4)`` """ |
if name not in stores:
raise ValueError('valid stores are {0}'.format(', '.join(stores)))
if name == 'memcache':
store = MemcacheStore
elif name == 'memory':
store = MemoryStore
elif name == 'redis':
store = RedisStore
return store(min_length=min_length, **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 do_copy(self, line):
'''
Copy packages between repos
copy SOURCE DESTINATION
Where SOURCE can be either LOCAL-FILE or REPO:PACKAGE-SPEC
DESTINATION can be either a REPO: or a directory.
'''
words = line.split()
source, destination = words
destination_repo = self._get_destination_repo(destination)
local_file_source = ':' not in source
if local_file_source:
destination_repo.upload_packages([source])
else:
source_repo_name, _, package_spec = source.partition(':')
try:
source_repo = self.network.get_repo(source_repo_name)
except UnknownRepoError:
raise ShellError(
'Unknown repository {}'.format(source_repo_name)
)
# copy between repos with the help of temporary storage
try:
source_repo.download_packages(package_spec, self.__temp_dir)
destination_repo.upload_packages(self.__temp_dir.files)
finally:
self.__temp_dir.clear() |
<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_work_on(self, repo):
'''
Make repo the active one.
Commands working on a repo will use it as default for repo parameter.
'''
self.abort_on_nonexisting_repo(repo, 'work_on')
self.network.active_repo = repo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_status(self, line):
'''
Show python packaging configuration status
'''
# Pyrene version
print('{} {}'.format(bold('Pyrene version'), green(get_version())))
# .pip/pip.conf - Pyrene repo name | exists or not
pip_conf = os.path.expanduser('~/.pip/pip.conf')
if os.path.exists(pip_conf):
conf = read_file(pip_conf)
repo = self._get_repo_for_pip_conf(conf)
if repo:
print(
'{} is configured for repository "{}"'
.format(bold(pip_conf), green(repo.name))
)
else:
print(
'{} exists, but is a {}'
.format(bold(pip_conf), red('custom configuration'))
)
else:
print('{} {}'.format(bold(pip_conf), red('does not exists')))
# existence of ~/.pypirc
if os.path.exists(self.pypirc):
template = green('exists')
else:
template = red('does not exists')
template = '{} ' + template
print(template.format(bold(self.pypirc))) |
<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_forget(self, repo):
'''
Drop definition of a repo.
forget REPO
'''
self.abort_on_nonexisting_repo(repo, 'forget')
self.network.forget(repo) |
<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_set(self, line):
'''
Set repository attributes on the active repo.
set attribute=value
# intended use:
# directory repos:
work_on developer-repo
set type=directory
set directory=package-directory
# http repos:
work_on company-private-repo
set type=http
set download-url=http://...
set upload-url=http://...
set username=user
set password=pass
'''
self.abort_on_invalid_active_repo('set')
repo = self.network.active_repo
attribute, eq, value = line.partition('=')
if not attribute:
raise ShellError('command "set" requires a non-empty attribute')
if not eq:
raise ShellError('command "set" requires a value')
self.network.set(repo, attribute, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_list(self, line):
'''
List known repos
'''
repo_names = self.network.repo_names
print('Known repos:')
print(' ' + '\n '.join(repo_names)) |
<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_show(self, repo):
'''
List repo attributes
'''
self.abort_on_nonexisting_effective_repo(repo, 'show')
repo = self.network.get_repo(repo)
repo.print_attributes() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert(filename, num_questions=None, solution=False, pages_per_q=DEFAULT_PAGES_PER_Q, folder='question_pdfs', output='gradescope.pdf', zoom=1):
""" Public method that exports nb to PDF and pads all the questions. If num_questions is specified, will also check the final PDF for missing questions. If the output font size is too small/large, increase or decrease the zoom argument until the size looks correct. If solution=True, we'll export solution cells instead of student cells. Use this option to generate the solutions to upload to Gradescope. """ |
check_for_wkhtmltohtml()
save_notebook(filename)
nb = read_nb(filename, solution=solution)
pdf_names = create_question_pdfs(nb,
pages_per_q=pages_per_q,
folder=folder,
zoom=zoom)
merge_pdfs(pdf_names, output)
# The first pdf generated is the email PDF
n_questions_found = len(pdf_names) - 1
if num_questions is not None and n_questions_found != num_questions:
logging.warning(
'We expected there to be {} questions but there are only {} in '
'your final PDF. Gradescope will most likely not accept your '
'submission. Double check that you wrote your answers in the '
'cells that we provided.'
.format(num_questions, len(pdf_names))
)
try:
from IPython.display import display, HTML
display(HTML(DOWNLOAD_HTML.format(output)))
except ImportError:
print('Done! The resulting PDF is located in this directory and is '
'called {}. Upload that PDF to Gradescope for grading.'
.format(output))
print()
print('If the font size of your PDF is too small/large, change the value '
'of the zoom argument when calling convert. For example, setting '
'zoom=2 makes everything twice as big.') |
<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_for_wkhtmltohtml():
""" Checks to see if the wkhtmltohtml binary is installed. Raises error if not. """ |
locator = 'where' if sys.platform == 'win32' else 'which'
wkhtmltopdf = (subprocess.Popen([locator, 'wkhtmltopdf'],
stdout=subprocess.PIPE)
.communicate()[0].strip())
if not os.path.exists(wkhtmltopdf):
logging.error(
'No wkhtmltopdf executable found. Please install '
'wkhtmltopdf before trying again - {}'.format(WKHTMLTOPDF_URL))
raise ValueError(
'No wkhtmltopdf executable found. Please install '
'wkhtmltopdf before trying again - {}'.format(WKHTMLTOPDF_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 read_nb(filename, solution) -> nbformat.NotebookNode: """ Takes in a filename of a notebook and returns a notebook object containing only the cell outputs to export. """ |
with open(filename, 'r') as f:
nb = nbformat.read(f, as_version=4)
email = find_student_email(nb)
preamble = nbformat.v4.new_markdown_cell(
source='# ' + email, metadata={'tags': ['q_email']})
tags_to_check = TAGS if not solution else SOL_TAGS
cells = ([preamble] +
[remove_input(cell) for cell in nb['cells']
if cell_has_tags(cell, tags_to_check)])
nb['cells'] = cells
return nb |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nb_to_html_cells(nb) -> list: """ Converts notebook to an iterable of BS4 HTML nodes. Images are inline. """ |
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(nb)
return BeautifulSoup(body, 'html.parser').findAll('div', class_='cell') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nb_to_q_nums(nb) -> list: """ Gets question numbers from each cell in the notebook """ |
def q_num(cell):
assert cell.metadata.tags
return first(filter(lambda t: 'q' in t, cell.metadata.tags))
return [q_num(cell) for cell in nb['cells']] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pad_pdf_pages(pdf_name, pages_per_q) -> None: """ Checks if PDF has the correct number of pages. If it has too many, warns the user. If it has too few, adds blank pages until the right length is reached. """ |
pdf = PyPDF2.PdfFileReader(pdf_name)
output = PyPDF2.PdfFileWriter()
num_pages = pdf.getNumPages()
if num_pages > pages_per_q:
logging.warning('{} has {} pages. Only the first '
'{} pages will get output.'
.format(pdf_name, num_pages, pages_per_q))
# Copy over up to pages_per_q pages
for page in range(min(num_pages, pages_per_q)):
output.addPage(pdf.getPage(page))
# Pad if necessary
if num_pages < pages_per_q:
for page in range(pages_per_q - num_pages):
output.addBlankPage()
# Output the PDF
with open(pdf_name, 'wb') as out_file:
output.write(out_file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_question_pdfs(nb, pages_per_q, folder, zoom) -> list: """ Converts each cells in tbe notebook to a PDF named something like 'q04c.pdf'. Places PDFs in the specified folder and returns the list of created PDF locations. """ |
html_cells = nb_to_html_cells(nb)
q_nums = nb_to_q_nums(nb)
os.makedirs(folder, exist_ok=True)
pdf_options = PDF_OPTS.copy()
pdf_options['zoom'] = ZOOM_FACTOR * zoom
pdf_names = []
for question, cell in zip(q_nums, html_cells):
# Create question PDFs
pdf_name = os.path.join(folder, '{}.pdf'.format(question))
pdfkit.from_string(cell.prettify(), pdf_name, options=pdf_options)
pad_pdf_pages(pdf_name, pages_per_q)
print('Created ' + pdf_name)
pdf_names.append(pdf_name)
return pdf_names |
<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_pdfs(pdf_names, output) -> None: """ Merges all pdfs together into a single long PDF. """ |
merger = PyPDF2.PdfFileMerger()
for filename in pdf_names:
merger.append(filename)
merger.write(output)
merger.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connection_count(self):
"""Number of currently open connections to the database. (Stored in table sqlarray_master.) """ |
return self.sql("SELECT value FROM %(master)s WHERE name = 'connection_counter'" % vars(self),
cache=False, asrecarray=False)[0][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 sql_select(self,fields,*args,**kwargs):
"""Execute a simple SQL ``SELECT`` statement and returns values as new numpy rec array. The arguments *fields* and the additional optional arguments are simply concatenated with additional SQL statements according to the template:: SELECT <fields> FROM __self__ [args] The simplest fields argument is ``"*"``. Example: Create a recarray in which students with average grade less than 3 are listed:: result = T.SELECT("surname, subject, year, avg(grade) AS avg_grade", "WHERE avg_grade < 3", "GROUP BY surname,subject", "ORDER BY avg_grade,surname") The resulting SQL would be:: SELECT surname, subject, year, avg(grade) AS avg_grade FROM __self__ WHERE avg_grade < 3 GROUP BY surname,subject ORDER BY avg_grade,surname Note how one can use aggregate functions such avg(). The string *'__self__'* is automatically replaced with the table name (``T.name``); this can be used for cartesian products such as :: .. Note:: See the documentation for :meth:`~SQLarray.sql` for more details on the available keyword arguments and the use of ``?`` parameter interpolation. """ |
SQL = "SELECT "+str(fields)+" FROM __self__ "+ " ".join(args)
return self.sql(SQL,**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 sql(self,SQL,parameters=None,asrecarray=True,cache=True):
"""Execute sql statement. :Arguments: SQL : string Full SQL command; can contain the ``?`` place holder so that values supplied with the ``parameters`` keyword can be interpolated using the ``pysqlite`` interface. parameters : tuple Parameters for ``?`` interpolation. asrecarray : boolean ``True``: return a ``numpy.recarray`` if possible; ``False``: return records as a list of tuples. [``True``] cache : boolean Should the results be cached? Set to ``False`` for large queries to avoid memory issues. Queries with ``?`` place holders are never cached. [``True``] :Returns: For *asrecarray* = ``True`` a :class:`numpy.recarray` is returned; otherwise a simple list of tuples is returned. :Raises: :exc:`TypeError` if the conversion to :class:`~numpy.recarray` fails for any reason. .. warning:: There are **no sanity checks** applied to the SQL. The last *cachesize* queries are cached (for *cache* = ``True``) and are returned directly unless the table has been modified. The string "__self__" in *SQL* is substituted with the table name. See the :meth:`SELECT` method for more details. """ |
SQL = SQL.replace('__self__',self.name)
# Cache the last N (query,result) tuples using a 'FIFO-dict'
# of length N, where key = SQL; if we can use the cache
# (cache=True) and if query in dict (AND cache
# valid, ie it hasn't been emptied (??)) just return cache result.
#
# Never use the cache if place holders are used because then we
# would return the same result for differing input!
if not '?' in SQL and cache and SQL in self.__cache:
return self.__cache[SQL]
c = self.cursor
if parameters is None:
c.execute(SQL) # no sanity checks!
else:
c.execute(SQL, parameters) # no sanity checks; params should be tuple
if c.rowcount > 0 or SQL.upper().find('DELETE') > -1:
# table was (potentially) modified
# rowcount does not change for DELETE, see
# http://oss.itsystementwicklung.de/download/pysqlite/doc/sqlite3.html#cursor-objects
# so we catch this case manually and invalidate the whole cache
self.__cache.clear()
result = c.fetchall()
if not result:
return [] # leaving here keeps cache invalidated
if asrecarray:
try:
names = [x[0] for x in c.description] # first elements are column names
result = numpy.rec.fromrecords(result,names=names)
except:
raise TypeError("SQLArray.sql(): failed to return recarray, try setting asrecarray=False to return tuples instead")
else:
pass # keep as tuples/data structure as requested
if cache:
self.__cache.append(SQL,result)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def limits(self,variable):
"""Return minimum and maximum of variable across all rows of data.""" |
(vmin,vmax), = self.SELECT('min(%(variable)s), max(%(variable)s)' % vars())
return vmin,vmax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def selection(self, SQL, parameters=None, **kwargs):
"""Return a new SQLarray from a SELECT selection. This method is useful to build complicated selections and essentially new tables from existing data. The result of the SQL query is stored as a new table in the database. By default, a unique name is created but this can be overridden with the *name* keyword. :Arguments: *SQL* SQL ``SELECT`` query string. A leading ``SELECT * FROM __self__ WHERE`` can be omitted (see examples below). The SQL is scrubbed and only data up to the first semicolon is used (note that this means that there cannot even be a semicolon in quotes; if this is a problem, file a bug report and it might be changed). :Keywords: *name* name of the table, ``None`` autogenerates a name unique to this query. *name* may not refer to the parent table itself. [``None``] *parameters* tuple of values that are safely interpolated into subsequent ``?`` characters in the SQL string *force* If ``True`` then an existing table of the same *name* is ``DROP``ped first. If ``False`` and the table already exists then *SQL* is ignored and a :class:`SQLarray` of the existing table *name* is returned. [``False``] :Returns: a :class:`SQLarray` referring to the table *name* in the database; it also inherits the :attr:`SQLarray.dbfile` Examples:: s = SQLarray.selection('a > 3') s = SQLarray.selection('a > ?', (3,)) s = SQLarray.selection('SELECT * FROM __self__ WHERE a > ? AND b < ?', (3, 10)) """ |
# TODO: under development
# - could use VIEW
force = kwargs.pop('force', False)
# pretty unsafe... I hope the user knows what they are doing
# - only read data to first semicolon
# - here should be input scrubbing...
safe_sql = re.match(r'(?P<SQL>[^;]*)',SQL).group('SQL')
if re.match(r'\s*SELECT.*FROM',safe_sql,flags=re.IGNORECASE):
_sql = safe_sql
else:
# WHERE clause only
_sql = """SELECT * FROM __self__ WHERE """+str(safe_sql)
# (note: MUST replace __self__ before md5!)
_sql = _sql.replace('__self__', self.name)
# unique name for table (unless user supplied... which could be 'x;DROP TABLE...')
newname = kwargs.pop('name', 'selection_'+md5(_sql).hexdigest())
if newname in ("__self__", self.name):
raise ValueError("Table name %(newname)r cannot refer to the parent table itself." % vars())
has_newname = self.has_table(newname)
c = self.cursor
if has_newname and force:
c.execute("DROP TABLE %(newname)s" % vars())
has_newname = False
if not has_newname:
# create table directly
# SECURITY: unsafe tablename !!!! (but cannot interpolate?)
_sql = "CREATE TABLE %(newname)s AS " % vars() + _sql
if parameters is None:
c.execute(_sql) # no sanity checks!
else:
c.execute(_sql, parameters) # no sanity checks; params should be tuple
# associate with new table in db
return SQLarray(newname, None, dbfile=self.dbfile, connection=self.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 _init_sqlite_functions(self):
"""additional SQL functions to the database""" |
self.connection.create_function("sqrt", 1,sqlfunctions._sqrt)
self.connection.create_function("sqr", 1,sqlfunctions._sqr)
self.connection.create_function("periodic", 1,sqlfunctions._periodic)
self.connection.create_function("pow", 2,sqlfunctions._pow)
self.connection.create_function("match",2,sqlfunctions._match)
self.connection.create_function("regexp",2,sqlfunctions._regexp)
self.connection.create_function("fformat",2,sqlfunctions._fformat)
self.connection.create_aggregate("std",1,sqlfunctions._Stdev)
self.connection.create_aggregate("stdN",1,sqlfunctions._StdevN)
self.connection.create_aggregate("median",1,sqlfunctions._Median)
self.connection.create_aggregate("array",1,sqlfunctions._NumpyArray)
self.connection.create_aggregate("histogram",4,sqlfunctions._NumpyHistogram)
self.connection.create_aggregate("distribution",4,sqlfunctions._NormedNumpyHistogram)
self.connection.create_aggregate("meanhistogram",5,sqlfunctions._MeanHistogram)
self.connection.create_aggregate("stdhistogram",5,sqlfunctions._StdHistogram)
self.connection.create_aggregate("minhistogram",5,sqlfunctions._MinHistogram)
self.connection.create_aggregate("maxhistogram",5,sqlfunctions._MaxHistogram)
self.connection.create_aggregate("medianhistogram",5,sqlfunctions._MedianHistogram)
self.connection.create_aggregate("zscorehistogram",5,sqlfunctions._ZscoreHistogram) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prune(self):
"""Primitive way to keep dict in sync with RB.""" |
delkeys = [k for k in self.keys() if k not in self.__ringbuffer]
for k in delkeys: # necessary because dict is changed during iterations
super(KRingbuffer,self).__delitem__(k) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def chunk_on(pipeline, new_chunk_signal, output_type=tuple):
''' split the stream into seperate chunks based on a new chunk signal '''
assert iterable(pipeline), 'chunks needs pipeline to be iterable'
assert callable(new_chunk_signal), 'chunks needs new_chunk_signal to be callable'
assert callable(output_type), 'chunks needs output_type to be callable'
out = deque()
for i in pipeline:
if new_chunk_signal(i) and len(out): # if new chunk start detected
yield output_type(out)
out.clear()
out.append(i)
# after looping, if there is anything in out, yield that too
if len(out):
yield output_type(out) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def center_image(self, img):
"""Sets an image's anchor point to its center""" |
img.anchor_x = img.width // 2 # int
img.anchor_y = img.height // 2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_persons(self):
""" Returns list of strings which represents persons being chated with """ |
cs = self.data["to"]["data"]
res = []
for c in cs:
res.append(c["name"])
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_messages(self):
""" Returns list of Message objects which represents messages being transported. """ |
cs = self.data["comments"]["data"]
res = []
for c in cs:
res.append(Message(c,self))
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next(self):
""" Returns next paging """ |
c = Conversation(self.data, requests.get(self.data["comments"]["paging"]["next"]).json())
if "error" in c.data["comments"] and c.data["comments"]["error"]["code"] == 613:
raise LimitExceededException()
return c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _subset_table(full_table, subset):
""" Return subtable matching all conditions in subset Parameters full_table : dataframe Entire data table subset : str String describing subset of data to use for analysis Returns ------- dataframe Subtable with records from table meeting requirements in subset """ |
if not subset:
return full_table
# TODO: Figure out syntax for logical or
conditions = subset.replace(' ','').split(';')
valid = np.ones(len(full_table), dtype=bool)
for condition in conditions:
col = re.split("[<>=!]", condition)[0]
comp = condition.replace(col, "")
try:
this_valid = eval("full_table['{0}']{1}".format(col, comp))
except KeyError as e: # catch error and redisplay for twiggy
raise KeyError("Column '%s' not found" % e.message)
valid = np.logical_and(valid, this_valid)
return full_table[valid] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _subset_meta(full_meta, subset, incremented=False):
""" Return metadata reflecting all conditions in subset Parameters full_meta : ConfigParser obj Metadata object subset : str String describing subset of data to use for analysis incremented : bool If True, the metadata has already been incremented Returns ------- Configparser object or dict Updated version of full_meta accounting for subset string """ |
if not subset:
return full_meta, False
meta = {} # Make deepcopy of entire meta (all section dicts in meta dict)
for key, val in full_meta.iteritems():
meta[key] = copy.deepcopy(dict(val))
conditions = subset.replace(' ','').split(';')
inc = False
for condition in conditions:
condition_list = re.split('[<>=]', condition)
col = condition_list[0]
val = condition_list[-1]
try:
col_step = meta[col]['step']
except: # If there's no metadata for this col, do nothing
continue
operator = re.sub('[^<>=]', '', condition)
if operator == '==':
meta[col]['min'] = val
meta[col]['max'] = val
elif operator == '>=':
meta[col]['min'] = val
elif operator == '>':
if incremented:
meta[col]['min'] = val
else:
meta[col]['min'] = str(eval(val) + eval(col_step))
inc = True
elif operator == '<=':
meta[col]['max'] = val
elif operator == '<':
if incremented:
meta[col]['max'] = val
else:
meta[col]['max'] = str(eval(val) - eval(col_step))
inc = True
else:
raise ValueError, "Subset %s not valid" % condition
return meta, inc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sad(patch, cols, splits, clean=True):
""" Calculates an empirical species abundance distribution Parameters {0} clean : bool If True, all species with zero abundance are removed from SAD results. Default False. Returns ------- {1} Result has two columns: spp (species identifier) and y (individuals of that species). Notes ----- {2} {3} Examples -------- {4} spp y 0 arsp1 2 1 cabr 31 2 caspi1 58 3 chst 1 4 comp1 5 5 cran 4 6 crcr 65 7 crsp2 79 8 enfa 1 9 gnwe 41 10 grass 1110 11 lesp1 1 12 magl 1 13 mesp 6 14 mobe 4 15 phdi 210 16 plsp1 1 17 pypo 73 18 sasp 2 19 ticr 729 20 unsh1 1 21 unsp1 18 22 unsp3 1 23 unsp4 1 4 ('row>=-0.5; row<1.5; column>=-0.5; column<1.5', spp y 0 arsp1 0 1 cabr 7 2 caspi1 0 3 chst 1 4 comp1 1 5 cran 3 6 crcr 21 7 crsp2 16 8 enfa 0 9 gnwe 8 10 grass 236 11 lesp1 0 12 magl 0 13 mesp 4 14 mobe 0 15 phdi 33 16 plsp1 1 17 pypo 8 18 sasp 2 19 ticr 317 20 unsh1 1 21 unsp1 0 22 unsp3 1 23 unsp4 1) See http://www.macroeco.org/tutorial_macroeco.html for additional examples and explanation """ |
(spp_col, count_col), patch = \
_get_cols(['spp_col', 'count_col'], cols, patch)
full_spp_list = np.unique(patch.table[spp_col])
# Loop through each split
result_list = []
for substring, subpatch in _yield_subpatches(patch, splits):
# Get abundance for each species
sad_list = []
for spp in full_spp_list:
this_spp = (subpatch.table[spp_col] == spp)
count = np.sum(subpatch.table[count_col][this_spp])
sad_list.append(count)
# Create dataframe of spp names and abundances
subdf = pd.DataFrame({'spp': full_spp_list, 'y': sad_list})
# Remove zero abundance rows if requested
if clean:
subdf = subdf[subdf['y'] > 0]
# Append subset result
result_list.append((substring, subdf))
# Return all results
return result_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ssad(patch, cols, splits):
""" Calculates an empirical intra-specific spatial abundance distribution Parameters {0} Returns ------- {1} Result has one column giving the individuals of species in each subplot. Notes ----- {2} {3} Examples -------- {4} y 0 42 1 20 2 60 3 60 4 88 5 86 6 20 7 0 8 110 9 12 10 115 11 180 12 160 13 120 14 26 15 11 See http://www.macroeco.org/tutorial_macroeco.html for additional examples and explanation """ |
# Get and check SAD
sad_results = sad(patch, cols, splits, clean=False)
# Create dataframe with col for spp name and numbered col for each split
for i, sad_result in enumerate(sad_results):
if i == 0: # For first result, create dataframe
fulldf = sad_result[1]
fulldf.columns = ['spp', '0'] # Renames y col to 0
else: # For other results, append col to dataframe, named by num
fulldf[str(i)] = sad_result[1]['y']
# Get each spp SSAD (row of fulldf) and append as tuple in result_list
result_list = []
for _, row in fulldf.iterrows():
row_values_array = np.array(row[1:], dtype=float)
result_list.append((row[0], pd.DataFrame({'y': row_values_array})))
# Return all results
return result_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sar(patch, cols, splits, divs, ear=False):
""" Calculates an empirical species area or endemics area relationship Parameters {0} divs : str Description of how to divide x_col and y_col. See notes. ear : bool If True, calculates an endemics area relationship Returns ------- {1} Result has 5 columns; div, x, and y; that give the ID for the division given as an argument, fractional area, and the mean species richness at that division. Notes ----- {2} For the SAR and EAR, cols must also contain x_col and y_col, giving the x and y dimensions along which to grid the patch. {3} {4} Examples -------- {5} cols='spp_col:spp; count_col:count; x_col:row; y_col:column', splits="", divs="1,1; 1,2; 2,1; 2,2; 2,4; 4,2; 4,4") div n_individs n_spp x y 0 1,1 2445.0000 24.0000 16 24.0000 1 1,2 1222.5000 18.5000 8 18.5000 2 2,1 1222.5000 17.0000 8 17.0000 3 2,2 611.2500 13.5000 4 13.5000 4 2,4 305.6250 10.1250 2 10.1250 5 4,2 305.6250 10.5000 2 10.5000 6 4,4 152.8125 7.5625 1 7.5625 The column div gives the divisions specified in the function call. The column n_individs specifies the average number of individuals across the cells made from the given division. n_spp gives the average species across the cells made from the given division. x gives the absolute area of a cell for the given division. y gives the same information as n_spp and is included for easy plotting. See http://www.macroeco.org/tutorial_macroeco.html for additional examples and explanation """ |
def sar_y_func(spatial_table, all_spp):
return np.mean(spatial_table['n_spp'])
def ear_y_func(spatial_table, all_spp):
endemic_counter = 0
for spp in all_spp:
spp_in_cell = [spp in x for x in spatial_table['spp_set']]
spp_n_cells = np.sum(spp_in_cell)
if spp_n_cells == 1: # If a spp is in only 1 cell, endemic
endemic_counter += 1
n_cells = len(spatial_table)
return endemic_counter / n_cells # mean endemics / cell
if ear:
y_func = ear_y_func
else:
y_func = sar_y_func
return _sar_ear_inner(patch, cols, splits, divs, y_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 _sar_ear_inner(patch, cols, splits, divs, y_func):
""" y_func is function calculating the mean number of species or endemics, respectively, for the SAR or EAR """ |
(spp_col, count_col, x_col, y_col), patch = \
_get_cols(['spp_col', 'count_col', 'x_col', 'y_col'], cols, patch)
# Loop through each split
result_list = []
for substring, subpatch in _yield_subpatches(patch, splits):
# Get A0
A0 = _patch_area(subpatch, x_col, y_col)
# Loop through all divisions within this split
all_spp = np.unique(subpatch.table[spp_col])
subresultx = []
subresulty = []
subresultnspp = []
subresultnindivids = []
subdivlist = _split_divs(divs)
for subdiv in subdivlist:
spatial_table = _yield_spatial_table(subpatch, subdiv, spp_col,
count_col, x_col, y_col)
subresulty.append(y_func(spatial_table, all_spp))
subresultx.append(A0 / eval(subdiv.replace(',', '*')))
subresultnspp.append(np.mean(spatial_table['n_spp']))
subresultnindivids.append(np.mean(spatial_table['n_individs']))
# Append subset result
subresult = pd.DataFrame({'div': subdivlist, 'x': subresultx,
'y': subresulty, 'n_spp': subresultnspp,
'n_individs': subresultnindivids})
result_list.append((substring, subresult))
return result_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comm_grid(patch, cols, splits, divs, metric='Sorensen'):
""" Calculates commonality as a function of distance for a gridded patch Parameters {0} divs : str Description of how to divide x_col and y_col. Unlike SAR and EAR, only one division can be given at a time. See notes. metric : str One of Sorensen or Jaccard, giving the metric to use for commonality calculation Returns ------- {1} Result has three columns, pair, x, and y, that give the locations of the pair of patches for which commonality is calculated, the distance between those cells, and the Sorensen or Jaccard result. Notes ----- {2} For gridded commonality, cols must also contain x_col and y_col, giving the x and y dimensions along which to grid the patch. {3} """ |
(spp_col, count_col, x_col, y_col), patch = \
_get_cols(['spp_col', 'count_col', 'x_col', 'y_col'], cols, patch)
# Loop through each split
result_list = []
for substring, subpatch in _yield_subpatches(patch, splits):
# Get spatial table and break out columns
spatial_table = _yield_spatial_table(subpatch, divs, spp_col,
count_col, x_col, y_col)
spp_set = spatial_table['spp_set']
cell_loc = spatial_table['cell_loc']
n_spp = spatial_table['n_spp']
# Get all possible pairwise combinations of cells
pair_list = []
dist_list = []
comm_list = []
for i in range(len(spatial_table)):
for j in range(i+1, len(spatial_table)):
iloc = np.round(cell_loc[i], 6)
jloc = np.round(cell_loc[j], 6)
pair_list.append('('+str(iloc[0])+' '+str(iloc[1])+') - '+
'('+str(jloc[0])+' '+str(jloc[1])+')')
dist_list.append(_distance(cell_loc[i], cell_loc[j]))
ij_intersect = spp_set[i] & spp_set[j]
if metric.lower() == 'sorensen':
comm = 2*len(ij_intersect) / (n_spp[i] + n_spp[j])
elif metric.lower() == 'jaccard':
comm = len(ij_intersect) / len(spp_set[i] | spp_set[j])
else:
raise ValueError, ("Only Sorensen and Jaccard metrics are "
"available for gridded commonality")
comm_list.append(comm)
# Append subset result
subresult = pd.DataFrame({'pair': pair_list, 'x': dist_list,
'y': comm_list})
result_list.append((substring, subresult))
# Return all results
return result_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _yield_spatial_table(patch, div, spp_col, count_col, x_col, y_col):
""" Calculates an empirical spatial table Yields ------- DataFrame Spatial table for each division. See Notes. Notes ----- The spatial table is the precursor to the SAR, EAR, and grid-based commonality metrics. Each row in the table corresponds to a cell created by a given division. Columns are cell_loc (within the grid defined by the division), spp_set, n_spp, and n_individs. """ |
# Catch error if you don't use ; after divs in comm_grid in MacroecoDesktop
try:
div_split_list = div.replace(';','').split(',')
except AttributeError:
div_split_list = str(div).strip("()").split(',')
div_split = (x_col + ':' + div_split_list[0] + ';' +
y_col + ':' + div_split_list[1])
# Get cell_locs
# Requires _parse_splits and _product functions to go y inside of x
x_starts, x_ends = _col_starts_ends(patch, x_col, div_split_list[0])
x_offset = (x_ends[0] - x_starts[0]) / 2
x_locs = x_starts + x_offset
y_starts, y_ends = _col_starts_ends(patch, y_col, div_split_list[1])
y_offset = (y_ends[0] - y_starts[0]) / 2
y_locs = y_starts + y_offset
cell_locs = _product(x_locs, y_locs)
# Get spp set and count for all cells
n_spp_list = [] # Number of species in cell
n_individs_list = []
spp_set_list = [] # Set object giving unique species IDs in cell
for cellstring, cellpatch in _yield_subpatches(patch,div_split,name='div'):
spp_set = set(np.unique(cellpatch.table[spp_col]))
spp_set_list.append(spp_set)
n_spp_list.append(len(spp_set))
n_individs_list.append(np.sum(cellpatch.table[count_col]))
# Create and return dataframe
df = pd.DataFrame({'cell_loc': cell_locs, 'spp_set': spp_set_list,
'n_spp': n_spp_list, 'n_individs': n_individs_list})
return df |
<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_cols(special_col_names, cols, patch):
""" Retrieve values of special_cols from cols string or patch metadata """ |
# If cols not given, try to fall back on cols from metadata
if not cols:
if 'cols' in patch.meta['Description'].keys():
cols = patch.meta['Description']['cols']
else:
raise NameError, ("cols argument not given, spp_col at a minimum "
"must be specified")
# Parse cols string into dict
cols = cols.replace(' ', '')
col_list = cols.split(';')
col_dict = {x.split(':')[0]: x.split(':')[1] for x in col_list}
# Get special_col_names from dict
result = []
for special_col_name in special_col_names:
col_name = col_dict.get(special_col_name, None)
# Create a count col if its requested and doesn't exist
if special_col_name is 'count_col' and col_name is None:
col_name = 'count'
patch.table['count'] = np.ones(len(patch.table))
# All special cols must be specified (count must exist by now)
if col_name is None:
raise ValueError, ("Required column %s not specified" %
special_col_name)
result.append(col_name)
return tuple(result), patch |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _yield_subpatches(patch, splits, name='split'):
""" Iterator for subtables defined by a splits string Parameters patch : obj Patch object containing data to subset splits : str Specifies how a column of a dataset should be split. See Notes. Yields ------ tuple First element is subset string, second is subtable dataframe Notes ----- {0} """ |
if splits:
subset_list = _parse_splits(patch, splits)
for subset in subset_list:
logging.info('Analyzing subset %s: %s' % (name, subset))
subpatch = copy.copy(patch)
subpatch.table = _subset_table(patch.table, subset)
subpatch.meta, subpatch.incremented = _subset_meta(patch.meta,
subset, incremented=True)
yield subset, subpatch
else:
yield '', patch |
<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_splits(patch, splits):
""" Parse splits string to get list of all associated subset strings. Parameters patch : obj Patch object containing data to subset splits : str Specifies how a column of a dataset should be split. See Notes. Returns ------- list List of subset strings derived from splits string Notes ----- {0} """ |
split_list = splits.replace(' ','').split(';')
subset_list = [] # List of all subset strings
for split in split_list:
col, val = split.split(':')
if val == 'split':
uniques = []
for level in patch.table[col]:
if level not in uniques:
uniques.append(level)
level_list = [col + '==' + str(x) + '; ' for x in uniques]
else:
starts, ends = _col_starts_ends(patch, col, val)
level_list = [col + '>=' + str(x) + '; ' + col + '<' + str(y)+'; '
for x, y in zip(starts, ends)]
subset_list.append(level_list)
# Get product of all string levels as list, conv to string, drop final ;
return [''.join(x)[:-2] for x in _product(*subset_list)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _product(*args, **kwds):
""" Generates cartesian product of lists given as arguments From itertools.product documentation """ |
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def empirical_cdf(data):
""" Generates an empirical cdf from data Parameters data : iterable Empirical data Returns -------- DataFrame Columns 'data' and 'ecdf'. 'data' contains ordered data and 'ecdf' contains the corresponding ecdf values for the data. """ |
vals = pd.Series(data).value_counts()
ecdf = pd.DataFrame(data).set_index(keys=0)
probs = pd.DataFrame(vals.sort_index().cumsum() / np.float(len(data)))
ecdf = ecdf.join(probs)
ecdf = ecdf.reset_index()
ecdf.columns = ['data', 'ecdf']
return ecdf |
<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_table(self, metadata_path, data_path):
""" Load data table, taking subset if needed Parameters metadata_path : str Path to metadata file data_path : str Path to data file, absolute or relative to metadata file Returns ------- dataframe Table for analysis """ |
metadata_dir = os.path.dirname(os.path.expanduser(metadata_path))
data_path = os.path.normpath(os.path.join(metadata_dir, data_path))
extension = data_path.split('.')[-1]
if extension == 'csv':
full_table = pd.read_csv(data_path, index_col=False)
table = _subset_table(full_table, self.subset)
self.meta, _ = _subset_meta(self.meta, self.subset)
elif extension in ['db', 'sql']:
# TODO: deal with incrementing in DB table
table = self._get_db_table(data_path, extension)
else:
raise TypeError('Cannot process file of type %s' % extension)
return table |
<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_db_table(self, data_path, extension):
""" Query a database and return query result as a recarray Parameters data_path : str Path to the database file extension : str Type of database, either sql or db Returns ------- table : recarray The database query as a recarray """ |
# TODO: This is probably broken
raise NotImplementedError, "SQL and db file formats not yet supported"
# Load table
if extension == 'sql':
con = lite.connect(':memory:')
con.row_factory = lite.Row
cur = con.cursor()
with open(data_path, 'r') as f:
sql = f.read()
cur.executescript(sql)
else:
con = lite.connect(data_path)
con.row_factory = lite.Row
cur = con.cursor()
cur.execute(self.subset)
# Check that table is not empty
db_info = cur.fetchall()
try:
col_names = db_info[0].keys()
except IndexError:
raise lite.OperationalError("Query %s to database %s is empty" %
(query_str, data_path))
# Convert objects to tuples
converted_info = [tuple(x) for x in db_info]
# NOTE: Using default value for Unicode: Seems better than checking
# lengths. Should we keep the type as unicode?
dtypes=[type(x) if type(x) != unicode else 'S150' for x in db_info[0]]
table = np.array(converted_info, dtype=zip(col_names, dtypes))
con.commit()
con.close()
# Return a recarray for consistency
# TODO: This should now be a pd.dataframe
return table.view(np.recarray) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def doc_sub(*sub):
""" Decorator for performing substitutions in docstrings. Using @doc_sub(some_note, other_note) on a function with {0} and {1} in the docstring will substitute the contents of some_note and other_note for {0} and {1}, respectively. Decorator appears to work properly both with IPython help (tab completion and ?) and with Sphinx. """ |
def dec(obj):
obj.__doc__ = obj.__doc__.format(*sub)
return obj
return dec |
<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_start_end(f):
""" Decorator to log start and end of function Use of decorator module here ensures that argspec will inspect wrapped function, not the decorator itself. http://micheles.googlecode.com/hg/decorator/documentation.html """ |
def inner(f, *args, **kwargs):
logging.info('Starting %s' % f.__name__)
res = f(*args, **kwargs)
logging.info('Finished %s' % f.__name__)
return res
return decorator.decorator(inner, 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 check_parameter_file(filename):
""" Function does a rudimentary check whether the cols, splits and divs columns in the parameter files are formatted properly. Just provides a preliminary check. Will only catch basic mistakes Parameters filename : str Path to parameters file Returns ------- : list Contains the number of possible bad strings detected """ |
# Load file
with open(filename, "r") as fin:
content = fin.read()
# Check cols and splits strings
bad_names = []
line_numbers = []
strs = ["cols", "splits", "divs"]
for tstr in strs:
start = content.find(tstr)
while start != -1:
cols_str = "".join(content[start:].split("\n")[0].split("=")[-1].split(" "))
semis = cols_str.count(";")
# Get line number
line_end = content.find("\n", start)
line_number = content[:line_end].count("\n") + 1
if tstr == "divs":
colons = cols_str.count(",")
else:
colons = cols_str.count(":")
if colons != (semis + 1):
bad_names.append(tstr)
line_numbers.append(line_number)
start = content.find(tstr, start + 1)
return bad_names, line_numbers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_starttag(self, tag, attrs):
"""Function called for new opening tags""" |
if tag.lower() in self.allowed_tag_whitelist:
if tag.lower() == 'ol':
# we need a list to store the last
# number used in the previous ordered lists
self.previous_nbs.append(self.nb)
self.nb = 0
# we need to know which is the tag list
self.previous_type_lists.append(tag.lower())
# we must remove any non-relevant spacing and end of
# line before
self.result = self.result.rstrip()
elif tag.lower() == 'ul':
self.previous_type_lists.append(tag.lower())
# we must remove any non-relevant spacing and end of
# line before
self.result = self.result.rstrip()
elif tag.lower() == 'li':
# we must remove any non-relevant spacing and end of
# line before
self.result = self.result.rstrip()
if self.previous_type_lists[-1] == 'ol':
self.nb += 1
self.result += '\n' + self.line_quotation + \
' ' * len(self.previous_type_lists) + \
str(self.nb) + '. '
else:
self.result += '\n' + self.line_quotation + \
' ' * len(self.previous_type_lists) + '* '
elif tag.lower() == 'a':
# self.previous_type_lists.append(tag.lower())
for (attr, value) in attrs:
if attr.lower() == 'href':
self.url = value
self.result += '<' + value + '>' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_entityref(self, name):
"""Process a general entity reference of the form "&name;". Transform to text whenever possible.""" |
char_code = html_entities.name2codepoint.get(name, None)
if char_code is not None:
try:
self.result += unichr(char_code).encode("utf-8")
except:
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bethe_lattice(energy, hopping):
"""Bethe lattice in inf dim density of states""" |
energy = np.asarray(energy).clip(-2*hopping, 2*hopping)
return np.sqrt(4*hopping**2 - energy**2) / (2*np.pi*hopping**2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bethe_fermi(energy, quasipart, shift, hopping, beta):
"""product of the bethe lattice dos, fermi distribution""" |
return fermi_dist(quasipart * energy - shift, beta) \
* bethe_lattice(energy, hopping) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.