_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q39700 | LigolwSegments.insert_from_segmentlistdict | train | def insert_from_segmentlistdict(self, seglists, name, version = None, comment = None, valid=None):
"""
Insert the segments from the segmentlistdict object
seglists as a new list of "active" segments into this
LigolwSegments object. The dictionary's keys are assumed
to provide the instrument name for each seg... | python | {
"resource": ""
} |
q39701 | LigolwSegments.get_by_name | train | def get_by_name(self, name, clip_to_valid = False):
"""
Retrieve the active segmentlists whose name equals name.
The result is a segmentlistdict indexed by instrument. All
segmentlist objects within it will be copies of the
contents of this object, modifications will not affect the
contents of this object.... | python | {
"resource": ""
} |
q39702 | LigolwSegments.finalize | train | def finalize(self, process_row = None):
"""
Restore the LigolwSegmentList objects to the XML tables in
preparation for output. All segments from all segment
lists are inserted into the tables in time order, but this
is NOT behaviour external applications should rely on.
This is done simply in the belief th... | python | {
"resource": ""
} |
q39703 | GraphBuilder.add_graph | train | def add_graph(self, rhs_graph):
"""
Adds a graph to self.g
:param rhs_graph: the graph to add
:return: itself
"""
rhs_graph = self.__substitute_names_in_graph(rhs_graph)
self.g = self.__merge_graphs(self.g, rhs_graph)
return self | python | {
"resource": ""
} |
q39704 | GraphBuilder.set | train | def set(self, code):
"""
Executes the code and apply it to the self.g
:param code: the LISP code to execute
:return: True/False, depending on the result of the LISP code
"""
if self.update:
self.vertices_substitution_dict, self.edges_substitution_dict, self.m... | python | {
"resource": ""
} |
q39705 | get_lock | train | def get_lock(lockfile):
"""
Tries to write a lockfile containing the current pid. Excepts if
the lockfile already contains the pid of a running process.
Although this should prevent a lock from being granted twice, it
can theoretically deny a lock unjustly in the unlikely event that
the origin... | python | {
"resource": ""
} |
q39706 | confirm_lock | train | def confirm_lock(lockfile):
"""
Confirm that the given lockfile contains our pid.
Should be entirely unecessary, but paranoia always served me well.
"""
pidfile = open(lockfile, "r")
pidfile_pid = pidfile.readline().strip()
pidfile.close()
if int(pidfile_pid) != os.getpid():
rais... | python | {
"resource": ""
} |
q39707 | _totuple | train | def _totuple( x ):
"""Utility stuff to convert string, int, long, float, None or anything to a usable tuple."""
if isinstance( x, basestring ):
out = x,
elif isinstance( x, ( int, long, float ) ):
out = str( x ),
elif x is None:
out = None,
else:
out = tuple( x )
... | python | {
"resource": ""
} |
q39708 | escape | train | def escape( text, newline=False ):
"""Escape special html characters."""
if isinstance( text, basestring ):
if '&' in text:
text = text.replace( '&', '&' )
if '>' in text:
text = text.replace( '>', '>' )
if '<' in text:
text = text.replace( '<'... | python | {
"resource": ""
} |
q39709 | element.render | train | def render( self, tag, single, between, kwargs ):
"""Append the actual tags to content."""
out = "<%s" % tag
for key, value in list( kwargs.items( ) ):
if value is not None: # when value is None that means stuff like <... checked>
key = key.strip('_') ... | python | {
"resource": ""
} |
q39710 | element.close | train | def close( self ):
"""Append a closing tag unless element has only opening tag."""
if self.tag in self.parent.twotags:
self.parent.content.append( "</%s>" % self.tag )
elif self.tag in self.parent.onetags:
raise ClosingError( self.tag )
elif self.parent.mode == '... | python | {
"resource": ""
} |
q39711 | element.open | train | def open( self, **kwargs ):
"""Append an opening tag."""
if self.tag in self.parent.twotags or self.tag in self.parent.onetags:
self.render( self.tag, False, None, kwargs )
elif self.mode == 'strict_html' and self.tag in self.parent.deptags:
raise DeprecationError( self.... | python | {
"resource": ""
} |
q39712 | MultiIter | train | def MultiIter(*sequences):
"""
A generator for iterating over the elements of multiple sequences
simultaneously. With N sequences given as input, the generator
yields all possible distinct N-tuples that contain one element from
each of the input sequences.
Example:
>>> x = MultiIter([0, 1, 2], [10, 11])
>>> ... | python | {
"resource": ""
} |
q39713 | choices | train | def choices(vals, n):
"""
A generator for iterating over all choices of n elements from the
input sequence vals. In each result returned, the original order
of the values is preserved.
Example:
>>> x = choices(["a", "b", "c"], 2)
>>> list(x)
[('a', 'b'), ('a', 'c'), ('b', 'c')]
The order of combinations in... | python | {
"resource": ""
} |
q39714 | nonuniq | train | def nonuniq(iterable):
"""
Yield the non-unique items of an iterable, preserving order. If an
item occurs N > 0 times in the input sequence, it will occur N-1
times in the output sequence.
Example:
>>> x = nonuniq([0, 0, 2, 6, 2, 0, 5])
>>> list(x)
[0, 2, 0]
"""
temp_dict = {}
for e in iterable:
if e in... | python | {
"resource": ""
} |
q39715 | inorder | train | def inorder(*iterables, **kwargs):
"""
A generator that yields the values from several ordered iterables
in order.
Example:
>>> x = [0, 1, 2, 3]
>>> y = [1.5, 2.5, 3.5, 4.5]
>>> z = [1.75, 2.25, 3.75, 4.25]
>>> list(inorder(x, y, z))
[0, 1, 1.5, 1.75, 2, 2.25, 2.5, 3, 3.5, 3.75, 4.25, 4.5]
>>> list(inorder(... | python | {
"resource": ""
} |
q39716 | randindex | train | def randindex(lo, hi, n = 1.):
"""
Yields integers in the range [lo, hi) where 0 <= lo < hi. Each
return value is a two-element tuple. The first element is the
random integer, the second is the natural logarithm of the
probability with which that integer will be chosen.
The CDF for the distribution from which ... | python | {
"resource": ""
} |
q39717 | segment.shift | train | def shift(self, x):
"""
Return a new segment whose bounds are given by adding x to
the segment's upper and lower bounds.
"""
return tuple.__new__(self.__class__, (self[0] + x, self[1] + x)) | python | {
"resource": ""
} |
q39718 | segmentlist.extent | train | def extent(self):
"""
Return the segment whose end-points denote the maximum and
minimum extent of the segmentlist. Does not require the
segmentlist to be coalesced.
"""
if not len(self):
raise ValueError("empty list")
min, max = self[0]
for lo, hi in self:
if min > lo:
min = lo
if max < h... | python | {
"resource": ""
} |
q39719 | segmentlist.find | train | def find(self, item):
"""
Return the smallest i such that i is the index of an
element that wholly contains item. Raises ValueError if no
such element exists. Does not require the segmentlist to
be coalesced.
"""
for i, seg in enumerate(self):
if item in seg:
return i
raise ValueError(item) | python | {
"resource": ""
} |
q39720 | segmentlistdict.map | train | def map(self, func):
"""
Return a dictionary of the results of func applied to each
of the segmentlist objects in self.
Example:
>>> x = segmentlistdict()
>>> x["H1"] = segmentlist([segment(0, 10)])
>>> x["H2"] = segmentlist([segment(5, 15)])
>>> x.map(lambda l: 12 in l)
{'H2': True, 'H1': False}
... | python | {
"resource": ""
} |
q39721 | segmentlistdict.keys_at | train | def keys_at(self, x):
"""
Return a list of the keys for the segment lists that
contain x.
Example:
>>> x = segmentlistdict()
>>> x["H1"] = segmentlist([segment(0, 10)])
>>> x["H2"] = segmentlist([segment(5, 15)])
>>> x.keys_at(12)
['H2']
"""
return [key for key, segs in self.items() if x in segs... | python | {
"resource": ""
} |
q39722 | segmentlistdict.intersects_segment | train | def intersects_segment(self, seg):
"""
Returns True if any segmentlist in self intersects the
segment, otherwise returns False.
"""
return any(value.intersects_segment(seg) for value in self.itervalues()) | python | {
"resource": ""
} |
q39723 | segmentlistdict.intersects | train | def intersects(self, other):
"""
Returns True if there exists a segmentlist in self that
intersects the corresponding segmentlist in other; returns
False otherwise.
See also:
.intersects_all(), .all_intersects(), .all_intersects_all()
"""
return any(key in self and self[key].intersects(value) for key... | python | {
"resource": ""
} |
q39724 | segmentlistdict.intersects_all | train | def intersects_all(self, other):
"""
Returns True if each segmentlist in other intersects the
corresponding segmentlist in self; returns False
if this is not the case, or if other is empty.
See also:
.intersects(), .all_intersects(), .all_intersects_all()
"""
return all(key in self and self[key].inte... | python | {
"resource": ""
} |
q39725 | segmentlistdict.all_intersects_all | train | def all_intersects_all(self, other):
"""
Returns True if self and other have the same keys, and each
segmentlist intersects the corresponding segmentlist in the
other; returns False if this is not the case or if either
dictionary is empty.
See also:
.intersects(), .all_intersects(), .intersects_all()
... | python | {
"resource": ""
} |
q39726 | segmentlistdict.extend | train | def extend(self, other):
"""
Appends the segmentlists from other to the corresponding
segmentlists in self, adding new segmentslists to self as
needed.
"""
for key, value in other.iteritems():
if key not in self:
self[key] = _shallowcopy(value)
else:
self[key].extend(value) | python | {
"resource": ""
} |
q39727 | segmentlistdict.extract_common | train | def extract_common(self, keys):
"""
Return a new segmentlistdict containing only those
segmentlists associated with the keys in keys, with each
set to their mutual intersection. The offsets are
preserved.
"""
keys = set(keys)
new = self.__class__()
intersection = self.intersection(keys)
for key in ... | python | {
"resource": ""
} |
q39728 | segmentlistdict.intersection | train | def intersection(self, keys):
"""
Return the intersection of the segmentlists associated with
the keys in keys.
"""
keys = set(keys)
if not keys:
return segmentlist()
seglist = _shallowcopy(self[keys.pop()])
for key in keys:
seglist &= self[key]
return seglist | python | {
"resource": ""
} |
q39729 | extract | train | def extract(connection, filename, table_names = None, verbose = False, xsl_file = None):
"""
Convert the database at the given connection to a tabular LIGO
Light-Weight XML document. The XML document is written to the file
named filename. If table_names is not None, it should be a
sequence of strings and only th... | python | {
"resource": ""
} |
q39730 | append_search_summary | train | def append_search_summary(xmldoc, process, shared_object = "standalone", lalwrapper_cvs_tag = "", lal_cvs_tag = "", comment = None, ifos = None, inseg = None, outseg = None, nevents = 0, nnodes = 1):
"""
Append search summary information associated with the given process
to the search summary table in xmldoc. Retur... | python | {
"resource": ""
} |
q39731 | common_options | train | def common_options(func):
"""Commonly used command options."""
def parse_preset(ctx, param, value):
return PRESETS.get(value, (None, None))
def parse_private(ctx, param, value):
return hex_from_b64(value) if value else None
func = click.option('--private', default=None, help='Private.... | python | {
"resource": ""
} |
q39732 | get_session_data | train | def get_session_data( username, password_verifier, salt, client_public, private, preset):
"""Print out server session data."""
session = SRPServerSession(
SRPContext(username, prime=preset[0], generator=preset[1]),
hex_from_b64(password_verifier), private=private)
session.process(client_pub... | python | {
"resource": ""
} |
q39733 | get_session_data | train | def get_session_data(ctx, username, password, salt, server_public, private, preset):
"""Print out client session data."""
session = SRPClientSession(
SRPContext(username, password, prime=preset[0], generator=preset[1]),
private=private)
session.process(server_public, salt, base64=True)
... | python | {
"resource": ""
} |
q39734 | cwd_decorator | train | def cwd_decorator(func):
"""
decorator to change cwd to directory containing rst for this function
"""
def wrapper(*args, **kw):
cur_dir = os.getcwd()
found = False
for arg in sys.argv:
if arg.endswith(".rst"):
found = arg
break
... | python | {
"resource": ""
} |
q39735 | to_xml | train | def to_xml(node, pretty=False):
""" convert an etree node to xml """
fout = Sio()
etree = et.ElementTree(node)
etree.write(fout)
xml = fout.getvalue()
if pretty:
xml = pretty_xml(xml, True)
return xml | python | {
"resource": ""
} |
q39736 | pretty_xml | train | def pretty_xml(string_input, add_ns=False):
""" pretty indent string_input """
if add_ns:
elem = "<foo "
for key, value in DOC_CONTENT_ATTRIB.items():
elem += ' %s="%s"' % (key, value)
string_input = elem + ">" + string_input + "</foo>"
doc = minidom.parseString(string_in... | python | {
"resource": ""
} |
q39737 | add_cell | train | def add_cell(preso, pos, width, height, padding=1, top_margin=4, left_margin=2):
""" Add a text frame to current slide """
available_width = SLIDE_WIDTH
available_width -= left_margin * 2
available_width -= padding * (width - 1)
column_width = available_width / width
avail_height = SLIDE_HEIGHT
... | python | {
"resource": ""
} |
q39738 | Preso.add_otp_style | train | def add_otp_style(self, zip_odp, style_file):
"""
takes the slide content and merges in the style_file
"""
style = zipwrap.Zippier(style_file)
for picture_file in style.ls("Pictures"):
zip_odp.write(picture_file, style.cat(picture_file, True))
xml_data = style... | python | {
"resource": ""
} |
q39739 | Picture.update_frame_attributes | train | def update_frame_attributes(self, attrib):
""" For positioning update the frame """
if "align" in self.user_defined:
align = self.user_defined["align"]
if "top" in align:
attrib["style:vertical-pos"] = "top"
if "right" in align:
attrib... | python | {
"resource": ""
} |
q39740 | Slide.update_style | train | def update_style(self, mapping):
"""Use to update fill-color"""
default = {
"presentation:background-visible": "true",
"presentation:background-objects-visible": "true",
"draw:fill": "solid",
"draw:fill-color": "#772953",
"draw:fill-image-width... | python | {
"resource": ""
} |
q39741 | Slide._copy | train | def _copy(self):
""" needs to update page numbers """
ins = copy.copy(self)
ins._fire_page_number(self.page_number + 1)
return ins | python | {
"resource": ""
} |
q39742 | Slide.get_node | train | def get_node(self):
"""return etree Element representing this slide"""
# already added title, text frames
# add animation chunks
if self.animations:
anim_par = el("anim:par", attrib={"presentation:node-type": "timing-root"})
self._page.append(anim_par)
... | python | {
"resource": ""
} |
q39743 | Slide.add_list | train | def add_list(self, bl):
"""
note that this pushes the cur_element, but doesn't pop it.
You'll need to do that
"""
# text:list doesn't like being a child of text:p
if self.cur_element is None:
self.add_text_frame()
self.push_element()
self.cur_e... | python | {
"resource": ""
} |
q39744 | Slide.add_table | train | def add_table(self, t):
"""
remember to call pop_element after done with table
"""
self.push_element()
self._page.append(t.node)
self.cur_element = t | python | {
"resource": ""
} |
q39745 | XMLSlide.update_text | train | def update_text(self, mapping):
"""Iterate over nodes, replace text with mapping"""
found = False
for node in self._page.iter("*"):
if node.text or node.tail:
for old, new in mapping.items():
if node.text and old in node.text:
... | python | {
"resource": ""
} |
q39746 | MixedContent.parent_of | train | def parent_of(self, name):
"""
go to parent of node with name, and set as cur_node. Useful
for creating new paragraphs
"""
if not self._in_tag(name):
return
node = self.cur_node
while node.tag != name:
node = node.getparent()
self.... | python | {
"resource": ""
} |
q39747 | MixedContent._is_last_child | train | def _is_last_child(self, tagname, attributes=None):
"""
Check if last child of cur_node is tagname with attributes
"""
children = self.cur_node.getchildren()
if children:
result = self._is_node(tagname, attributes, node=children[-1])
return result
... | python | {
"resource": ""
} |
q39748 | MixedContent._in_tag | train | def _in_tag(self, tagname, attributes=None):
"""
Determine if we are already in a certain tag.
If we give attributes, make sure they match.
"""
node = self.cur_node
while not node is None:
if node.tag == tagname:
if attributes and node.attrib =... | python | {
"resource": ""
} |
q39749 | MixedContent._check_add_node | train | def _check_add_node(self, parent, name):
""" Returns False if bad to make name a child of parent """
if name == ns("text", "a"):
if parent.tag == ns("draw", "text-box"):
return False
return True | python | {
"resource": ""
} |
q39750 | MixedContent._add_styles | train | def _add_styles(self, add_paragraph=True, add_text=True):
"""
Adds paragraph and span wrappers if necessary based on style
"""
p_styles = self.get_para_styles()
t_styles = self.get_span_styles()
for s in self.slide.pending_styles:
if isinstance(s, ParagraphSty... | python | {
"resource": ""
} |
q39751 | MixedContent.line_break | train | def line_break(self):
"""insert as many line breaks as the insert_line_break variable says
"""
for i in range(self.slide.insert_line_break):
# needs to be inside text:p
if not self._in_tag(ns("text", "p")):
# we can just add a text:p and no line-break
... | python | {
"resource": ""
} |
q39752 | Table.__tableStringParser | train | def __tableStringParser(self, tableString):
"""
Will parse and check tableString parameter for any invalid strings.
Args:
tableString (str): Standard table string with header and decisions.
Raises:
ValueError: tableString is empty.
ValueError: One of the header element is not unique.
ValueError: M... | python | {
"resource": ""
} |
q39753 | Table.__replaceSpecialValues | train | def __replaceSpecialValues(self, decisions):
"""
Will replace special values in decisions array.
Args:
decisions (array of array of str): Standard decision array format.
Raises:
ValueError: Row element don't have parent value.
Returns:
New decision array with updated values.
"""
error = []
fo... | python | {
"resource": ""
} |
q39754 | Table.__toString | train | def __toString(self, values):
"""
Will replace dict values with string values
Args:
values (dict): Dictionary of values
Returns:
Updated values dict
"""
for key in values:
if not values[key] is str:
values[key] = str(values[key])
return values | python | {
"resource": ""
} |
q39755 | Table.__valueKeyWithHeaderIndex | train | def __valueKeyWithHeaderIndex(self, values):
"""
This is hellper function, so that we can mach decision values with row index
as represented in header index.
Args:
values (dict): Normaly this will have dict of header values and values from decision
Return:
>>> return()
{
values[headerName] : in... | python | {
"resource": ""
} |
q39756 | Table.__checkDecisionParameters | train | def __checkDecisionParameters(self, result, **values):
"""
Checker of decision parameters, it will raise ValueError if finds something wrong.
Args:
result (array of str): See public decision methods
**values (array of str): See public decision methods
Raise:
ValueError: Result array none.
ValueErr... | python | {
"resource": ""
} |
q39757 | Table.__getDecision | train | def __getDecision(self, result, multiple=False, **values):
"""
The main method for decision picking.
Args:
result (array of str): What values you want to get in return array.
multiple (bolean, optional): Do you want multiple result if it finds many maching decisions.
**values (dict): What should finder ... | python | {
"resource": ""
} |
q39758 | Table.decision | train | def decision(self, result, **values):
"""
The decision method with callback option. This method will find matching row, construct
a dictionary and call callback with dictionary.
Args:
callback (function): Callback function will be called when decision will be finded.
result (array of str): Array of heade... | python | {
"resource": ""
} |
q39759 | Table.allDecisions | train | def allDecisions(self, result, **values):
"""
Joust like self.decision but for multiple finded values.
Returns:
Arrays of arrays of finded elements or if finds only one mach, array of strings.
"""
data = self.__getDecision(result, multiple=True, **values)
data = [data[value] for value in result]
if le... | python | {
"resource": ""
} |
q39760 | ThriftConnection._dict_to_map_str_str | train | def _dict_to_map_str_str(self, d):
"""
Thrift requires the params and headers dict values to only contain str values.
"""
return dict(map(
lambda (k, v): (k, str(v).lower() if isinstance(v, bool) else str(v)),
d.iteritems()
)) | python | {
"resource": ""
} |
q39761 | suppress_stdout | train | def suppress_stdout():
"""
Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test
"""
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout | python | {
"resource": ""
} |
q39762 | clean_title | train | def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile(r'\W*'
r'\... | python | {
"resource": ""
} |
q39763 | get_ext | train | def get_ext(url):
"""
Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present.
"""
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(pars... | python | {
"resource": ""
} |
q39764 | delete_duplicates | train | def delete_duplicates(seq):
"""
Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | python | {
"resource": ""
} |
q39765 | RethinkCollection.joinOn | train | def joinOn(self, model, onIndex):
"""
Performs an eqJoin on with the given model. The resulting join will be
accessible through the models name.
"""
return self._joinOnAsPriv(model, onIndex, model.__name__) | python | {
"resource": ""
} |
q39766 | RethinkCollection.joinOnAs | train | def joinOnAs(self, model, onIndex, whatAs):
"""
Like `joinOn` but allows setting the joined results name to access it
from.
Performs an eqJoin on with the given model. The resulting join will be
accessible through the given name.
"""
return self._joinOnAsPriv(mod... | python | {
"resource": ""
} |
q39767 | RethinkCollection._joinOnAsPriv | train | def _joinOnAsPriv(self, model, onIndex, whatAs):
"""
Private method for handling joins.
"""
if self._join:
raise Exception("Already joined with a table!")
self._join = model
self._joinedField = whatAs
table = model.table
self._query = self._qu... | python | {
"resource": ""
} |
q39768 | RethinkCollection.orderBy | train | def orderBy(self, field, direct="desc"):
"""
Allows for the results to be ordered by a specific field. If given,
direction can be set with passing an additional argument in the form
of "asc" or "desc"
"""
if direct == "desc":
self._query = self._query.order_by... | python | {
"resource": ""
} |
q39769 | RethinkCollection.offset | train | def offset(self, value):
"""
Allows for skipping a specified number of results in query. Useful
for pagination.
"""
self._query = self._query.skip(value)
return self | python | {
"resource": ""
} |
q39770 | RethinkCollection.limit | train | def limit(self, value):
"""
Allows for limiting number of results returned for query. Useful
for pagination.
"""
self._query = self._query.limit(value)
return self | python | {
"resource": ""
} |
q39771 | RethinkCollection.fetch | train | def fetch(self):
"""
Fetches the query and then tries to wrap the data in the model, joining
as needed, if applicable.
"""
returnResults = []
results = self._query.run()
for result in results:
if self._join:
# Because we can tell the m... | python | {
"resource": ""
} |
q39772 | coerce_put_post | train | def coerce_put_post(request):
"""
Django doesn't particularly understand REST.
In case we send data over PUT, Django won't
actually look at the data and load it. We need
to twist its arm here.
The try/except abominiation here is due to a bug
in mod_python. This should fix it.
"""
if... | python | {
"resource": ""
} |
q39773 | Mimer.loader_for_type | train | def loader_for_type(self, ctype):
"""
Gets a function ref to deserialize content
for a certain mimetype.
"""
for loadee, mimes in Mimer.TYPES.iteritems():
for mime in mimes:
if ctype.startswith(mime):
return loadee | python | {
"resource": ""
} |
q39774 | getsteps | train | def getsteps(levels, tagmax):
""" Returns a list with the max number of posts per "tagcloud level"
"""
ntw = levels
if ntw < 2:
ntw = 2
steps = [(stp, 1 + (stp * int(math.ceil(tagmax * 1.0 / ntw - 1))))
for stp in range(ntw)]
# just to be sure~
steps[-1] = (steps[-1][0], tagmax+1)
return steps | python | {
"resource": ""
} |
q39775 | build | train | def build(site, tagdata):
""" Returns the tag cloud for a list of tags.
"""
tagdata.sort()
# we get the most popular tag to calculate the tags' weigth
tagmax = 0
for tagname, tagcount in tagdata:
if tagcount > tagmax:
tagmax = tagcount
steps = getsteps(site.tagcloud_levels, tagmax)
tags = []
for tagnam... | python | {
"resource": ""
} |
q39776 | getquery | train | def getquery(query):
'Performs a query and get the results.'
try:
conn = connection.cursor()
conn.execute(query)
data = conn.fetchall()
conn.close()
except: data = list()
return data | python | {
"resource": ""
} |
q39777 | getcloud | train | def getcloud(site, feed_id=None):
""" Returns the tag cloud for a site or a site's subscriber.
"""
cloudict = fjcache.cache_get(site.id, 'tagclouds')
if not cloudict:
cloudict = cloudata(site)
fjcache.cache_set(site, 'tagclouds', cloudict)
# A subscriber's tag cloud has been requested.
if feed_id:
feed_id... | python | {
"resource": ""
} |
q39778 | extract_stations | train | def extract_stations(page):
'''Extract bus stations from routine page.
:param page: crawled page.
'''
stations = [_(station.value) for station in page('.stateName')]
return {
'terminal': {
stations[0]: list(reversed(stations)),
stations[-1]: stations
},
... | python | {
"resource": ""
} |
q39779 | extract_current_routine | train | def extract_current_routine(page, stations):
'''Extract current routine information from page.
:param page: crawled page.
:param stations: bus stations list. See `~extract_stations`.
'''
current_routines = CURRENT_ROUTINE_PATTERN.findall(page.text())
if not current_routines:
return
... | python | {
"resource": ""
} |
q39780 | extract_bus_routine | train | def extract_bus_routine(page):
'''Extract bus routine information from page.
:param page: crawled page.
'''
if not isinstance(page, pq):
page = pq(page)
stations = extract_stations(page)
return {
# Routine name.
'name': extract_routine_name(page),
# Bus station... | python | {
"resource": ""
} |
q39781 | RethinkModel._grabData | train | def _grabData(self, key):
"""
Tries to find the existing document in the database, if it is found,
then the objects _data is set to that document, and this returns
`True`, otherwise this will return `False`
:param key: The primary key of the object we're looking for
:typ... | python | {
"resource": ""
} |
q39782 | RethinkModel.save | train | def save(self):
"""
If an id exists in the database, we assume we'll update it, and if not
then we'll insert it. This could be a problem with creating your own
id's on new objects, however luckily, we keep track of if this is a new
object through a private _new variable, and use ... | python | {
"resource": ""
} |
q39783 | RethinkModel.delete | train | def delete(self):
"""
Deletes the current instance. This assumes that we know what we're
doing, and have a primary key in our data already. If this is a new
instance, then we'll let the user know with an Exception
"""
if self._new:
raise Exception("This is a n... | python | {
"resource": ""
} |
q39784 | BGTree.add_edge | train | def add_edge(self, node1_name, node2_name, edge_length=DEFAULT_EDGE_LENGTH):
""" Adds a new edge to the current tree with specified characteristics
Forbids addition of an edge, if a parent node is not present
Forbids addition of an edge, if a child node already exists
:param node1_name... | python | {
"resource": ""
} |
q39785 | BGTree.__get_node_by_name | train | def __get_node_by_name(self, name):
""" Returns a first TreeNode object, which name matches the specified argument
:raises: ValueError (if no node with specified name is present in the tree)
"""
try:
for entry in filter(lambda x: x.name == name, self.nodes()):
... | python | {
"resource": ""
} |
q39786 | BGTree.__has_edge | train | def __has_edge(self, node1_name, node2_name, account_for_direction=True):
""" Returns a boolean flag, telling if a tree has an edge with two nodes, specified by their names as arguments
If a account_for_direction is specified as True, the order of specified node names has to relate to parent - child re... | python | {
"resource": ""
} |
q39787 | BGTree.__get_v_tree_consistent_leaf_based_hashable_multicolors | train | def __get_v_tree_consistent_leaf_based_hashable_multicolors(self):
""" Internally used method, that recalculates VTree-consistent sets of leaves in the current tree """
result = []
nodes = deque([self.__root])
while len(nodes) > 0:
current_node = nodes.popleft()
c... | python | {
"resource": ""
} |
q39788 | reload | train | def reload(*command, ignore_patterns=[]):
"""Reload given command"""
path = "."
sig = signal.SIGTERM
delay = 0.25
ignorefile = ".reloadignore"
ignore_patterns = ignore_patterns or load_ignore_patterns(ignorefile)
event_handler = ReloadEventHandler(ignore_patterns)
reloader = Reloader(c... | python | {
"resource": ""
} |
q39789 | reload_me | train | def reload_me(*args, ignore_patterns=[]):
"""Reload currently running command with given args"""
command = [sys.executable, sys.argv[0]]
command.extend(args)
reload(*command, ignore_patterns=ignore_patterns) | python | {
"resource": ""
} |
q39790 | GRIMMReader.parse_data_string | train | def parse_data_string(data_string):
""" Parses a string assumed to contain gene order data, retrieving information about fragment type, gene order, blocks names and their orientation
First checks if gene order termination signs are present.
Selects the earliest one.
Checks that informat... | python | {
"resource": ""
} |
q39791 | GRIMMReader.__assign_vertex_pair | train | def __assign_vertex_pair(block):
""" Assigns usual BreakpointGraph type vertices to supplied block.
Vertices are labeled as "block_name" + "h" and "block_name" + "t" according to blocks orientation.
:param block: information about a genomic block to create a pair of vertices for in a format of... | python | {
"resource": ""
} |
q39792 | GRIMMReader.get_breakpoint_graph | train | def get_breakpoint_graph(stream, merge_edges=True):
""" Taking a file-like object transforms supplied gene order data into the language of
:param merge_edges: a flag that indicates if parallel edges in produced breakpoint graph shall be merged or not
:type merge_edges: ``bool``
:param s... | python | {
"resource": ""
} |
q39793 | BGGenome.from_json | train | def from_json(cls, data, json_schema_class=None):
""" JSON deserialization method that retrieves a genome instance from its json representation
If specific json schema is provided, it is utilized, and if not, a class specific is used
"""
schema = cls.json_schema if json_schema_class is ... | python | {
"resource": ""
} |
q39794 | send_file | train | def send_file(request, filename, content_type='image/jpeg'):
"""
Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for... | python | {
"resource": ""
} |
q39795 | send_zipfile | train | def send_zipfile(request, fileList):
"""
Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files.... | python | {
"resource": ""
} |
q39796 | enable | train | def enable():
"""
Enable all benchmarking.
"""
Benchmark.enable = True
ComparisonBenchmark.enable = True
BenchmarkedFunction.enable = True
BenchmarkedClass.enable = True | python | {
"resource": ""
} |
q39797 | disable | train | def disable():
"""
Disable all benchmarking.
"""
Benchmark.enable = False
ComparisonBenchmark.enable = False
BenchmarkedFunction.enable = False
BenchmarkedClass.enable = False | python | {
"resource": ""
} |
q39798 | TaggedVertex.add_tag | train | def add_tag(self, tag, value):
""" as tags are kept in a sorted order, a bisection is a fastest way to identify a correct position
of or a new tag to be added. An additional check is required to make sure w don't add duplicates
"""
index = bisect_left(self.tags, (tag, value))
con... | python | {
"resource": ""
} |
q39799 | BGEdge.colors_json_ids | train | def colors_json_ids(self):
""" A proxy property based access to vertices in current edge
When edge is serialized to JSON object, no explicit object for its multicolor is created, but rather all colors,
taking into account their multiplicity, are referenced by their json_ids.
"""
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.