text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def str_numerator(self):
"""Returns the numerator with formatting."""
unit_numerator, unit = UnitByte(self.numerator).auto_no_thousands
if unit_numerator >= 10:
formatter = '%d'
else:
formatter = '%0.1f'
return '{0} {1}'.format(locale.format(formatter, uni... | [
"def",
"str_numerator",
"(",
"self",
")",
":",
"unit_numerator",
",",
"unit",
"=",
"UnitByte",
"(",
"self",
".",
"numerator",
")",
".",
"auto_no_thousands",
"if",
"unit_numerator",
">=",
"10",
":",
"formatter",
"=",
"'%d'",
"else",
":",
"formatter",
"=",
"... | 43.5 | 20 |
def as_string(self, forsigning=False):
"""
>>> len(OmapiMessage().as_string(True)) >= 24
True
@type forsigning: bool
@rtype: bytes
@raises OmapiSizeLimitError:
"""
ret = OutBuffer()
self.serialize(ret, forsigning)
return ret.getvalue() | [
"def",
"as_string",
"(",
"self",
",",
"forsigning",
"=",
"False",
")",
":",
"ret",
"=",
"OutBuffer",
"(",
")",
"self",
".",
"serialize",
"(",
"ret",
",",
"forsigning",
")",
"return",
"ret",
".",
"getvalue",
"(",
")"
] | 20.416667 | 14.916667 |
def add_output_list_opt(self, opt, outputs):
""" Add an option that determines a list of outputs
"""
self.add_opt(opt)
for out in outputs:
self.add_opt(out)
self._add_output(out) | [
"def",
"add_output_list_opt",
"(",
"self",
",",
"opt",
",",
"outputs",
")",
":",
"self",
".",
"add_opt",
"(",
"opt",
")",
"for",
"out",
"in",
"outputs",
":",
"self",
".",
"add_opt",
"(",
"out",
")",
"self",
".",
"_add_output",
"(",
"out",
")"
] | 32.571429 | 7.142857 |
def servo_config(self, pin, min_pulse=544, max_pulse=2400):
"""
This method configures the Arduino for servo operation.
:param pin: Servo control pin
:param min_pulse: Minimum pulse width
:param max_pulse: Maximum pulse width
:returns: No return value
"""
... | [
"def",
"servo_config",
"(",
"self",
",",
"pin",
",",
"min_pulse",
"=",
"544",
",",
"max_pulse",
"=",
"2400",
")",
":",
"task",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"core",
".",
"servo_config",
"(",
"pin",
",",
"min_pulse",
",",
"max_... | 32.8 | 19.333333 |
def post_process(self):
""" Apply last 2D transforms"""
self.image.putdata(self.pixels)
self.image = self.image.transpose(Image.ROTATE_90) | [
"def",
"post_process",
"(",
"self",
")",
":",
"self",
".",
"image",
".",
"putdata",
"(",
"self",
".",
"pixels",
")",
"self",
".",
"image",
"=",
"self",
".",
"image",
".",
"transpose",
"(",
"Image",
".",
"ROTATE_90",
")"
] | 39.75 | 9 |
def get_form(self, form_class=None):
'''
Set form groups to the groups specified in the view if defined
'''
formobj = super(GenModify, self).get_form(form_class)
# Set requested group to this form
selfgroups = getattr(self, "form_groups", None)
if selfgroups:
... | [
"def",
"get_form",
"(",
"self",
",",
"form_class",
"=",
"None",
")",
":",
"formobj",
"=",
"super",
"(",
"GenModify",
",",
"self",
")",
".",
"get_form",
"(",
"form_class",
")",
"# Set requested group to this form",
"selfgroups",
"=",
"getattr",
"(",
"self",
"... | 33.5 | 18 |
def node_labels(node_labels, node_indices):
"""Validate that there is a label for each node."""
if len(node_labels) != len(node_indices):
raise ValueError("Labels {0} must label every node {1}.".format(
node_labels, node_indices))
if len(node_labels) != len(set(node_labels)):
ra... | [
"def",
"node_labels",
"(",
"node_labels",
",",
"node_indices",
")",
":",
"if",
"len",
"(",
"node_labels",
")",
"!=",
"len",
"(",
"node_indices",
")",
":",
"raise",
"ValueError",
"(",
"\"Labels {0} must label every node {1}.\"",
".",
"format",
"(",
"node_labels",
... | 47.125 | 15.5 |
def append_to_file(file_name, line_data):
"""append a line of text to a file"""
with open(file_name, mode='a', encoding='utf-8') as f1:
f1.write(line_data)
f1.write("\n") | [
"def",
"append_to_file",
"(",
"file_name",
",",
"line_data",
")",
":",
"with",
"open",
"(",
"file_name",
",",
"mode",
"=",
"'a'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f1",
":",
"f1",
".",
"write",
"(",
"line_data",
")",
"f1",
".",
"write",
"(... | 38 | 10.2 |
def getCanonicalRep(record_cluster):
"""
Given a list of records within a duplicate cluster, constructs a
canonical representation of the cluster by finding canonical
values for each field
"""
canonical_rep = {}
keys = record_cluster[0].keys()
for key in keys:
key_values = []
... | [
"def",
"getCanonicalRep",
"(",
"record_cluster",
")",
":",
"canonical_rep",
"=",
"{",
"}",
"keys",
"=",
"record_cluster",
"[",
"0",
"]",
".",
"keys",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"key_values",
"=",
"[",
"]",
"for",
"record",
"in",
"record... | 28.375 | 18.375 |
def energy_at_conditions(self, pH, V):
"""
Get free energy for a given pH and V
Args:
pH (float): pH at which to evaluate free energy
V (float): voltage at which to evaluate free energy
Returns:
free energy at conditions
"""
return se... | [
"def",
"energy_at_conditions",
"(",
"self",
",",
"pH",
",",
"V",
")",
":",
"return",
"self",
".",
"energy",
"+",
"self",
".",
"npH",
"*",
"PREFAC",
"*",
"pH",
"+",
"self",
".",
"nPhi",
"*",
"V"
] | 29.916667 | 17.416667 |
def on_connection_unblocked(self, method_frame):
"""When RabbitMQ indicates the connection is unblocked, set the state
appropriately.
:param pika.amqp_object.Method method_frame: Unblocked method frame
"""
LOGGER.debug('Connection unblocked: %r', method_frame)
self.stat... | [
"def",
"on_connection_unblocked",
"(",
"self",
",",
"method_frame",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Connection unblocked: %r'",
",",
"method_frame",
")",
"self",
".",
"state",
"=",
"self",
".",
"STATE_READY",
"if",
"self",
".",
"on_ready",
":",
"self"... | 35.272727 | 17.272727 |
def read_var_uint32(self):
"""Reads a varint from the stream, interprets this varint
as an unsigned, 32-bit integer, and returns the integer.
"""
i = self.read_var_uint64()
if i > wire_format.UINT32_MAX:
raise errors.DecodeError('Value out of range for uint32: %d' % i... | [
"def",
"read_var_uint32",
"(",
"self",
")",
":",
"i",
"=",
"self",
".",
"read_var_uint64",
"(",
")",
"if",
"i",
">",
"wire_format",
".",
"UINT32_MAX",
":",
"raise",
"errors",
".",
"DecodeError",
"(",
"'Value out of range for uint32: %d'",
"%",
"i",
")",
"ret... | 41.375 | 13.375 |
def _reaction_to_dicts(reaction):
"""Convert a reaction to reduced left, right dictionaries.
Returns a pair of (left, right) dictionaries mapping compounds to
normalized integer stoichiometric values. If a compound occurs multiple
times on one side, the occurences are combined into a single entry in th... | [
"def",
"_reaction_to_dicts",
"(",
"reaction",
")",
":",
"def",
"dict_from_iter_sum",
"(",
"it",
",",
"div",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"it",
":",
"if",
"k",
"not",
"in",
"d",
":",
"d",
"[",
"k",
"]",
"=",
"0",
"... | 31.416667 | 20.458333 |
def _import_ucsmsdk(self):
"""Imports the Ucsm SDK module.
This module is not installed as part of the normal Neutron
distributions. It is imported dynamically in this module so that
the import can be mocked, allowing unit testing without requiring
the installation of UcsSdk.
... | [
"def",
"_import_ucsmsdk",
"(",
"self",
")",
":",
"# Check if SSL certificate checking has been disabled.",
"# If so, warn the user before proceeding.",
"if",
"not",
"CONF",
".",
"ml2_cisco_ucsm",
".",
"ucsm_https_verify",
":",
"LOG",
".",
"warning",
"(",
"const",
".",
"SS... | 39.954545 | 19.681818 |
def read_seg(self, parc_type='aparc'):
"""Read the MRI segmentation.
Parameters
----------
parc_type : str
'aparc' or 'aparc.a2009s'
Returns
-------
numpy.ndarray
3d matrix with values
numpy.ndarray
4x4 affine matrix
... | [
"def",
"read_seg",
"(",
"self",
",",
"parc_type",
"=",
"'aparc'",
")",
":",
"seg_file",
"=",
"self",
".",
"dir",
"/",
"'mri'",
"/",
"(",
"parc_type",
"+",
"'+aseg.mgz'",
")",
"seg_mri",
"=",
"load",
"(",
"seg_file",
")",
"seg_aff",
"=",
"seg_mri",
".",... | 25.5 | 15.2 |
def _wrapped(self):
"""
Wrap this udf with a function and attach docstring from func
"""
# It is possible for a callable instance without __name__ attribute or/and
# __module__ attribute to be wrapped here. For example, functools.partial. In this case,
# we should avoid ... | [
"def",
"_wrapped",
"(",
"self",
")",
":",
"# It is possible for a callable instance without __name__ attribute or/and",
"# __module__ attribute to be wrapped here. For example, functools.partial. In this case,",
"# we should avoid wrapping the attributes from the wrapped function to the wrapper",
... | 45.357143 | 24.928571 |
def lock():
'''
Attempts an exclusive lock on the candidate configuration. This
is a non-blocking call.
.. note::
When locking, it is important to remember to call
:py:func:`junos.unlock <salt.modules.junos.unlock>` once finished. If
locking during orchestration, remember to inc... | [
"def",
"lock",
"(",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"try",
":",
"conn",
".",
"cu",
".",
"lock",
"(",
")",
"ret",
"[",
"'message'",
"]",
"=",
... | 28.142857 | 25.5 |
def get_probability_masks(self, non_valid_value=0):
"""
Get probability maps of areas for each available date. The pixels without valid data are assigned
non_valid_value.
:param non_valid_value: Value to be assigned to non valid data pixels
:type non_valid_value: float
:... | [
"def",
"get_probability_masks",
"(",
"self",
",",
"non_valid_value",
"=",
"0",
")",
":",
"if",
"self",
".",
"probability_masks",
"is",
"None",
":",
"self",
".",
"get_data",
"(",
")",
"self",
".",
"probability_masks",
"=",
"self",
".",
"cloud_detector",
".",
... | 43.9375 | 23.4375 |
def from_list(lst):
"""Parses list
:param lst: list of elements
:return: LinkedList: Nodes from list
"""
if not lst:
return None
head = Node(lst[0], None)
if len(lst) == 1:
return head
head.next_node = LinkedList.from_list(lst[1... | [
"def",
"from_list",
"(",
"lst",
")",
":",
"if",
"not",
"lst",
":",
"return",
"None",
"head",
"=",
"Node",
"(",
"lst",
"[",
"0",
"]",
",",
"None",
")",
"if",
"len",
"(",
"lst",
")",
"==",
"1",
":",
"return",
"head",
"head",
".",
"next_node",
"="... | 20.5 | 18.8125 |
def removeComponent(self, component):
"""
Remove ``component`` from the glyph.
>>> glyph.removeComponent(component)
``component`` may be a :ref:`BaseComponent` or an
:ref:`type-int` representing a component index.
"""
if isinstance(component, int):
... | [
"def",
"removeComponent",
"(",
"self",
",",
"component",
")",
":",
"if",
"isinstance",
"(",
"component",
",",
"int",
")",
":",
"index",
"=",
"component",
"else",
":",
"index",
"=",
"self",
".",
"_getComponentIndex",
"(",
"component",
")",
"index",
"=",
"... | 35.235294 | 13.588235 |
def add_for_targets(self, targets, products):
"""Updates the products for the given targets, adding to existing entries.
:API: public
"""
# TODO: This is a temporary helper for use until the classpath has been split.
for target in targets:
self.add_for_target(target, products) | [
"def",
"add_for_targets",
"(",
"self",
",",
"targets",
",",
"products",
")",
":",
"# TODO: This is a temporary helper for use until the classpath has been split.",
"for",
"target",
"in",
"targets",
":",
"self",
".",
"add_for_target",
"(",
"target",
",",
"products",
")"
... | 37.125 | 16 |
def export(self, output, tight=False, concat=True, close_pdf=None,
use_time=False, **kwargs):
"""Exports the figures of the project to one or more image files
Parameters
----------
output: str, iterable or matplotlib.backends.backend_pdf.PdfPages
if string or ... | [
"def",
"export",
"(",
"self",
",",
"output",
",",
"tight",
"=",
"False",
",",
"concat",
"=",
"True",
",",
"close_pdf",
"=",
"None",
",",
"use_time",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"matplotlib",
".",
"backends",
".",
"backend... | 38.331081 | 21.054054 |
def _remove_api_url_from_link(link):
'''Remove the API URL from the link if it is there'''
if link.startswith(_api_url()):
link = link[len(_api_url()):]
if link.startswith(_api_url(mirror=True)):
link = link[len(_api_url(mirror=True)):]
return link | [
"def",
"_remove_api_url_from_link",
"(",
"link",
")",
":",
"if",
"link",
".",
"startswith",
"(",
"_api_url",
"(",
")",
")",
":",
"link",
"=",
"link",
"[",
"len",
"(",
"_api_url",
"(",
")",
")",
":",
"]",
"if",
"link",
".",
"startswith",
"(",
"_api_ur... | 39.142857 | 9.714286 |
def iter_variants_by_names(self, names):
"""Iterates over the genotypes for variants using a list of names.
Args:
names (list): The list of names for variant extraction.
"""
for name in names:
for result in self.get_variant_by_name(name):
yield r... | [
"def",
"iter_variants_by_names",
"(",
"self",
",",
"names",
")",
":",
"for",
"name",
"in",
"names",
":",
"for",
"result",
"in",
"self",
".",
"get_variant_by_name",
"(",
"name",
")",
":",
"yield",
"result"
] | 31.6 | 17.7 |
def encode_json_body(data):
"""
Return prettified JSON `data`, set ``response.content_type`` to
``application/json; charset=utf-8``.
Args:
data (any): Any basic python data structure.
Returns:
str: Data converted to prettified JSON.
"""
# support for StringIO / file - like ... | [
"def",
"encode_json_body",
"(",
"data",
")",
":",
"# support for StringIO / file - like objects",
"if",
"hasattr",
"(",
"data",
",",
"\"read\"",
")",
":",
"return",
"data",
"response",
".",
"content_type",
"=",
"\"application/json; charset=utf-8\"",
"return",
"json",
... | 23.272727 | 20.545455 |
def get_channels(self, condensed=False):
'''Grabs all channels in the slack team
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dic: Dict of channels in Slack team.
See also: https://api.slack.com/methods/channels.list
... | [
"def",
"get_channels",
"(",
"self",
",",
"condensed",
"=",
"False",
")",
":",
"channel_list",
"=",
"self",
".",
"slack_client",
".",
"api_call",
"(",
"'channels.list'",
")",
"if",
"not",
"channel_list",
".",
"get",
"(",
"'ok'",
")",
":",
"return",
"None",
... | 32.190476 | 23.333333 |
def to_str(self, s):
'''
In py2 converts a unicode to str (bytes) using utf-8.
-- in py3 raises an error if it's not str already.
'''
if s.__class__ != str:
if not IS_PY3K:
s = s.encode('utf-8')
else:
raise AssertionError('E... | [
"def",
"to_str",
"(",
"self",
",",
"s",
")",
":",
"if",
"s",
".",
"__class__",
"!=",
"str",
":",
"if",
"not",
"IS_PY3K",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
"else",
":",
"raise",
"AssertionError",
"(",
"'Expected to have str on Pyth... | 35.909091 | 23.363636 |
def get_referenced_object(referring_object, fieldname):
"""
Get an object referred to by a field in another object.
For example an object of type Construction has fields for each layer, each
of which refers to a Material. This functions allows the object
representing a Material to be fetched using ... | [
"def",
"get_referenced_object",
"(",
"referring_object",
",",
"fieldname",
")",
":",
"idf",
"=",
"referring_object",
".",
"theidf",
"object_list",
"=",
"referring_object",
".",
"getfieldidd_item",
"(",
"fieldname",
",",
"u'object-list'",
")",
"for",
"obj_type",
"in"... | 36.69697 | 23.545455 |
def draw(self, img, pixmapper, bounds):
'''draw a polygon on the image'''
if self.hidden:
return
(x,y,w,h) = bounds
spacing = 1000
while True:
start = mp_util.latlon_round((x,y), spacing)
dist = mp_util.gps_distance(x,y,x+w,y+h)
cou... | [
"def",
"draw",
"(",
"self",
",",
"img",
",",
"pixmapper",
",",
"bounds",
")",
":",
"if",
"self",
".",
"hidden",
":",
"return",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
"=",
"bounds",
"spacing",
"=",
"1000",
"while",
"True",
":",
"start",
"=... | 39.12 | 20.8 |
def complete(self):
"""
Returns whether or not this manager has reached a "completed" state.
"""
if not self._techniques:
return False
if not any(tech._is_overriden('complete') for tech in self._techniques):
return False
return self.completion_mode... | [
"def",
"complete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_techniques",
":",
"return",
"False",
"if",
"not",
"any",
"(",
"tech",
".",
"_is_overriden",
"(",
"'complete'",
")",
"for",
"tech",
"in",
"self",
".",
"_techniques",
")",
":",
"return... | 44 | 24 |
def _ScopesFromMetadataServer(self, scopes):
"""Returns instance scopes based on GCE metadata server."""
if not util.DetectGce():
raise exceptions.ResourceUnavailableError(
'GCE credentials requested outside a GCE instance')
if not self.GetServiceAccount(self.__servic... | [
"def",
"_ScopesFromMetadataServer",
"(",
"self",
",",
"scopes",
")",
":",
"if",
"not",
"util",
".",
"DetectGce",
"(",
")",
":",
"raise",
"exceptions",
".",
"ResourceUnavailableError",
"(",
"'GCE credentials requested outside a GCE instance'",
")",
"if",
"not",
"self... | 49.684211 | 16.263158 |
def find_phase(self, obj):
r"""
Find the Phase associated with a given object.
Parameters
----------
obj : OpenPNM Object
Can either be a Physics or Algorithm object
Returns
-------
An OpenPNM Phase object.
Raises
------
... | [
"def",
"find_phase",
"(",
"self",
",",
"obj",
")",
":",
"# If received phase, just return self",
"if",
"obj",
".",
"_isa",
"(",
"'phase'",
")",
":",
"return",
"obj",
"# If phase happens to be in settings (i.e. algorithm), look it up",
"if",
"'phase'",
"in",
"obj",
"."... | 33.9 | 19.6 |
def write_sub_file(self):
"""
Write a submit file for this Condor job.
"""
if not self.__log_file:
raise CondorSubmitError, "Log file not specified."
if not self.__err_file:
raise CondorSubmitError, "Error file not specified."
if not self.__out_file:
raise CondorSubmitError, "O... | [
"def",
"write_sub_file",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__log_file",
":",
"raise",
"CondorSubmitError",
",",
"\"Log file not specified.\"",
"if",
"not",
"self",
".",
"__err_file",
":",
"raise",
"CondorSubmitError",
",",
"\"Error file not specified... | 38.584416 | 18.142857 |
def list_of_matching(self, tup_tree, matched):
"""
Parse only the children of particular types defined in the list/tuple
matched under tup_tree.
Other children are ignored rather than giving an error.
"""
result = []
for child in kids(tup_tree):
if ... | [
"def",
"list_of_matching",
"(",
"self",
",",
"tup_tree",
",",
"matched",
")",
":",
"result",
"=",
"[",
"]",
"for",
"child",
"in",
"kids",
"(",
"tup_tree",
")",
":",
"if",
"name",
"(",
"child",
")",
"not",
"in",
"matched",
":",
"continue",
"result",
"... | 26.8125 | 19.0625 |
def write(cls, filename, samples, write_params=None, static_args=None,
**metadata):
"""Writes the injection samples to the given hdf file.
Parameters
----------
filename : str
The name of the file to write to.
samples : io.FieldArray
FieldAr... | [
"def",
"write",
"(",
"cls",
",",
"filename",
",",
"samples",
",",
"write_params",
"=",
"None",
",",
"static_args",
"=",
"None",
",",
"*",
"*",
"metadata",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"'w'",
")",
"as",
"fp",
":",
"# ... | 40.757576 | 12.969697 |
def load_xml_attrs(self):
"""
Load XML attributes as object attributes.
:returns: List of parsed attributes.
:rtype: list
"""
attrs_list = list()
if hasattr(self, 'xml_element'):
xml_attrs = self.xml_element.attrib
for variable, value i... | [
"def",
"load_xml_attrs",
"(",
"self",
")",
":",
"attrs_list",
"=",
"list",
"(",
")",
"if",
"hasattr",
"(",
"self",
",",
"'xml_element'",
")",
":",
"xml_attrs",
"=",
"self",
".",
"xml_element",
".",
"attrib",
"for",
"variable",
",",
"value",
"in",
"iter",... | 26.409091 | 17.227273 |
def init_app(self, app, router=None, realm=None, in_twisted=None):
"""Configure and call the :meth:`AutobahnSync.start` method
:param app: Flask app to configure
:param router: WAMP router to connect to
:param realm: WAMP realm to connect to
:param in_twisted: Is the code is goi... | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"router",
"=",
"None",
",",
"realm",
"=",
"None",
",",
"in_twisted",
"=",
"None",
")",
":",
"router",
"=",
"router",
"or",
"app",
".",
"config",
".",
"get",
"(",
"'AUTHOBAHN_ROUTER'",
")",
"realm",
"="... | 46.047619 | 22.333333 |
def _set_child_joined_alias_using_join_map(child, join_map, alias_map):
"""
Set the joined alias on the child, for Django <= 1.7.x.
:param child:
:param join_map:
:param alias_map:
"""
for lhs, table, join_cols in join_map:
if lhs is None:
... | [
"def",
"_set_child_joined_alias_using_join_map",
"(",
"child",
",",
"join_map",
",",
"alias_map",
")",
":",
"for",
"lhs",
",",
"table",
",",
"join_cols",
"in",
"join_map",
":",
"if",
"lhs",
"is",
"None",
":",
"continue",
"if",
"lhs",
"==",
"child",
".",
"a... | 33.416667 | 15.75 |
def _FormatSocketUnixToken(self, token_data):
"""Formats an Unix socket token as a dictionary of values.
Args:
token_data (bsm_token_data_sockunix): AUT_SOCKUNIX token data.
Returns:
dict[str, str]: token values.
"""
protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_family, 'UNKN... | [
"def",
"_FormatSocketUnixToken",
"(",
"self",
",",
"token_data",
")",
":",
"protocol",
"=",
"bsmtoken",
".",
"BSM_PROTOCOLS",
".",
"get",
"(",
"token_data",
".",
"socket_family",
",",
"'UNKNOWN'",
")",
"return",
"{",
"'protocols'",
":",
"protocol",
",",
"'fami... | 31.428571 | 18.357143 |
def get_conversations(self):
"""
Returns list of Conversation objects
"""
cs = self.data["data"]
res = []
for c in cs:
res.append(Conversation(c))
return res | [
"def",
"get_conversations",
"(",
"self",
")",
":",
"cs",
"=",
"self",
".",
"data",
"[",
"\"data\"",
"]",
"res",
"=",
"[",
"]",
"for",
"c",
"in",
"cs",
":",
"res",
".",
"append",
"(",
"Conversation",
"(",
"c",
")",
")",
"return",
"res"
] | 24.222222 | 10.444444 |
def is_extension_supported(request, extension_alias):
"""Check if a specified extension is supported.
:param request: django request object
:param extension_alias: neutron extension alias
"""
extensions = list_extensions(request)
for extension in extensions:
if extension['alias'] == ext... | [
"def",
"is_extension_supported",
"(",
"request",
",",
"extension_alias",
")",
":",
"extensions",
"=",
"list_extensions",
"(",
"request",
")",
"for",
"extension",
"in",
"extensions",
":",
"if",
"extension",
"[",
"'alias'",
"]",
"==",
"extension_alias",
":",
"retu... | 31.416667 | 12.583333 |
def generate(ast_tree: ast.Tree, model_name: str):
"""
:param ast_tree: AST to generate from
:param model_name: class to generate
:return: sympy source code for model
"""
component_ref = ast.ComponentRef.from_string(model_name)
ast_tree_new = copy.deepcopy(ast_tree)
ast_walker = TreeWalk... | [
"def",
"generate",
"(",
"ast_tree",
":",
"ast",
".",
"Tree",
",",
"model_name",
":",
"str",
")",
":",
"component_ref",
"=",
"ast",
".",
"ComponentRef",
".",
"from_string",
"(",
"model_name",
")",
"ast_tree_new",
"=",
"copy",
".",
"deepcopy",
"(",
"ast_tree... | 39 | 9 |
def set_dataset_date(self, dataset_date, dataset_end_date=None, date_format=None):
# type: (str, Optional[str], Optional[str]) -> None
"""Set dataset date from string using specified format. If no format is supplied, the function will guess.
For unambiguous formats, this should be fine.
... | [
"def",
"set_dataset_date",
"(",
"self",
",",
"dataset_date",
",",
"dataset_end_date",
"=",
"None",
",",
"date_format",
"=",
"None",
")",
":",
"# type: (str, Optional[str], Optional[str]) -> None",
"parsed_date",
"=",
"self",
".",
"_parse_date",
"(",
"dataset_date",
",... | 48.631579 | 25.842105 |
def cmdline_params(self,
distance_matrix_file_name='distance.matrix',
remote_folder_path=None):
"""Synthesize command line parameters
e.g. [ ['--output-file', 'out.barcode'], ['distance_matrix.file']]
:param distance_matrix_file_name: Name of dista... | [
"def",
"cmdline_params",
"(",
"self",
",",
"distance_matrix_file_name",
"=",
"'distance.matrix'",
",",
"remote_folder_path",
"=",
"None",
")",
":",
"parameters",
"=",
"[",
"]",
"pm_dict",
"=",
"self",
".",
"get_dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
... | 34.75 | 22 |
def is_editable(self, request):
"""
Restrict in-line editing to the objects's owner and superusers.
"""
return request.user.is_superuser or request.user.id == self.user_id | [
"def",
"is_editable",
"(",
"self",
",",
"request",
")",
":",
"return",
"request",
".",
"user",
".",
"is_superuser",
"or",
"request",
".",
"user",
".",
"id",
"==",
"self",
".",
"user_id"
] | 39.8 | 15 |
def setlist(self, key, new_list):
# type: (Hashable, List[Any]) -> None
"""
Remove the old values for a key and add new ones. Note that the list
you pass the values in will be shallow-copied before it is inserted in
the dictionary.
>>> d = MultiValueDict()
>>> d.... | [
"def",
"setlist",
"(",
"self",
",",
"key",
",",
"new_list",
")",
":",
"# type: (Hashable, List[Any]) -> None",
"dict",
".",
"__setitem__",
"(",
"self",
",",
"key",
",",
"list",
"(",
"new_list",
")",
")"
] | 38.764706 | 15.705882 |
def list(self, **kwargs):
"""Retrieve a list of objects.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_list (bool): ... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_compute_path",
"(",
"'/projects/%(project_id)s/forks'",
")",
"return",
"ListMixin",
".",
"list",
"(",
"self",
",",
"path",
"=",
"path",
",",
"*",
"*",
"kwargs",
... | 41.238095 | 26.619048 |
def _apply_policy_config(policy_spec, policy_dict):
'''Applies a policy dictionary to a policy spec'''
log.trace('policy_dict = %s', policy_dict)
if policy_dict.get('name'):
policy_spec.name = policy_dict['name']
if policy_dict.get('description'):
policy_spec.description = policy_dict['d... | [
"def",
"_apply_policy_config",
"(",
"policy_spec",
",",
"policy_dict",
")",
":",
"log",
".",
"trace",
"(",
"'policy_dict = %s'",
",",
"policy_dict",
")",
"if",
"policy_dict",
".",
"get",
"(",
"'name'",
")",
":",
"policy_spec",
".",
"name",
"=",
"policy_dict",
... | 53.638298 | 17.723404 |
def query_topology_db(self, dict_convert=False, **req):
"""Query an entry to the topology DB. """
session = db.get_session()
with session.begin(subtransactions=True):
try:
# Check if entry exists.
topo_disc = session.query(DfaTopologyDb).filter_by(**re... | [
"def",
"query_topology_db",
"(",
"self",
",",
"dict_convert",
"=",
"False",
",",
"*",
"*",
"req",
")",
":",
"session",
"=",
"db",
".",
"get_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
"subtransactions",
"=",
"True",
")",
":",
"try",
":",
... | 43.076923 | 13.923077 |
def _submitQuery(self, gitquery, gitvars={}, verbose=False, rest=False):
"""Send a curl request to GitHub.
Args:
gitquery (str): The query or endpoint itself.
Examples:
query: 'query { viewer { login } }'
endpoint: '/user'
... | [
"def",
"_submitQuery",
"(",
"self",
",",
"gitquery",
",",
"gitvars",
"=",
"{",
"}",
",",
"verbose",
"=",
"False",
",",
"rest",
"=",
"False",
")",
":",
"errOut",
"=",
"DEVNULL",
"if",
"not",
"verbose",
"else",
"None",
"authhead",
"=",
"'Authorization: bea... | 39.28125 | 19.8125 |
def parse_raw_token(self, raw_token):
"Parse token and secret from raw token response."
if raw_token is None:
return (None, None)
# Load as json first then parse as query string
try:
token_data = json.loads(raw_token)
except ValueError:
qs = pa... | [
"def",
"parse_raw_token",
"(",
"self",
",",
"raw_token",
")",
":",
"if",
"raw_token",
"is",
"None",
":",
"return",
"(",
"None",
",",
"None",
")",
"# Load as json first then parse as query string",
"try",
":",
"token_data",
"=",
"json",
".",
"loads",
"(",
"raw_... | 36.846154 | 13.461538 |
def simplified_edges(self):
"""
A generator for getting all of the edges without consuming extra
memory.
"""
for group, edgelist in self.edges.items():
for u, v, d in edgelist:
yield (u, v) | [
"def",
"simplified_edges",
"(",
"self",
")",
":",
"for",
"group",
",",
"edgelist",
"in",
"self",
".",
"edges",
".",
"items",
"(",
")",
":",
"for",
"u",
",",
"v",
",",
"d",
"in",
"edgelist",
":",
"yield",
"(",
"u",
",",
"v",
")"
] | 31.25 | 12 |
def fromapi(_class, apiresponse):
"""Create a bulletin object from an API response (dict), containing `sbj`, etc."""
for resp in apiresponse['sb']:
# Extract details from dict
_id = "n/a" or resp.get("nm")
subject = resp.get("sbj")
text = resp.get('dtl') +... | [
"def",
"fromapi",
"(",
"_class",
",",
"apiresponse",
")",
":",
"for",
"resp",
"in",
"apiresponse",
"[",
"'sb'",
"]",
":",
"# Extract details from dict",
"_id",
"=",
"\"n/a\"",
"or",
"resp",
".",
"get",
"(",
"\"nm\"",
")",
"subject",
"=",
"resp",
".",
"ge... | 45 | 16.666667 |
def _insert_layer_between(self, src, snk, new_layer, new_keras_layer):
"""
Insert the new_layer before layer, whose position is layer_idx. The new layer's
parameter is stored in a Keras layer called new_keras_layer
"""
if snk is None:
insert_pos = self.layer_list.inde... | [
"def",
"_insert_layer_between",
"(",
"self",
",",
"src",
",",
"snk",
",",
"new_layer",
",",
"new_keras_layer",
")",
":",
"if",
"snk",
"is",
"None",
":",
"insert_pos",
"=",
"self",
".",
"layer_list",
".",
"index",
"(",
"src",
")",
"+",
"1",
"else",
":",... | 43.894737 | 14.526316 |
def verify(self, obj):
"""Verify that the object conforms to this verifier's schema
Args:
obj (object): A python object to verify
Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thrown with at least the reaso... | [
"def",
"verify",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
"!=",
"self",
".",
"_literal",
":",
"raise",
"ValidationError",
"(",
"\"Object is not equal to literal\"",
",",
"reason",
"=",
"'%s is not equal to %s'",
"%",
"(",
"str",
"(",
"obj",
")",
",",
... | 36.705882 | 27.352941 |
def init_registry(mongo, model_defs, clear_collection=False):
"""Initialize a model registry with a list of model definitions in Json
format.
Parameters
----------
mongo : scodata.MongoDBFactory
Connector for MongoDB
model_defs : list()
List of model definitions in Json-like for... | [
"def",
"init_registry",
"(",
"mongo",
",",
"model_defs",
",",
"clear_collection",
"=",
"False",
")",
":",
"# Create model registry",
"registry",
"=",
"DefaultModelRegistry",
"(",
"mongo",
")",
"# Drop collection if clear flag is set to True",
"if",
"clear_collection",
":"... | 31.730769 | 14.807692 |
def modify(self, **params):
"""https://developers.coinbase.com/api#modify-an-account"""
data = self.api_client.update_account(self.id, **params)
self.update(data)
return data | [
"def",
"modify",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"data",
"=",
"self",
".",
"api_client",
".",
"update_account",
"(",
"self",
".",
"id",
",",
"*",
"*",
"params",
")",
"self",
".",
"update",
"(",
"data",
")",
"return",
"data"
] | 40.4 | 14.6 |
def fishers_method(pvals):
"""Fisher's method for combining independent p-values."""
pvals = np.asarray(pvals)
degrees_of_freedom = 2 * pvals.size
chisq_stat = np.sum(-2*np.log(pvals))
fishers_pval = stats.chi2.sf(chisq_stat, degrees_of_freedom)
return fishers_pval | [
"def",
"fishers_method",
"(",
"pvals",
")",
":",
"pvals",
"=",
"np",
".",
"asarray",
"(",
"pvals",
")",
"degrees_of_freedom",
"=",
"2",
"*",
"pvals",
".",
"size",
"chisq_stat",
"=",
"np",
".",
"sum",
"(",
"-",
"2",
"*",
"np",
".",
"log",
"(",
"pval... | 40.428571 | 9.714286 |
def splits(cls, fields, root=".data", train="train.txt",
test="test.txt", validation_frac=0.1, **kwargs):
"""Downloads and loads the CoNLL 2000 Chunking dataset.
NOTE: There is only a train and test dataset so we use
10% of the train set as validation
"""
tr... | [
"def",
"splits",
"(",
"cls",
",",
"fields",
",",
"root",
"=",
"\".data\"",
",",
"train",
"=",
"\"train.txt\"",
",",
"test",
"=",
"\"test.txt\"",
",",
"validation_frac",
"=",
"0.1",
",",
"*",
"*",
"kwargs",
")",
":",
"train",
",",
"test",
"=",
"super",
... | 36.153846 | 19.461538 |
def gated_linear_unit_layer(x, name=None):
"""Gated linear unit layer.
Paper: Language Modeling with Gated Convolutional Networks.
Link: https://arxiv.org/abs/1612.08083
x = Wx * sigmoid(W'x).
Args:
x: A tensor
name: A string
Returns:
A tensor of the same shape as x.
"""
with tf.variable_... | [
"def",
"gated_linear_unit_layer",
"(",
"x",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"glu_layer\"",
",",
"values",
"=",
"[",
"x",
"]",
")",
":",
"depth",
"=",
"shape_list",
"(",
"... | 27.210526 | 17.315789 |
def find_course_and_crosslistings(self, partial):
"""Returns the given course and all other courses it is
crosslisted with.
"""
course = self.find_course(partial)
crosslisted = self.crosslisted_with(course.crn)
return (course,) + tuple(map(self.find_course_by_crn, crossli... | [
"def",
"find_course_and_crosslistings",
"(",
"self",
",",
"partial",
")",
":",
"course",
"=",
"self",
".",
"find_course",
"(",
"partial",
")",
"crosslisted",
"=",
"self",
".",
"crosslisted_with",
"(",
"course",
".",
"crn",
")",
"return",
"(",
"course",
",",
... | 45.714286 | 10.857143 |
def redirect_to_url(req, url, redirection_type=None, norobot=False):
"""
Redirect current page to url.
@param req: request as received from apache
@param url: url to redirect to
@param redirection_type: what kind of redirection is required:
e.g.: apache.HTTP_MULTIPLE_CHOICES = 300
... | [
"def",
"redirect_to_url",
"(",
"req",
",",
"url",
",",
"redirection_type",
"=",
"None",
",",
"norobot",
"=",
"False",
")",
":",
"url",
"=",
"url",
".",
"strip",
"(",
")",
"if",
"redirection_type",
"is",
"None",
":",
"redirection_type",
"=",
"apache",
"."... | 41.791667 | 21.555556 |
def _kl_laplace_laplace(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Laplace.
Args:
a: instance of a Laplace distribution object.
b: instance of a Laplace distribution object.
name: (optional) Name to use for created operations.
default is "kl_laplace_laplace".... | [
"def",
"_kl_laplace_laplace",
"(",
"a",
",",
"b",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"\"kl_laplace_laplace\"",
")",
":",
"# Consistent with",
"# http://www.mast.queensu.ca/~communications/Papers/gil-msc11.pdf, page 38... | 33.65 | 17.25 |
def build_or_install_bokehjs():
''' Build a new BokehJS (and install it) or install a previously build
BokehJS.
If no options ``--build-js`` or ``--install-js`` are detected, the
user is prompted for what to do.
If ``--existing-js`` is detected, then this setup.py is being run from a
packaged ... | [
"def",
"build_or_install_bokehjs",
"(",
")",
":",
"# This happens when building from inside a published, pre-packaged sdist",
"# The --existing-js option is not otherwise documented",
"if",
"'--existing-js'",
"in",
"sys",
".",
"argv",
":",
"sys",
".",
"argv",
".",
"remove",
"("... | 31.44898 | 25.244898 |
def _create_embedded_unclaimed_draft_with_template(self, test_mode=False, client_id=None, is_for_embedded_signing=False, template_id=None, template_ids=None, requester_email_address=None, title=None, subject=None, message=None, signers=None, ccs=None, signing_redirect_url=None, requesting_redirect_url=None, metadata=No... | [
"def",
"_create_embedded_unclaimed_draft_with_template",
"(",
"self",
",",
"test_mode",
"=",
"False",
",",
"client_id",
"=",
"None",
",",
"is_for_embedded_signing",
"=",
"False",
",",
"template_id",
"=",
"None",
",",
"template_ids",
"=",
"None",
",",
"requester_emai... | 46.302326 | 27.465116 |
def principal_curve(data, basis='pca', n_comps=4, clusters_list=None, copy=False):
"""Computes the principal curve
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
basis: `str` (default: `'pca'`)
Basis to use for computing the principal curve.
n_com... | [
"def",
"principal_curve",
"(",
"data",
",",
"basis",
"=",
"'pca'",
",",
"n_comps",
"=",
"4",
",",
"clusters_list",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"adata",
"=",
"data",
".",
"copy",
"(",
")",
"if",
"copy",
"else",
"data",
"import",
... | 35.326087 | 20.108696 |
def serialize(obj, no_dump=False):
"""
Serialize an object.
Returns a dict containing an `_error` property if a MemoryError happens during the
object serialization. See #369.
:param obj: the object to serialize
:type obj: alignak.objects.item.Item | dict | list | str
:param no_dump: if Tru... | [
"def",
"serialize",
"(",
"obj",
",",
"no_dump",
"=",
"False",
")",
":",
"# print(\"Serialize (%s): %s\" % (no_dump, obj))",
"if",
"hasattr",
"(",
"obj",
",",
"\"serialize\"",
")",
"and",
"isinstance",
"(",
"obj",
".",
"serialize",
",",
"collections",
".",
"Calla... | 31.9375 | 24.354167 |
def _object_instance_content(obj):
"""
Returns consistant content for a action class or an instance thereof
:Parameters:
- `obj` Should be either and action class or an instance thereof
:Returns:
bytearray or bytes representing the obj suitable for generating a signature from.
"""
... | [
"def",
"_object_instance_content",
"(",
"obj",
")",
":",
"retval",
"=",
"bytearray",
"(",
")",
"if",
"obj",
"is",
"None",
":",
"return",
"b'N.'",
"if",
"isinstance",
"(",
"obj",
",",
"SCons",
".",
"Util",
".",
"BaseStringTypes",
")",
":",
"return",
"SCon... | 34.215686 | 23.078431 |
def lgammln(xx):
"""
Returns the gamma function of xx.
Gamma(z) = Integral(0,infinity) of t^(z-1)exp(-t) dt.
(Adapted from: Numerical Recipies in C.)
Usage: lgammln(xx)
"""
coeff = [76.18009173, -86.50532033, 24.01409822, -1.231739516,
0.120858003e-2, -0.536382e-5]
x = xx - 1.0
tmp ... | [
"def",
"lgammln",
"(",
"xx",
")",
":",
"coeff",
"=",
"[",
"76.18009173",
",",
"-",
"86.50532033",
",",
"24.01409822",
",",
"-",
"1.231739516",
",",
"0.120858003e-2",
",",
"-",
"0.536382e-5",
"]",
"x",
"=",
"xx",
"-",
"1.0",
"tmp",
"=",
"x",
"+",
"5.5... | 25.789474 | 15.789474 |
def adapt(self, d, x):
"""
Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array)
"""
y = np.dot(self.w, x)
e = d - y
nu = self.mu / (self.eps + np.dot(x, x))
... | [
"def",
"adapt",
"(",
"self",
",",
"d",
",",
"x",
")",
":",
"y",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"w",
",",
"x",
")",
"e",
"=",
"d",
"-",
"y",
"nu",
"=",
"self",
".",
"mu",
"/",
"(",
"self",
".",
"eps",
"+",
"np",
".",
"dot",
"... | 24 | 17.714286 |
def stop(self):
"""Stop the progress bar."""
if self._progressing:
self._progressing = False
self._thread.join() | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_progressing",
":",
"self",
".",
"_progressing",
"=",
"False",
"self",
".",
"_thread",
".",
"join",
"(",
")"
] | 29.6 | 9.6 |
def find(self, table_name, constraints=None, *, columns=None, order_by=None):
"""Returns the first record that matches the given criteria.
:table_name: the name of the table to search on
:constraints: is any construct that can be parsed by SqlWriter.parse_constraints.
:columns: either a string or a lis... | [
"def",
"find",
"(",
"self",
",",
"table_name",
",",
"constraints",
"=",
"None",
",",
"*",
",",
"columns",
"=",
"None",
",",
"order_by",
"=",
"None",
")",
":",
"query_string",
",",
"params",
"=",
"self",
".",
"sql_writer",
".",
"get_find_all_query",
"(",
... | 49 | 18.916667 |
def set_process_type(self, value):
"""
Setter for 'process_type' field.
:param value - a new value of 'process_type' field.
"""
if value is None or not isinstance(value, str):
raise TypeError("ProcessType must be set to a String")
elif value not in Process.__p... | [
"def",
"set_process_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"ProcessType must be set to a String\"",
")",
"elif",
"value",
"not",
"in... | 44.181818 | 15.636364 |
def args(self) -> str:
"""Provides arguments for the command."""
return '{}{}{}{}{}'.format(
to_ascii_hex(self._index, 2),
to_ascii_hex(self._group_number, 2),
to_ascii_hex(self._unit_number, 2),
to_ascii_hex(int(self._enable_status), 4),
to_as... | [
"def",
"args",
"(",
"self",
")",
"->",
"str",
":",
"return",
"'{}{}{}{}{}'",
".",
"format",
"(",
"to_ascii_hex",
"(",
"self",
".",
"_index",
",",
"2",
")",
",",
"to_ascii_hex",
"(",
"self",
".",
"_group_number",
",",
"2",
")",
",",
"to_ascii_hex",
"(",... | 43.125 | 7.75 |
def _filter_validate(filepath, location, values, validate):
"""Generator for validate() results called against all given values. On
errors, fields are warned about and ignored, unless strict mode is set in
which case a compiler error is raised.
"""
for value in values:
if not isinstance(valu... | [
"def",
"_filter_validate",
"(",
"filepath",
",",
"location",
",",
"values",
",",
"validate",
")",
":",
"for",
"value",
"in",
"values",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"warn_invalid",
"(",
"filepath",
",",
"location",
... | 44.5625 | 16.8125 |
def max_repetition_level(self, path):
"""Get the max repetition level for the given schema path."""
max_level = 0
for part in path:
element = self.schema_element(part)
if element.repetition_type == parquet_thrift.FieldRepetitionType.REQUIRED:
max_level += ... | [
"def",
"max_repetition_level",
"(",
"self",
",",
"path",
")",
":",
"max_level",
"=",
"0",
"for",
"part",
"in",
"path",
":",
"element",
"=",
"self",
".",
"schema_element",
"(",
"part",
")",
"if",
"element",
".",
"repetition_type",
"==",
"parquet_thrift",
".... | 42.375 | 14.5 |
def schema(self, shex: Optional[Union[str, ShExJ.Schema]]) -> None:
""" Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed schema.
:param shex: Schema
"""
self.pfx = None
if shex is not None:
if isinstance(shex, ShExJ.Schema):
... | [
"def",
"schema",
"(",
"self",
",",
"shex",
":",
"Optional",
"[",
"Union",
"[",
"str",
",",
"ShExJ",
".",
"Schema",
"]",
"]",
")",
"->",
"None",
":",
"self",
".",
"pfx",
"=",
"None",
"if",
"shex",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",... | 44.052632 | 16 |
def tofile(self, f):
"""Serialize this ScalableBloomFilter into the file-object
`f'."""
f.write(pack(self.FILE_FMT, self.scale, self.ratio,
self.initial_capacity, self.error_rate))
# Write #-of-filters
f.write(pack(b'<l', len(self.filters)))
if len(... | [
"def",
"tofile",
"(",
"self",
",",
"f",
")",
":",
"f",
".",
"write",
"(",
"pack",
"(",
"self",
".",
"FILE_FMT",
",",
"self",
".",
"scale",
",",
"self",
".",
"ratio",
",",
"self",
".",
"initial_capacity",
",",
"self",
".",
"error_rate",
")",
")",
... | 35.695652 | 14.608696 |
def pop(self, key, *args, **kwargs):
"""Remove and return the value associated with case-insensitive ``key``."""
return super(CaseInsensitiveDict, self).pop(CaseInsensitiveStr(key)) | [
"def",
"pop",
"(",
"self",
",",
"key",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"CaseInsensitiveDict",
",",
"self",
")",
".",
"pop",
"(",
"CaseInsensitiveStr",
"(",
"key",
")",
")"
] | 65 | 13.333333 |
def scatter_plot(data, index_x, index_y, percent=100.0, seed=1, size=50, title=None, outfile=None, wait=True):
"""
Plots two attributes against each other.
TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html
:param data: the dataset
:type data: Instances
:param i... | [
"def",
"scatter_plot",
"(",
"data",
",",
"index_x",
",",
"index_y",
",",
"percent",
"=",
"100.0",
",",
"seed",
"=",
"1",
",",
"size",
"=",
"50",
",",
"title",
"=",
"None",
",",
"outfile",
"=",
"None",
",",
"wait",
"=",
"True",
")",
":",
"if",
"no... | 32.537313 | 20.089552 |
def query_pager_by_slug(slug, current_page_num=1, tag='', order=False):
'''
Query pager via category slug.
'''
cat_rec = MCategory.get_by_slug(slug)
if cat_rec:
cat_id = cat_rec.uid
else:
return None
# The flowing code is valid.
if... | [
"def",
"query_pager_by_slug",
"(",
"slug",
",",
"current_page_num",
"=",
"1",
",",
"tag",
"=",
"''",
",",
"order",
"=",
"False",
")",
":",
"cat_rec",
"=",
"MCategory",
".",
"get_by_slug",
"(",
"slug",
")",
"if",
"cat_rec",
":",
"cat_id",
"=",
"cat_rec",
... | 32.326531 | 18.612245 |
def get_handlers(self, event: str) -> T.List[T.Callable]:
"""Returns a list of handlers registered for the given event."""
return list(self._events.get(event, [])) | [
"def",
"get_handlers",
"(",
"self",
",",
"event",
":",
"str",
")",
"->",
"T",
".",
"List",
"[",
"T",
".",
"Callable",
"]",
":",
"return",
"list",
"(",
"self",
".",
"_events",
".",
"get",
"(",
"event",
",",
"[",
"]",
")",
")"
] | 44.25 | 16.25 |
def grab_sub_repo(repositories, repos):
"""
Grab SUB_REPOSITORY
"""
for i, repo in enumerate(repositories):
if repos in repo:
sub = repositories[i].replace(repos, "")
repositories[i] = repos
return sub
return "" | [
"def",
"grab_sub_repo",
"(",
"repositories",
",",
"repos",
")",
":",
"for",
"i",
",",
"repo",
"in",
"enumerate",
"(",
"repositories",
")",
":",
"if",
"repos",
"in",
"repo",
":",
"sub",
"=",
"repositories",
"[",
"i",
"]",
".",
"replace",
"(",
"repos",
... | 26.6 | 9.8 |
def check_methods(self, resource):
'''Iteratively check all methods (endpoints) in the Resource.'''
checker = ResourceMethodChecker()
errors = []
for callback in resource.callbacks:
new_errors = checker(callback)
if new_errors:
errors.extend(new_er... | [
"def",
"check_methods",
"(",
"self",
",",
"resource",
")",
":",
"checker",
"=",
"ResourceMethodChecker",
"(",
")",
"errors",
"=",
"[",
"]",
"for",
"callback",
"in",
"resource",
".",
"callbacks",
":",
"new_errors",
"=",
"checker",
"(",
"callback",
")",
"if"... | 37.666667 | 11 |
def topic_present(name, subscriptions=None, attributes=None,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the SNS topic exists.
name
Name of the SNS topic.
subscriptions
List of SNS subscriptions.
Each subscription is a dictionary with a proto... | [
"def",
"topic_present",
"(",
"name",
",",
"subscriptions",
"=",
"None",
",",
"attributes",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
... | 43.067485 | 25.840491 |
def get_filter_qobj(self, keys=None):
"""
Return a copy of this Query object with additional where clauses for the
keys in the argument
"""
# only care about columns in aggregates right?
cols = set()
for agg in self.select.aggregates:
cols.update(agg.cols)
sels = [SelectExpr(col... | [
"def",
"get_filter_qobj",
"(",
"self",
",",
"keys",
"=",
"None",
")",
":",
"# only care about columns in aggregates right?",
"cols",
"=",
"set",
"(",
")",
"for",
"agg",
"in",
"self",
".",
"select",
".",
"aggregates",
":",
"cols",
".",
"update",
"(",
"agg",
... | 31.357143 | 14.571429 |
def _parse_docstring(docstring):
"""
Using the sphinx RSTParse to parse __doc__ for argparse `parameters`, `help`, and `description`. The first
rst paragraph encountered it treated as the argparse help text. Any param fields are treated as argparse
arguments. Any other text is combined and added to the ... | [
"def",
"_parse_docstring",
"(",
"docstring",
")",
":",
"settings",
"=",
"OptionParser",
"(",
"components",
"=",
"(",
"RSTParser",
",",
")",
")",
".",
"get_default_values",
"(",
")",
"rstparser",
"=",
"RSTParser",
"(",
")",
"document",
"=",
"utils",
".",
"n... | 34.979167 | 20.854167 |
def _convert_json(obj):
'''
Converts from the JSON output provided by ovs-vsctl into a usable Python
object tree. In particular, sets and maps are converted from lists to
actual sets or maps.
Args:
obj: Object that shall be recursively converted.
Returns:
Converted version of o... | [
"def",
"_convert_json",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"{",
"_convert_json",
"(",
"key",
")",
":",
"_convert_json",
"(",
"val",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"six",
".",
"iter... | 34.354839 | 21.064516 |
def idle_task(self):
'''called rapidly by mavproxy'''
now = time.time()
if now-self.last_bored > self.boredom_interval:
self.last_bored = now
message = self.boredom_message()
self.say("%s: %s" % (self.name,message))
# See if whatever we're connecte... | [
"def",
"idle_task",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"now",
"-",
"self",
".",
"last_bored",
">",
"self",
".",
"boredom_interval",
":",
"self",
".",
"last_bored",
"=",
"now",
"message",
"=",
"self",
".",
"boredom... | 46.9 | 15.3 |
def app_template_global(self, name: Optional[str]=None) -> Callable:
"""Add an application wide template global.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.template_global`. An example usage,
.. code-block:: python
bluepri... | [
"def",
"app_template_global",
"(",
"self",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Callable",
":",
"def",
"decorator",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"self",
".",
"add_app_template_global",
"(",
... | 34.941176 | 18.823529 |
def _get_concatenation(extractors, text, *, ignore_whitespace=True):
"""Returns a concatenation ParseNode whose children are the nodes returned by each of the
methods in the extractors enumerable.
If ignore_whitespace is True, whitespace will be ignored and then attached to the child it
preceeded.
"""
igno... | [
"def",
"_get_concatenation",
"(",
"extractors",
",",
"text",
",",
"*",
",",
"ignore_whitespace",
"=",
"True",
")",
":",
"ignored_ws",
",",
"use_text",
"=",
"_split_ignored",
"(",
"text",
",",
"ignore_whitespace",
")",
"extractor",
",",
"",
"*",
"remaining",
... | 44.678571 | 28.75 |
def render(self):
'''Render a matplotlib figure from the analyzer result
Return the figure, use fig.show() to display if neeeded
'''
fig, ax = plt.subplots()
self.data_object._render_plot(ax)
return fig | [
"def",
"render",
"(",
"self",
")",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
")",
"self",
".",
"data_object",
".",
"_render_plot",
"(",
"ax",
")",
"return",
"fig"
] | 27.444444 | 23.444444 |
def list_current_orders(self, bet_ids=None, market_ids=None, order_projection=None, customer_order_refs=None,
customer_strategy_refs=None, date_range=time_range(), order_by=None, sort_dir=None,
from_record=None, record_count=None, session=None, lightweight=None):
... | [
"def",
"list_current_orders",
"(",
"self",
",",
"bet_ids",
"=",
"None",
",",
"market_ids",
"=",
"None",
",",
"order_projection",
"=",
"None",
",",
"customer_order_refs",
"=",
"None",
",",
"customer_strategy_refs",
"=",
"None",
",",
"date_range",
"=",
"time_range... | 72.107143 | 41.607143 |
def generate(self):
"""
Fetch all rows associated with this experiment.
This will generate a huge .csv.
"""
exp_name = self.exp_name()
fname = os.path.basename(self.out_path)
fname = "{exp}_{prefix}_{name}{ending}".format(
exp=exp_name,
p... | [
"def",
"generate",
"(",
"self",
")",
":",
"exp_name",
"=",
"self",
".",
"exp_name",
"(",
")",
"fname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"out_path",
")",
"fname",
"=",
"\"{exp}_{prefix}_{name}{ending}\"",
".",
"format",
"(",
"exp... | 31.894737 | 13.789474 |
def write_config(path, config):
"""
Write the config with a little post-converting formatting.
"""
config_as_string = to_nice_yaml(config)
config_as_string = "---\n" + config_as_string
string_to_file(path, config_as_string) | [
"def",
"write_config",
"(",
"path",
",",
"config",
")",
":",
"config_as_string",
"=",
"to_nice_yaml",
"(",
"config",
")",
"config_as_string",
"=",
"\"---\\n\"",
"+",
"config_as_string",
"string_to_file",
"(",
"path",
",",
"config_as_string",
")"
] | 26.777778 | 13.888889 |
def path_to_str(path):
""" Convert pathlib.Path objects to str; return other objects as-is. """
try:
from pathlib import Path as _Path
except ImportError: # Python < 3.4
class _Path:
pass
if isinstance(path, _Path):
return str(path)
return path | [
"def",
"path_to_str",
"(",
"path",
")",
":",
"try",
":",
"from",
"pathlib",
"import",
"Path",
"as",
"_Path",
"except",
"ImportError",
":",
"# Python < 3.4",
"class",
"_Path",
":",
"pass",
"if",
"isinstance",
"(",
"path",
",",
"_Path",
")",
":",
"return",
... | 29.2 | 14.6 |
def get_extract_method(path):
"""Returns `ExtractMethod` to use on resource at path. Cannot be None."""
info_path = _get_info_path(path)
info = _read_info(info_path)
fname = info.get('original_fname', path) if info else path
return _guess_extract_method(fname) | [
"def",
"get_extract_method",
"(",
"path",
")",
":",
"info_path",
"=",
"_get_info_path",
"(",
"path",
")",
"info",
"=",
"_read_info",
"(",
"info_path",
")",
"fname",
"=",
"info",
".",
"get",
"(",
"'original_fname'",
",",
"path",
")",
"if",
"info",
"else",
... | 44.166667 | 8.333333 |
def fetch_task_to_run(self):
"""
Returns the first task that is ready to run or
None if no task can be submitted at present"
Raises:
`StopIteration` if all tasks are done.
"""
# All the tasks are done so raise an exception
# that will be handled by th... | [
"def",
"fetch_task_to_run",
"(",
"self",
")",
":",
"# All the tasks are done so raise an exception",
"# that will be handled by the client code.",
"if",
"all",
"(",
"task",
".",
"is_completed",
"for",
"task",
"in",
"self",
")",
":",
"raise",
"StopIteration",
"(",
"\"All... | 33.857143 | 17.380952 |
def is_running(self) -> bool:
"""Return True if ffmpeg is running."""
if self._proc is None or self._proc.returncode is not None:
return False
return True | [
"def",
"is_running",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_proc",
"is",
"None",
"or",
"self",
".",
"_proc",
".",
"returncode",
"is",
"not",
"None",
":",
"return",
"False",
"return",
"True"
] | 37.2 | 15 |
def same_page_choosen(form, field):
"""Check that we are not trying to assign list page itself as a child."""
if form._obj is not None:
if field.data.id == form._obj.list_id:
raise ValidationError(
_('You cannot assign list page itself as a child.')) | [
"def",
"same_page_choosen",
"(",
"form",
",",
"field",
")",
":",
"if",
"form",
".",
"_obj",
"is",
"not",
"None",
":",
"if",
"field",
".",
"data",
".",
"id",
"==",
"form",
".",
"_obj",
".",
"list_id",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
... | 48.166667 | 9.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.