text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def label_accuracy_score(label_trues, label_preds, n_class):
"""Returns accuracy score evaluation result.
- overall accuracy
- mean accuracy
- mean IU
- fwavacc
"""
hist = np.zeros((n_class, n_class))
for lt, lp in zip(label_trues, label_preds):
hist += _fast_hist(lt.fla... | [
"def",
"label_accuracy_score",
"(",
"label_trues",
",",
"label_preds",
",",
"n_class",
")",
":",
"hist",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_class",
",",
"n_class",
")",
")",
"for",
"lt",
",",
"lp",
"in",
"zip",
"(",
"label_trues",
",",
"label_preds",
... | 36.478261 | 0.001161 |
def get_metadata_from_xml_tree(tree, get_issns_from_nlm=False,
get_abstracts=False, prepend_title=False,
mesh_annotations=False):
"""Get metadata for an XML tree containing PubmedArticle elements.
Documentation on the XML structure can be found at:
... | [
"def",
"get_metadata_from_xml_tree",
"(",
"tree",
",",
"get_issns_from_nlm",
"=",
"False",
",",
"get_abstracts",
"=",
"False",
",",
"prepend_title",
"=",
"False",
",",
"mesh_annotations",
"=",
"False",
")",
":",
"# Iterate over the articles and build the results dict",
... | 40.080645 | 0.000393 |
def get_dashboard_version(self, id, version, **kwargs): # noqa: E501
"""Get a specific version of a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thre... | [
"def",
"get_dashboard_version",
"(",
"self",
",",
"id",
",",
"version",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"sel... | 44.272727 | 0.00201 |
def format_time_large(seconds):
"""
Same as format_time() but always uses the format dd:hh:mm:ss.
"""
if not isinstance(seconds, (int, float)):
return str(seconds)
if math.isnan(seconds):
return "-"
seconds = int(round(seconds))
if abs(seconds)<60:
return "{:d}".fo... | [
"def",
"format_time_large",
"(",
"seconds",
")",
":",
"if",
"not",
"isinstance",
"(",
"seconds",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"str",
"(",
"seconds",
")",
"if",
"math",
".",
"isnan",
"(",
"seconds",
")",
":",
"return",
"\"-\... | 28.482759 | 0.01171 |
def __check_hash(self, message):
"""return true/false if hash is good
message = dict
"""
return message[W_HASH] == self.__make_hash(message[W_MESSAGE], self.__token, message[W_SEQ]) | [
"def",
"__check_hash",
"(",
"self",
",",
"message",
")",
":",
"return",
"message",
"[",
"W_HASH",
"]",
"==",
"self",
".",
"__make_hash",
"(",
"message",
"[",
"W_MESSAGE",
"]",
",",
"self",
".",
"__token",
",",
"message",
"[",
"W_SEQ",
"]",
")"
] | 41.8 | 0.014085 |
def render_pdf_file_to_image_files_pdftoppm_ppm(pdf_file_name, root_output_file_path,
res_x=150, res_y=150, extra_args=None):
"""Use the pdftoppm program to render a PDF file to .png images. The
root_output_file_path is prepended to all the output files, which have nu... | [
"def",
"render_pdf_file_to_image_files_pdftoppm_ppm",
"(",
"pdf_file_name",
",",
"root_output_file_path",
",",
"res_x",
"=",
"150",
",",
"res_y",
"=",
"150",
",",
"extra_args",
"=",
"None",
")",
":",
"if",
"extra_args",
"is",
"None",
":",
"extra_args",
"=",
"[",... | 50.714286 | 0.011982 |
def stack_push(self, value: Union[int, bytes]) -> None:
"""
Push ``value`` onto the stack.
Raise `eth.exceptions.StackDepthLimit` if the stack is full.
"""
return self._stack.push(value) | [
"def",
"stack_push",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"int",
",",
"bytes",
"]",
")",
"->",
"None",
":",
"return",
"self",
".",
"_stack",
".",
"push",
"(",
"value",
")"
] | 31.571429 | 0.008811 |
def _read_in_thread(address, pty, blocking):
"""Read data from the pty in a thread.
"""
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(address)
while 1:
data = pty.read(4096, blocking=blocking)
if not data and not pty.isalive():
while not data... | [
"def",
"_read_in_thread",
"(",
"address",
",",
"pty",
",",
"blocking",
")",
":",
"client",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"client",
".",
"connect",
"(",
"address",
")",
"while",
"1",
... | 26.12 | 0.001477 |
def authorize_handler(self, f):
"""Authorization handler decorator.
This decorator will sort the parameters and headers out, and
pre validate everything::
@app.route('/oauth/authorize', methods=['GET', 'POST'])
@oauth.authorize_handler
def authorize(*args, *... | [
"def",
"authorize_handler",
"(",
"self",
",",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"if",
"not",
"f",
"(",
"*",
... | 39.02439 | 0.00122 |
def from_indigo(idgmol, assign_descriptor=True):
"""Convert RDMol to molecule"""
mol = Compound()
for atom in idgmol.iterateAtoms():
key = atom.index()
a = Atom(atom.symbol())
a.coords = list(atom.xyz())
mol.add_atom(key, a)
for bond in idgmol.iterateBonds():
u = ... | [
"def",
"from_indigo",
"(",
"idgmol",
",",
"assign_descriptor",
"=",
"True",
")",
":",
"mol",
"=",
"Compound",
"(",
")",
"for",
"atom",
"in",
"idgmol",
".",
"iterateAtoms",
"(",
")",
":",
"key",
"=",
"atom",
".",
"index",
"(",
")",
"a",
"=",
"Atom",
... | 31.411765 | 0.001818 |
def __handle_low_seq_resend(self, msg, req):
"""special error case - low sequence number (update sequence number & resend if applicable). Returns True if
a resend was scheduled, False otherwise. MUST be called within self.__requests lock."""
if msg[M_TYPE] == E_FAILED and msg[M_PAYLOAD][P_COD... | [
"def",
"__handle_low_seq_resend",
"(",
"self",
",",
"msg",
",",
"req",
")",
":",
"if",
"msg",
"[",
"M_TYPE",
"]",
"==",
"E_FAILED",
"and",
"msg",
"[",
"M_PAYLOAD",
"]",
"[",
"P_CODE",
"]",
"==",
"E_FAILED_CODE_LOWSEQNUM",
":",
"with",
"self",
".",
"__seq... | 66.5 | 0.008902 |
def flush(self, objects=None, batch_size=None, **kwargs):
''' flush objects stored in self.container or those passed in'''
batch_size = batch_size or self.config.get('batch_size')
# if we're flushing these from self.store, we'll want to
# pop them later.
if objects:
f... | [
"def",
"flush",
"(",
"self",
",",
"objects",
"=",
"None",
",",
"batch_size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"batch_size",
"=",
"batch_size",
"or",
"self",
".",
"config",
".",
"get",
"(",
"'batch_size'",
")",
"# if we're flushing these from... | 42.644444 | 0.001019 |
def color_mod(self):
"""Tuple[int, int, int]: The additional color value used in render copy operations in (red, green, blue)
format.
"""
rgb = ffi.new('Uint8[]', 3)
check_int_err(lib.SDL_GetTextureColorMod(self._ptr, rgb + 0, rgb + 1, rgb + 2))
r... | [
"def",
"color_mod",
"(",
"self",
")",
":",
"rgb",
"=",
"ffi",
".",
"new",
"(",
"'Uint8[]'",
",",
"3",
")",
"check_int_err",
"(",
"lib",
".",
"SDL_GetTextureColorMod",
"(",
"self",
".",
"_ptr",
",",
"rgb",
"+",
"0",
",",
"rgb",
"+",
"1",
",",
"rgb",... | 49.142857 | 0.011429 |
def get_int_or_uuid(value):
"""Check if a value is valid as UUID or an integer.
This method is mainly used to convert floating IP id to the
appropriate type. For floating IP id, integer is used in Nova's
original implementation, but UUID is used in Neutron based one.
"""
try:
uuid.UUID(... | [
"def",
"get_int_or_uuid",
"(",
"value",
")",
":",
"try",
":",
"uuid",
".",
"UUID",
"(",
"value",
")",
"return",
"value",
"except",
"(",
"ValueError",
",",
"AttributeError",
")",
":",
"return",
"int",
"(",
"value",
")"
] | 33.583333 | 0.002415 |
def _encode_message(cls, message):
"""
Encode a single message.
The magic number of a message is a format version number.
The only supported magic number right now is zero
Format
======
Message => Crc MagicByte Attributes Key Value
Crc => int32
... | [
"def",
"_encode_message",
"(",
"cls",
",",
"message",
")",
":",
"if",
"message",
".",
"magic",
"==",
"0",
":",
"msg",
"=",
"b''",
".",
"join",
"(",
"[",
"struct",
".",
"pack",
"(",
"'>BB'",
",",
"message",
".",
"magic",
",",
"message",
".",
"attrib... | 31.296296 | 0.002296 |
def MD_restrained(dirname='MD_POSRES', **kwargs):
"""Set up MD with position restraints.
Additional itp files should be in the same directory as the top file.
Many of the keyword arguments below already have sensible values. Note that
setting *mainselection* = ``None`` will disable many of the automat... | [
"def",
"MD_restrained",
"(",
"dirname",
"=",
"'MD_POSRES'",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"info",
"(",
"\"[{dirname!s}] Setting up MD with position restraints...\"",
".",
"format",
"(",
"*",
"*",
"vars",
"(",
")",
")",
")",
"kwargs",
".",
... | 43.244898 | 0.001384 |
def rate_limit(client, headers, atexit=False):
"""Pause the process based on suggested rate interval."""
if not client or not headers:
return False
if not getattr(client.config, "rate_limit", False):
return False
rate_info = RateLimitsInfo.from_headers(headers)
if not rate_info or ... | [
"def",
"rate_limit",
"(",
"client",
",",
"headers",
",",
"atexit",
"=",
"False",
")",
":",
"if",
"not",
"client",
"or",
"not",
"headers",
":",
"return",
"False",
"if",
"not",
"getattr",
"(",
"client",
".",
"config",
",",
"\"rate_limit\"",
",",
"False",
... | 31.555556 | 0.001709 |
def pex_hash(cls, d):
"""Return a reproducible hash of the contents of a directory."""
names = sorted(f for f in cls._iter_files(d) if not (f.endswith('.pyc') or f.startswith('.')))
def stream_factory(name):
return open(os.path.join(d, name), 'rb') # noqa: T802
return cls._compute_hash(names, str... | [
"def",
"pex_hash",
"(",
"cls",
",",
"d",
")",
":",
"names",
"=",
"sorted",
"(",
"f",
"for",
"f",
"in",
"cls",
".",
"_iter_files",
"(",
"d",
")",
"if",
"not",
"(",
"f",
".",
"endswith",
"(",
"'.pyc'",
")",
"or",
"f",
".",
"startswith",
"(",
"'.'... | 54.5 | 0.012048 |
def DeleteOldClientStats(self, yield_after_count,
retention_time
):
"""Deletes ClientStats older than a given timestamp."""
deleted_count = 0
yielded = False
for stats_dict in itervalues(self.client_stats):
for timestamp in list(stats_dict.keys... | [
"def",
"DeleteOldClientStats",
"(",
"self",
",",
"yield_after_count",
",",
"retention_time",
")",
":",
"deleted_count",
"=",
"0",
"yielded",
"=",
"False",
"for",
"stats_dict",
"in",
"itervalues",
"(",
"self",
".",
"client_stats",
")",
":",
"for",
"timestamp",
... | 30.8 | 0.012598 |
def reference(language, word):
''' Returns the articles (singular and plural) combined with singular and plural for a given noun. '''
sg, pl, art = word, '/'.join(plural(language, word) or ['-']), [[''], ['']]
art[0], art[1] = articles(language, word) or (['-'], ['-'])
result = ['%s %s' % ('/'.join(art[0]), sg), ... | [
"def",
"reference",
"(",
"language",
",",
"word",
")",
":",
"sg",
",",
"pl",
",",
"art",
"=",
"word",
",",
"'/'",
".",
"join",
"(",
"plural",
"(",
"language",
",",
"word",
")",
"or",
"[",
"'-'",
"]",
")",
",",
"[",
"[",
"''",
"]",
",",
"[",
... | 51.875 | 0.021327 |
def asDictionary(self):
""" returns the value as a dictionary """
template = {
"type": "dataLayer",
"dataSource": self._dataSource
}
if not self._fields is None:
template['fields'] = self._fields
return template | [
"def",
"asDictionary",
"(",
"self",
")",
":",
"template",
"=",
"{",
"\"type\"",
":",
"\"dataLayer\"",
",",
"\"dataSource\"",
":",
"self",
".",
"_dataSource",
"}",
"if",
"not",
"self",
".",
"_fields",
"is",
"None",
":",
"template",
"[",
"'fields'",
"]",
"... | 31.111111 | 0.013889 |
def labels_in_range(self, start, end, fully_included=False):
"""
Return a list of labels, that are within the given range.
Also labels that only overlap are included.
Args:
start(float): Start-time in seconds.
end(float): End-time in seconds.
fully_in... | [
"def",
"labels_in_range",
"(",
"self",
",",
"start",
",",
"end",
",",
"fully_included",
"=",
"False",
")",
":",
"if",
"fully_included",
":",
"intervals",
"=",
"self",
".",
"label_tree",
".",
"envelop",
"(",
"start",
",",
"end",
")",
"else",
":",
"interva... | 35.515152 | 0.001661 |
def discover_by_directory(self, start_directory, top_level_directory=None,
pattern='test*.py'):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
top... | [
"def",
"discover_by_directory",
"(",
"self",
",",
"start_directory",
",",
"top_level_directory",
"=",
"None",
",",
"pattern",
"=",
"'test*.py'",
")",
":",
"start_directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"start_directory",
")",
"if",
"top_level_di... | 41.21875 | 0.002222 |
def fromcsv(source=None, encoding=None, errors='strict', header=None,
**csvargs):
"""
Extract a table from a delimited file. E.g.::
>>> import petl as etl
>>> import csv
>>> # set up a CSV file to demonstrate with
... table1 = [['foo', 'bar'],
... ... | [
"def",
"fromcsv",
"(",
"source",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"header",
"=",
"None",
",",
"*",
"*",
"csvargs",
")",
":",
"source",
"=",
"read_source_from_arg",
"(",
"source",
")",
"csvargs",
".",
"setd... | 33.255814 | 0.002038 |
def ng_dissim(a, b, X=None, membship=None):
"""Ng et al.'s dissimilarity measure, as presented in
Michael K. Ng, Mark Junjie Li, Joshua Zhexue Huang, and Zengyou He, "On the
Impact of Dissimilarity Measure in k-Modes Clustering Algorithm", IEEE
Transactions on Pattern Analysis and Machine Intelligence, ... | [
"def",
"ng_dissim",
"(",
"a",
",",
"b",
",",
"X",
"=",
"None",
",",
"membship",
"=",
"None",
")",
":",
"# Without membership, revert to matching dissimilarity",
"if",
"membship",
"is",
"None",
":",
"return",
"matching_dissim",
"(",
"a",
",",
"b",
")",
"def",... | 45.692308 | 0.001099 |
def text(value: str, preformatted: bool = False):
"""
Adds text to the display. If the text is not preformatted, it will be
displayed in paragraph format. Preformatted text will be displayed
inside a pre tag with a monospace font.
:param value:
The text to display.
:param preformatted:
... | [
"def",
"text",
"(",
"value",
":",
"str",
",",
"preformatted",
":",
"bool",
"=",
"False",
")",
":",
"if",
"preformatted",
":",
"result",
"=",
"render_texts",
".",
"preformatted_text",
"(",
"value",
")",
"else",
":",
"result",
"=",
"render_texts",
".",
"te... | 32.3 | 0.001504 |
def python_2_format_compatible(method):
"""
Handles bytestring and unicode inputs for the `__format__()` method in
Python 2. This function has no effect in Python 3.
:param method: The `__format__()` method to wrap.
:return: The wrapped method.
"""
if six.PY3:
return method
def... | [
"def",
"python_2_format_compatible",
"(",
"method",
")",
":",
"if",
"six",
".",
"PY3",
":",
"return",
"method",
"def",
"wrapper",
"(",
"self",
",",
"format_spec",
")",
":",
"formatted",
"=",
"method",
"(",
"self",
",",
"format_spec",
")",
"if",
"isinstance... | 27.45 | 0.001761 |
def layout(self, slide):
""" Return layout information for slide """
image = Image.new('RGB', (WIDTH, HEIGHT), 'black')
draw = ImageDraw.Draw(image)
draw.font = self.font
self.vertical_layout(draw, slide)
self.horizontal_layout(draw, slide)
ret... | [
"def",
"layout",
"(",
"self",
",",
"slide",
")",
":",
"image",
"=",
"Image",
".",
"new",
"(",
"'RGB'",
",",
"(",
"WIDTH",
",",
"HEIGHT",
")",
",",
"'black'",
")",
"draw",
"=",
"ImageDraw",
".",
"Draw",
"(",
"image",
")",
"draw",
".",
"font",
"=",... | 26.5 | 0.012158 |
def _pluralize(value, item_key):
""""Force the value of a datacite3 key to be a list.
>>> _pluralize(xml_input['authors'], 'author')
['Sick, Jonathan', 'Economou, Frossie']
Background
----------
When `xmltodict` proceses metadata, it turns XML tags into new key-value
pairs whenever possibl... | [
"def",
"_pluralize",
"(",
"value",
",",
"item_key",
")",
":",
"v",
"=",
"value",
"[",
"item_key",
"]",
"if",
"not",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"# Force a singular value to be a list",
"return",
"[",
"v",
"]",
"else",
":",
"return",
"v... | 24.116667 | 0.000664 |
def delete(self):
"""Delete the workspace from FireCloud.
Note:
This action cannot be undone. Be careful!
"""
r = fapi.delete_workspace(self.namespace, self.name)
fapi._check_response_code(r, 202) | [
"def",
"delete",
"(",
"self",
")",
":",
"r",
"=",
"fapi",
".",
"delete_workspace",
"(",
"self",
".",
"namespace",
",",
"self",
".",
"name",
")",
"fapi",
".",
"_check_response_code",
"(",
"r",
",",
"202",
")"
] | 30.25 | 0.008032 |
def expValue(self, pred):
""" Helper function to return a scalar value representing the expected
value of a probability distribution
"""
if len(pred) == 1:
return pred.keys()[0]
return sum([x*p for x,p in pred.items()]) | [
"def",
"expValue",
"(",
"self",
",",
"pred",
")",
":",
"if",
"len",
"(",
"pred",
")",
"==",
"1",
":",
"return",
"pred",
".",
"keys",
"(",
")",
"[",
"0",
"]",
"return",
"sum",
"(",
"[",
"x",
"*",
"p",
"for",
"x",
",",
"p",
"in",
"pred",
".",... | 30.375 | 0.012 |
def parallel_timebin_lcdir(lcdir,
binsizesec,
maxobjects=None,
outdir=None,
lcformat='hat-sql',
lcformatdir=None,
timecols=None,
ma... | [
"def",
"parallel_timebin_lcdir",
"(",
"lcdir",
",",
"binsizesec",
",",
"maxobjects",
"=",
"None",
",",
"outdir",
"=",
"None",
",",
"lcformat",
"=",
"'hat-sql'",
",",
"lcformatdir",
"=",
"None",
",",
"timecols",
"=",
"None",
",",
"magcols",
"=",
"None",
","... | 36.684211 | 0.001397 |
def huji(magfile="", dir_path=".", input_dir_path="", datafile="", codelist="",
meas_file="measurements.txt", spec_file="specimens.txt",
samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
user="", specnum=0, samp_con="1", labfield=0, phi=0, theta=0,
location=""... | [
"def",
"huji",
"(",
"magfile",
"=",
"\"\"",
",",
"dir_path",
"=",
"\".\"",
",",
"input_dir_path",
"=",
"\"\"",
",",
"datafile",
"=",
"\"\"",
",",
"codelist",
"=",
"\"\"",
",",
"meas_file",
"=",
"\"measurements.txt\"",
",",
"spec_file",
"=",
"\"specimens.txt\... | 44.742857 | 0.001653 |
def send_button(recipient):
"""
Shortcuts are supported
page.send(recipient, Template.Buttons("hello", [
{'type': 'web_url', 'title': 'Open Web URL', 'value': 'https://www.oculus.com/en-us/rift/'},
{'type': 'postback', 'title': 'tigger Postback', 'value': 'DEVELOPED_DEFINED_PAYLOAD'},
... | [
"def",
"send_button",
"(",
"recipient",
")",
":",
"page",
".",
"send",
"(",
"recipient",
",",
"Template",
".",
"Buttons",
"(",
"\"hello\"",
",",
"[",
"Template",
".",
"ButtonWeb",
"(",
"\"Open Web URL\"",
",",
"\"https://www.oculus.com/en-us/rift/\"",
")",
",",
... | 50.142857 | 0.008392 |
def show(self, figure=None, invisible_axis=True, visible_grid=True, display=True, shift=None):
"""!
@brief Shows clusters (visualize).
@param[in] figure (fig): Defines requirement to use specified figure, if None - new figure is created for drawing clusters.
@param[in] invi... | [
"def",
"show",
"(",
"self",
",",
"figure",
"=",
"None",
",",
"invisible_axis",
"=",
"True",
",",
"visible_grid",
"=",
"True",
",",
"display",
"=",
"True",
",",
"shift",
"=",
"None",
")",
":",
"canvas_shift",
"=",
"shift",
"if",
"canvas_shift",
"is",
"N... | 42.285714 | 0.009904 |
def update_camera(self,**kargs):
"""
- update_camera(**kwarg): By using this method you can define all
the new paramenters of the camera. Read the available **kwarg in
the sphviewer.Camera documentation.
"""
self.Camera.set_params(**kargs)
self._x, self._y, sel... | [
"def",
"update_camera",
"(",
"self",
",",
"*",
"*",
"kargs",
")",
":",
"self",
".",
"Camera",
".",
"set_params",
"(",
"*",
"*",
"kargs",
")",
"self",
".",
"_x",
",",
"self",
".",
"_y",
",",
"self",
".",
"_hsml",
",",
"self",
".",
"_kview",
"=",
... | 45.555556 | 0.014354 |
def teetext(table, source=None, encoding=None, errors='strict', template=None,
prologue=None, epilogue=None):
"""
Return a table that writes rows to a text file as they are iterated over.
"""
assert template is not None, 'template is required'
return TeeTextView(table, source=source, e... | [
"def",
"teetext",
"(",
"table",
",",
"source",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"template",
"=",
"None",
",",
"prologue",
"=",
"None",
",",
"epilogue",
"=",
"None",
")",
":",
"assert",
"template",
"is",
... | 42.3 | 0.002315 |
def clear_selection(self):
"""Clear current selection"""
cursor = self.textCursor()
cursor.clearSelection()
self.setTextCursor(cursor) | [
"def",
"clear_selection",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"clearSelection",
"(",
")",
"self",
".",
"setTextCursor",
"(",
"cursor",
")"
] | 33.2 | 0.011765 |
def basic_distance(trig_pin, echo_pin, celsius=20):
'''Return an unformatted distance in cm's as read directly from
RPi.GPIO.'''
speed_of_sound = 331.3 * math.sqrt(1+(celsius / 273.15))
GPIO.setup(trig_pin, GPIO.OUT)
GPIO.setup(echo_pin, GPIO.IN)
GPIO.output(trig_pin, GPIO.LOW)
time.sleep(0... | [
"def",
"basic_distance",
"(",
"trig_pin",
",",
"echo_pin",
",",
"celsius",
"=",
"20",
")",
":",
"speed_of_sound",
"=",
"331.3",
"*",
"math",
".",
"sqrt",
"(",
"1",
"+",
"(",
"celsius",
"/",
"273.15",
")",
")",
"GPIO",
".",
"setup",
"(",
"trig_pin",
"... | 34.625 | 0.001171 |
def _translate_struct(inner_dict):
"""Translate a teleport Struct into a val subschema."""
try:
optional = inner_dict['optional'].items()
required = inner_dict['required'].items()
except KeyError as ex:
raise DeserializationError("Missing key: {}".format(ex))
except AttributeErro... | [
"def",
"_translate_struct",
"(",
"inner_dict",
")",
":",
"try",
":",
"optional",
"=",
"inner_dict",
"[",
"'optional'",
"]",
".",
"items",
"(",
")",
"required",
"=",
"inner_dict",
"[",
"'required'",
"]",
".",
"items",
"(",
")",
"except",
"KeyError",
"as",
... | 39.571429 | 0.001764 |
def fedit(data, title="", comment="", icon=None, parent=None, apply=None,
ok=True, cancel=True, result='list', outfile=None, type='form',
scrollbar=False, background_color=None, widget_color=None):
"""
Create form dialog and return result
(if Cancel button is pressed, return None)
:... | [
"def",
"fedit",
"(",
"data",
",",
"title",
"=",
"\"\"",
",",
"comment",
"=",
"\"\"",
",",
"icon",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"apply",
"=",
"None",
",",
"ok",
"=",
"True",
",",
"cancel",
"=",
"True",
",",
"result",
"=",
"'list'"... | 43.675325 | 0.002035 |
def main():
"""Command-Mode: Retrieve and display data then process commands."""
(cred, providers) = config_read()
cmd_mode = True
conn_objs = cld.get_conns(cred, providers)
while cmd_mode:
nodes = cld.get_data(conn_objs, providers)
node_dict = make_node_dict(nodes, "name")
i... | [
"def",
"main",
"(",
")",
":",
"(",
"cred",
",",
"providers",
")",
"=",
"config_read",
"(",
")",
"cmd_mode",
"=",
"True",
"conn_objs",
"=",
"cld",
".",
"get_conns",
"(",
"cred",
",",
"providers",
")",
"while",
"cmd_mode",
":",
"nodes",
"=",
"cld",
"."... | 38.636364 | 0.002299 |
def lsfolders(self, stream=sys.stdout):
"""List the subfolders"""
for f in self.folder.folders():
print(f.folder.strip("."), file=stream) | [
"def",
"lsfolders",
"(",
"self",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"f",
"in",
"self",
".",
"folder",
".",
"folders",
"(",
")",
":",
"print",
"(",
"f",
".",
"folder",
".",
"strip",
"(",
"\".\"",
")",
",",
"file",
"=",
"s... | 40.5 | 0.012121 |
def ckobj(ck, outCell=None):
"""
Find the set of ID codes of all objects in a specified CK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckobj_c.html
:param ck: Name of CK file.
:type ck: str
:param outCell: Optional user provided Spice Int cell.
:type outCell: Optional spi... | [
"def",
"ckobj",
"(",
"ck",
",",
"outCell",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"ck",
",",
"str",
")",
"ck",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ck",
")",
"if",
"not",
"outCell",
":",
"outCell",
"=",
"stypes",
".",
"SPICEINT_CEL... | 34.380952 | 0.001348 |
def __data_url(self):
"""
URL for posting metrics to the host agent. Only valid when announced.
"""
path = AGENT_DATA_PATH % self.from_.pid
return "http://%s:%s/%s" % (self.host, self.port, path) | [
"def",
"__data_url",
"(",
"self",
")",
":",
"path",
"=",
"AGENT_DATA_PATH",
"%",
"self",
".",
"from_",
".",
"pid",
"return",
"\"http://%s:%s/%s\"",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"path",
")"
] | 38.5 | 0.008475 |
def run(app_class: Type[Application],
extra_module_paths: List[str] = None, **kwargs: Any) -> None:
"""
Runner for haps application.
:param app_class: :class:`~haps.application.Application` type
:param extra_module_paths: Extra modules list to autodiscover
:param kwa... | [
"def",
"run",
"(",
"app_class",
":",
"Type",
"[",
"Application",
"]",
",",
"extra_module_paths",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"module",
"=",
"app_class",
".",
"__module__",
"i... | 33.5 | 0.002417 |
def _maybeCreateTable(self, tableClass, key):
"""
A type ID has been requested for an Item subclass whose table was not
present when this Store was opened. Attempt to create the table, and
if that fails because another Store object (perhaps in another process)
has created the ta... | [
"def",
"_maybeCreateTable",
"(",
"self",
",",
"tableClass",
",",
"key",
")",
":",
"try",
":",
"self",
".",
"_justCreateTable",
"(",
"tableClass",
")",
"except",
"errors",
".",
"TableAlreadyExists",
":",
"# Although we don't have a memory of this table from the last time... | 46.809524 | 0.000996 |
def t_ID(self, t):
r"""[a-zA-Z_][a-zA-Z_0-9]*"""
# If the value is a reserved name, give it the appropriate type (not ID)
if t.value in self.reserved:
t.type = self.reserved[t.value]
# If it's a function, give it the FUNC type
elif t.value in self.functions:
... | [
"def",
"t_ID",
"(",
"self",
",",
"t",
")",
":",
"# If the value is a reserved name, give it the appropriate type (not ID)",
"if",
"t",
".",
"value",
"in",
"self",
".",
"reserved",
":",
"t",
".",
"type",
"=",
"self",
".",
"reserved",
"[",
"t",
".",
"value",
"... | 28.916667 | 0.00838 |
def add_quantity(self,
quantities,
value,
source,
check_for_dupes=True,
compare_to_existing=True,
**kwargs):
"""Add an `Quantity` instance to this entry."""
success = True
... | [
"def",
"add_quantity",
"(",
"self",
",",
"quantities",
",",
"value",
",",
"source",
",",
"check_for_dupes",
"=",
"True",
",",
"compare_to_existing",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"success",
"=",
"True",
"for",
"quantity",
"in",
"listify",... | 37.045455 | 0.009569 |
def _ensure_tree(path):
"""Create a directory (and any ancestor directories required).
:param path: Directory to create
"""
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST:
if not os.path.isdir(path):
raise
else:
... | [
"def",
"_ensure_tree",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",... | 23.578947 | 0.002146 |
def get_report(self):
'''
need to wrap get_report, since we need to parse the report
'''
report_dict = self._meta_get_report()
report = Report.from_dict(report_dict)
return report | [
"def",
"get_report",
"(",
"self",
")",
":",
"report_dict",
"=",
"self",
".",
"_meta_get_report",
"(",
")",
"report",
"=",
"Report",
".",
"from_dict",
"(",
"report_dict",
")",
"return",
"report"
] | 31.571429 | 0.008811 |
def cublasZher(handle, uplo, n, alpha, x, incx, A, lda):
"""
Rank-1 operation on Hermitian matrix.
"""
status = _libcublas.cublasZher_v2(handle,
_CUBLAS_FILL_MODE[uplo],
n, alpha, int(x), incx, int(A), lda)
cublasChe... | [
"def",
"cublasZher",
"(",
"handle",
",",
"uplo",
",",
"n",
",",
"alpha",
",",
"x",
",",
"incx",
",",
"A",
",",
"lda",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasZher_v2",
"(",
"handle",
",",
"_CUBLAS_FILL_MODE",
"[",
"uplo",
"]",
",",
"n",
... | 32.7 | 0.011905 |
def unsubscribe_rpc(self, service, mask, value):
'''Remove a rpc subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value in the su... | [
"def",
"unsubscribe_rpc",
"(",
"self",
",",
"service",
",",
"mask",
",",
"value",
")",
":",
"log",
".",
"info",
"(",
"\"unsubscribing from RPC %r\"",
"%",
"(",
"(",
"service",
",",
"(",
"mask",
",",
"value",
")",
")",
",",
")",
")",
"return",
"self",
... | 42.157895 | 0.002442 |
def count_types(self) -> int:
""" Count subtypes """
n = 0
for s in self._hsig.values():
if type(s).__name__ == 'Type':
n += 1
return n | [
"def",
"count_types",
"(",
"self",
")",
"->",
"int",
":",
"n",
"=",
"0",
"for",
"s",
"in",
"self",
".",
"_hsig",
".",
"values",
"(",
")",
":",
"if",
"type",
"(",
"s",
")",
".",
"__name__",
"==",
"'Type'",
":",
"n",
"+=",
"1",
"return",
"n"
] | 27 | 0.010256 |
def upload(self, array, fields=None, table="MyDB", configfile=None):
"""
Upload an array to a personal database using SOAP POST protocol.
http://skyserver.sdss3.org/casjobs/services/jobs.asmx?op=UploadData
"""
wsid=''
password=''
if configfile is None:
... | [
"def",
"upload",
"(",
"self",
",",
"array",
",",
"fields",
"=",
"None",
",",
"table",
"=",
"\"MyDB\"",
",",
"configfile",
"=",
"None",
")",
":",
"wsid",
"=",
"''",
"password",
"=",
"''",
"if",
"configfile",
"is",
"None",
":",
"configfile",
"=",
"\"Ca... | 37.741935 | 0.009163 |
def call(self, name, *args, **kwargs):
"""Call a vimscript function."""
return self.request('nvim_call_function', name, args, **kwargs) | [
"def",
"call",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"request",
"(",
"'nvim_call_function'",
",",
"name",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 49.666667 | 0.013245 |
def rap(self,analytic=False,pot=None,**kwargs):
"""
NAME:
rap
PURPOSE:
return the apocenter radius
INPUT:
analytic - compute this analytically
pot - potential to use for analytical calculation
OUTPUT:
R_ap
HISTORY:
... | [
"def",
"rap",
"(",
"self",
",",
"analytic",
"=",
"False",
",",
"pot",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"analytic",
":",
"self",
".",
"_setupaA",
"(",
"pot",
"=",
"pot",
",",
"type",
"=",
"'adiabatic'",
")",
"(",
"rperi",
",",... | 30.652174 | 0.016506 |
def _ParseCshVariables(self, lines):
"""Extract env_var and path values from csh derivative shells.
Path attributes can be set several ways:
- setenv takes the form "setenv PATH_NAME COLON:SEPARATED:LIST"
- set takes the form "set path_name=(space separated list)" and is
automatically exported fo... | [
"def",
"_ParseCshVariables",
"(",
"self",
",",
"lines",
")",
":",
"paths",
"=",
"{",
"}",
"for",
"line",
"in",
"lines",
":",
"if",
"len",
"(",
"line",
")",
"<",
"2",
":",
"continue",
"action",
"=",
"line",
"[",
"0",
"]",
"if",
"action",
"==",
"\"... | 34.315789 | 0.008203 |
def _sdk_tools(self):
"""
Microsoft Windows SDK Tools paths generator
"""
if self.vc_ver < 15.0:
bin_dir = 'Bin' if self.vc_ver <= 11.0 else r'Bin\x86'
yield os.path.join(self.si.WindowsSdkDir, bin_dir)
if not self.pi.current_is_x86():
arch_su... | [
"def",
"_sdk_tools",
"(",
"self",
")",
":",
"if",
"self",
".",
"vc_ver",
"<",
"15.0",
":",
"bin_dir",
"=",
"'Bin'",
"if",
"self",
".",
"vc_ver",
"<=",
"11.0",
"else",
"r'Bin\\x86'",
"yield",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"si",
"... | 39.241379 | 0.001715 |
def set_subdata(self, data, offset=0, copy=False):
""" Set a sub-region of the buffer (deferred operation).
Parameters
----------
data : ndarray
Data to be uploaded
offset: int
Offset in buffer where to start copying data (in bytes)
copy: bool
... | [
"def",
"set_subdata",
"(",
"self",
",",
"data",
",",
"offset",
"=",
"0",
",",
"copy",
"=",
"False",
")",
":",
"data",
"=",
"np",
".",
"array",
"(",
"data",
",",
"copy",
"=",
"copy",
")",
"nbytes",
"=",
"data",
".",
"nbytes",
"if",
"offset",
"<",
... | 37.321429 | 0.001866 |
def validation_tween_factory(handler, registry):
"""Pyramid tween for performing validation.
Note this is very simple -- it validates requests, responses, and paths
while delegating to the relevant matching view.
"""
settings = load_settings(registry)
route_mapper = registry.queryUtility(IRoute... | [
"def",
"validation_tween_factory",
"(",
"handler",
",",
"registry",
")",
":",
"settings",
"=",
"load_settings",
"(",
"registry",
")",
"route_mapper",
"=",
"registry",
".",
"queryUtility",
"(",
"IRoutesMapper",
")",
"validation_context",
"=",
"_get_validation_context",... | 35.551724 | 0.000944 |
def move_mouse(self, x, y, screen=0):
"""
Move the mouse to a specific location.
:param x: the target X coordinate on the screen in pixels.
:param y: the target Y coordinate on the screen in pixels.
:param screen: the screen (number) you want to move on.
"""
# to... | [
"def",
"move_mouse",
"(",
"self",
",",
"x",
",",
"y",
",",
"screen",
"=",
"0",
")",
":",
"# todo: apparently the \"screen\" argument is not behaving properly",
"# and sometimes even making the interpreter crash..",
"# Figure out why (changed API / using wrong header?)",
... | 36.785714 | 0.001892 |
def to_string(self):
"""
Render a DataFrame to a console-friendly tabular output.
"""
from pandas import Series
frame = self.frame
if len(frame.columns) == 0 or len(frame.index) == 0:
info_line = ('Empty {name}\nColumns: {col}\nIndex: {idx}'
... | [
"def",
"to_string",
"(",
"self",
")",
":",
"from",
"pandas",
"import",
"Series",
"frame",
"=",
"self",
".",
"frame",
"if",
"len",
"(",
"frame",
".",
"columns",
")",
"==",
"0",
"or",
"len",
"(",
"frame",
".",
"index",
")",
"==",
"0",
":",
"info_line... | 43.440678 | 0.000763 |
def p_func_args(self, p):
'func_args : func_args COMMA expression'
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_func_args",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"(",
"p",
"[",
"3",
"]",
",",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 34.5 | 0.014184 |
def _get_cached_mounted_points():
"""! Get the volumes present on the system
@return List of mount points and their associated target id
Ex. [{ 'mount_point': 'D:', 'target_id_usb_id': 'xxxx'}, ...]
"""
result = []
try:
# Open the registry key for mounted devices
mounted_device... | [
"def",
"_get_cached_mounted_points",
"(",
")",
":",
"result",
"=",
"[",
"]",
"try",
":",
"# Open the registry key for mounted devices",
"mounted_devices_key",
"=",
"winreg",
".",
"OpenKey",
"(",
"winreg",
".",
"HKEY_LOCAL_MACHINE",
",",
"\"SYSTEM\\\\MountedDevices\"",
"... | 35.424242 | 0.002498 |
def random_get_int_mean(
rnd: Optional[tcod.random.Random], mi: int, ma: int, mean: int
) -> int:
"""Return a random weighted integer in the range: ``mi`` <= n <= ``ma``.
The result is affacted by calls to :any:`random_set_distribution`.
Args:
rnd (Optional[Random]): A Random instance, or None... | [
"def",
"random_get_int_mean",
"(",
"rnd",
":",
"Optional",
"[",
"tcod",
".",
"random",
".",
"Random",
"]",
",",
"mi",
":",
"int",
",",
"ma",
":",
"int",
",",
"mean",
":",
"int",
")",
"->",
"int",
":",
"return",
"int",
"(",
"lib",
".",
"TCOD_random_... | 34.52381 | 0.001342 |
def get_diameter(self):
'''
API:
get_diameter(self)
Description:
Returns diameter of the graph. Diameter is defined as follows.
distance(n,m): shortest unweighted path from n to m
eccentricity(n) = $\max _m distance(n,m)$
diameter = $\m... | [
"def",
"get_diameter",
"(",
"self",
")",
":",
"if",
"self",
".",
"attr",
"[",
"'type'",
"]",
"is",
"not",
"UNDIRECTED_GRAPH",
":",
"print",
"(",
"'This function only works for undirected graphs'",
")",
"return",
"diameter",
"=",
"'infinity'",
"eccentricity_n",
"="... | 40.96875 | 0.008197 |
def set_mem_per_proc(self, mem_mb):
"""Set the memory per process in megabytes"""
super().set_mem_per_proc(mem_mb)
self.qparams["mem_per_cpu"] = self.mem_per_proc | [
"def",
"set_mem_per_proc",
"(",
"self",
",",
"mem_mb",
")",
":",
"super",
"(",
")",
".",
"set_mem_per_proc",
"(",
"mem_mb",
")",
"self",
".",
"qparams",
"[",
"\"mem_per_cpu\"",
"]",
"=",
"self",
".",
"mem_per_proc"
] | 45.75 | 0.010753 |
def to_fixed(stype):
""" Returns the instruction sequence for converting the given
type stored in DE,HL to fixed DE,HL.
"""
output = [] # List of instructions
if is_int_type(stype):
output = to_word(stype)
output.append('ex de, hl')
output.append('ld hl, 0') # 'Truncate' t... | [
"def",
"to_fixed",
"(",
"stype",
")",
":",
"output",
"=",
"[",
"]",
"# List of instructions",
"if",
"is_int_type",
"(",
"stype",
")",
":",
"output",
"=",
"to_word",
"(",
"stype",
")",
"output",
".",
"append",
"(",
"'ex de, hl'",
")",
"output",
".",
"appe... | 29.466667 | 0.002193 |
def arpleak(target, plen=255, hwlen=255, **kargs):
"""Exploit ARP leak flaws, like NetBSD-SA2017-002.
https://ftp.netbsd.org/pub/NetBSD/security/advisories/NetBSD-SA2017-002.txt.asc
"""
# We want explicit packets
pkts_iface = {}
for pkt in ARP(pdst=target):
# We have to do some of Scapy's ... | [
"def",
"arpleak",
"(",
"target",
",",
"plen",
"=",
"255",
",",
"hwlen",
"=",
"255",
",",
"*",
"*",
"kargs",
")",
":",
"# We want explicit packets",
"pkts_iface",
"=",
"{",
"}",
"for",
"pkt",
"in",
"ARP",
"(",
"pdst",
"=",
"target",
")",
":",
"# We ha... | 32.9 | 0.00059 |
def edges(self, nodes=None):
"""
Returns a ``tuple`` of all edges in the ``DictGraph`` an edge is a pair
of **node objects**.
Arguments:
- nodes(iterable) [default: ``None``] iterable of **node objects** if
specified the edges will be limited to t... | [
"def",
"edges",
"(",
"self",
",",
"nodes",
"=",
"None",
")",
":",
"# If a Node has been directly updated (__not__ recommended)",
"# then the Graph will not know the added nodes and therefore will",
"# miss half of their edges.",
"edges",
"=",
"set",
"(",
")",
"for",
"node",
"... | 37.75 | 0.009044 |
def plan(self):
""" Gets the associated plan for this invoice.
In order to provide a consistent view of invoices, the plan object
should be taken from the first invoice item that has one, rather than
using the plan associated with the subscription.
Subscriptions (and their associated plan) are updated by th... | [
"def",
"plan",
"(",
"self",
")",
":",
"for",
"invoiceitem",
"in",
"self",
".",
"invoiceitems",
".",
"all",
"(",
")",
":",
"if",
"invoiceitem",
".",
"plan",
":",
"return",
"invoiceitem",
".",
"plan",
"if",
"self",
".",
"subscription",
":",
"return",
"se... | 34.68 | 0.022447 |
def unpack(regex):
"""
Remove the outermost parens, keep the (?P...) one
>>> unpack(r'(abc)')
'abc'
>>> unpack(r'(?:abc)')
'abc'
>>> unpack(r'(?P<xyz>abc)')
'(?P<xyz>abc)'
>>> unpack(r'[abc]')
'[abc]'
"""
if is_packed(regex) and not regex.startswith('(?P<'):
retu... | [
"def",
"unpack",
"(",
"regex",
")",
":",
"if",
"is_packed",
"(",
"regex",
")",
"and",
"not",
"regex",
".",
"startswith",
"(",
"'(?P<'",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'^\\((\\?:)?(?P<content>.*?)\\)$'",
",",
"r'\\g<content>'",
",",
"regex",
"... | 23.529412 | 0.002404 |
def delete_collection_audit_sink(self, **kwargs): # noqa: E501
"""delete_collection_audit_sink # noqa: E501
delete collection of AuditSink # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>... | [
"def",
"delete_collection_audit_sink",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"delete_collect... | 163.034483 | 0.000421 |
def combinations(iterable, r):
"""Calculate combinations
>>> list(combinations('ABCD',2))
[['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']]
>>> list(combinations(range(4), 3))
[[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]
Args:
iterable: Any iterable object.
... | [
"def",
"combinations",
"(",
"iterable",
",",
"r",
")",
":",
"pool",
"=",
"tuple",
"(",
"iterable",
")",
"n",
"=",
"len",
"(",
"pool",
")",
"if",
"r",
">",
"n",
":",
"return",
"indices",
"=",
"list",
"(",
"range",
"(",
"r",
")",
")",
"yield",
"l... | 23.228571 | 0.001181 |
def collect(self):
"""
Collects resources usage of each process defined under the
`process` subsection of the config file
"""
if not psutil:
self.log.error('Unable to import psutil')
self.log.error('No process resource metrics retrieved')
retur... | [
"def",
"collect",
"(",
"self",
")",
":",
"if",
"not",
"psutil",
":",
"self",
".",
"log",
".",
"error",
"(",
"'Unable to import psutil'",
")",
"self",
".",
"log",
".",
"error",
"(",
"'No process resource metrics retrieved'",
")",
"return",
"None",
"for",
"pro... | 35.714286 | 0.001947 |
async def delete_reply_markup(self):
"""
Use this method to delete reply markup of messages sent by the bot or via the bot (for inline bots).
:return: On success, if edited message is sent by the bot, the edited Message is returned,
otherwise True is returned.
:rtype: :obj:`... | [
"async",
"def",
"delete_reply_markup",
"(",
"self",
")",
":",
"return",
"await",
"self",
".",
"bot",
".",
"edit_message_reply_markup",
"(",
"chat_id",
"=",
"self",
".",
"chat",
".",
"id",
",",
"message_id",
"=",
"self",
".",
"message_id",
")"
] | 52.444444 | 0.010417 |
def process_pgturl(self, params):
"""
Handle PGT request
:param dict params: A template context dict
:raises ValidateError: if pgtUrl is invalid or if TLS validation of the pgtUrl fails
:return: The rendering of ``cas_server/serviceValidate.xml``, using ``params`... | [
"def",
"process_pgturl",
"(",
"self",
",",
"params",
")",
":",
"try",
":",
"pattern",
"=",
"ServicePattern",
".",
"validate",
"(",
"self",
".",
"pgt_url",
")",
"if",
"pattern",
".",
"proxy_callback",
":",
"proxyid",
"=",
"utils",
".",
"gen_pgtiou",
"(",
... | 43.453125 | 0.002461 |
def events(self):
"""
All events.
:type: List[:class:`.CommandHistoryEvent`]
"""
events = [self.acknowledge_event] + self.verification_events
return [x for x in events if x] | [
"def",
"events",
"(",
"self",
")",
":",
"events",
"=",
"[",
"self",
".",
"acknowledge_event",
"]",
"+",
"self",
".",
"verification_events",
"return",
"[",
"x",
"for",
"x",
"in",
"events",
"if",
"x",
"]"
] | 26.875 | 0.009009 |
def _handle_result(self, test, status, exception=None, message=None):
"""Create a :class:`~.TestResult` and add it to this
:class:`~ResultCollector`.
Parameters
----------
test : unittest.TestCase
The test that this result will represent.
status : haas.result... | [
"def",
"_handle_result",
"(",
"self",
",",
"test",
",",
"status",
",",
"exception",
"=",
"None",
",",
"message",
"=",
"None",
")",
":",
"if",
"self",
".",
"buffer",
":",
"stderr",
"=",
"self",
".",
"_stderr_buffer",
".",
"getvalue",
"(",
")",
"stdout",... | 33.568182 | 0.001316 |
def fetch(method, uri, params_prefix=None, **params):
"""Fetch the given uri and return the contents of the response."""
params = _prepare_params(params, params_prefix)
if method == "POST" or method == "PUT":
r_data = {"data": params}
else:
r_data = {"params": params}
# build the H... | [
"def",
"fetch",
"(",
"method",
",",
"uri",
",",
"params_prefix",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"params",
"=",
"_prepare_params",
"(",
"params",
",",
"params_prefix",
")",
"if",
"method",
"==",
"\"POST\"",
"or",
"method",
"==",
"\"PUT\""... | 29.964286 | 0.001155 |
def _machinectl(cmd,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False):
'''
Helper function to run machinectl
'''
prefix = 'machinectl --no-legend --no-pager'
return __salt__['cmd.run_all']('{0} {1}'.format(prefix, cmd),
... | [
"def",
"_machinectl",
"(",
"cmd",
",",
"output_loglevel",
"=",
"'debug'",
",",
"ignore_retcode",
"=",
"False",
",",
"use_vt",
"=",
"False",
")",
":",
"prefix",
"=",
"'machinectl --no-legend --no-pager'",
"return",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"'{0... | 39.333333 | 0.00207 |
def restore_dataset_to_ckan(catalog, owner_org, dataset_origin_identifier,
portal_url, apikey, download_strategy=None,
generate_new_access_url=None):
"""Restaura la metadata de un dataset en el portal pasado por parámetro.
Args:
catalog (D... | [
"def",
"restore_dataset_to_ckan",
"(",
"catalog",
",",
"owner_org",
",",
"dataset_origin_identifier",
",",
"portal_url",
",",
"apikey",
",",
"download_strategy",
"=",
"None",
",",
"generate_new_access_url",
"=",
"None",
")",
":",
"return",
"push_dataset_to_ckan",
"(",... | 55.413793 | 0.000612 |
def gauge(self, stat, value, tags=None):
"""Set a gauge."""
self._log('gauge', stat, value, tags) | [
"def",
"gauge",
"(",
"self",
",",
"stat",
",",
"value",
",",
"tags",
"=",
"None",
")",
":",
"self",
".",
"_log",
"(",
"'gauge'",
",",
"stat",
",",
"value",
",",
"tags",
")"
] | 37 | 0.017699 |
def check_oversized_pickle(pickled, name, obj_type, worker):
"""Send a warning message if the pickled object is too large.
Args:
pickled: the pickled object.
name: name of the pickled object.
obj_type: type of the pickled object, can be 'function',
'remote function', 'actor'... | [
"def",
"check_oversized_pickle",
"(",
"pickled",
",",
"name",
",",
"obj_type",
",",
"worker",
")",
":",
"length",
"=",
"len",
"(",
"pickled",
")",
"if",
"length",
"<=",
"ray_constants",
".",
"PICKLE_OBJECT_WARNING_SIZE",
":",
"return",
"warning_message",
"=",
... | 39.565217 | 0.001073 |
def create_from_item(self, languages, item, fields, trans_instance=None):
"""
Creates tasks from a model instance "item" (master)
Used in the api call
:param languages:
:param item:
:param fields:
:param trans_instance: determines if we are in bulk mode or not.
... | [
"def",
"create_from_item",
"(",
"self",
",",
"languages",
",",
"item",
",",
"fields",
",",
"trans_instance",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"TranslatableModel",
")",
":",
"return",
"self",
".",
"log",
"(",
"'gonna parse... | 43.428571 | 0.00227 |
def status(ctx, opts, owner_repo_package):
"""
Get the synchronisation status for a package.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'y... | [
"def",
"status",
"(",
"ctx",
",",
"opts",
",",
"owner_repo_package",
")",
":",
"owner",
",",
"repo",
",",
"slug",
"=",
"owner_repo_package",
"click",
".",
"echo",
"(",
"\"Getting status of %(package)s in %(owner)s/%(repo)s ... \"",
"%",
"{",
"\"owner\"",
":",
"cli... | 28.818182 | 0.00122 |
def conf_budget(self, budget):
"""
Set limit on the number of conflicts.
"""
if self.maplesat:
pysolvers.maplesat_cbudget(self.maplesat, budget) | [
"def",
"conf_budget",
"(",
"self",
",",
"budget",
")",
":",
"if",
"self",
".",
"maplesat",
":",
"pysolvers",
".",
"maplesat_cbudget",
"(",
"self",
".",
"maplesat",
",",
"budget",
")"
] | 26.714286 | 0.010363 |
def get_all_datasets(self):
"""
Make sure the datasets are present. If not, downloads and extracts them.
Attempts the download five times because the file hosting is unreliable.
:return: True if successful, false otherwise
"""
success = True
for dataset in tqdm(s... | [
"def",
"get_all_datasets",
"(",
"self",
")",
":",
"success",
"=",
"True",
"for",
"dataset",
"in",
"tqdm",
"(",
"self",
".",
"datasets",
")",
":",
"individual_success",
"=",
"self",
".",
"get_dataset",
"(",
"dataset",
")",
"if",
"not",
"individual_success",
... | 33.928571 | 0.008197 |
def bbox_line_intersect(nodes, line_start, line_end):
r"""Determine intersection of a bounding box and a line.
We do this by first checking if either the start or end node of the
segment are contained in the bounding box. If they aren't, then
checks if the line segment intersects any of the four sides ... | [
"def",
"bbox_line_intersect",
"(",
"nodes",
",",
"line_start",
",",
"line_end",
")",
":",
"left",
",",
"right",
",",
"bottom",
",",
"top",
"=",
"_helpers",
".",
"bbox",
"(",
"nodes",
")",
"if",
"_helpers",
".",
"in_interval",
"(",
"line_start",
"[",
"0",... | 36.861702 | 0.000281 |
def draw(
self,
show_tip_labels=True,
show_node_support=False,
use_edge_lengths=False,
orient="right",
print_args=False,
*args,
**kwargs):
"""
plot the tree using toyplot.graph.
Parameters:
-----------
show_... | [
"def",
"draw",
"(",
"self",
",",
"show_tip_labels",
"=",
"True",
",",
"show_node_support",
"=",
"False",
",",
"use_edge_lengths",
"=",
"False",
",",
"orient",
"=",
"\"right\"",
",",
"print_args",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
"... | 30.361111 | 0.009752 |
def encode(secret: Union[str, bytes], payload: dict = None,
alg: str = default_alg, header: dict = None) -> str:
"""
:param secret: The secret used to encode the token.
:type secret: Union[str, bytes]
:param payload: The payload to be encoded in the token.
:type payload: dict
:param a... | [
"def",
"encode",
"(",
"secret",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"payload",
":",
"dict",
"=",
"None",
",",
"alg",
":",
"str",
"=",
"default_alg",
",",
"header",
":",
"dict",
"=",
"None",
")",
"->",
"str",
":",
"secret",
"=",
"uti... | 33.733333 | 0.000961 |
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 | 0.015228 |
def groupby_sort(columns, column_tys, grouping_columns, grouping_column_tys, key_index, ascending):
"""
Groups the given columns by the corresponding grouping column
value, and aggregate by summing values.
Args:
columns (List<WeldObject>): List of columns as WeldObjects
column_tys (List... | [
"def",
"groupby_sort",
"(",
"columns",
",",
"column_tys",
",",
"grouping_columns",
",",
"grouping_column_tys",
",",
"key_index",
",",
"ascending",
")",
":",
"weld_obj",
"=",
"WeldObject",
"(",
"encoder_",
",",
"decoder_",
")",
"if",
"len",
"(",
"grouping_columns... | 40.417391 | 0.00147 |
def submit_selected(self, btnName=None, update_state=True,
*args, **kwargs):
"""Submit the form that was selected with :func:`select_form`.
:return: Forwarded from :func:`Browser.submit`.
If there are multiple submit input/button elements, passes ``btnName``
to ... | [
"def",
"submit_selected",
"(",
"self",
",",
"btnName",
"=",
"None",
",",
"update_state",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"get_current_form",
"(",
")",
".",
"choose_submit",
"(",
"btnName",
")",
"referer",
... | 43 | 0.002437 |
def _find_mapreduce_yaml(start, checked):
"""Traverse the directory tree identified by start until a directory already
in checked is encountered or the path of mapreduce.yaml is found.
Checked is present both to make loop termination easy to reason about and so
that the same directories do not get rechecked.
... | [
"def",
"_find_mapreduce_yaml",
"(",
"start",
",",
"checked",
")",
":",
"dir",
"=",
"start",
"while",
"dir",
"not",
"in",
"checked",
":",
"checked",
".",
"add",
"(",
"dir",
")",
"for",
"mr_yaml_name",
"in",
"MR_YAML_NAMES",
":",
"yaml_path",
"=",
"os",
".... | 32.391304 | 0.009126 |
def all_axis_bin_centers(self, axis):
"""Return ndarray of same shape as histogram containing bin center value along axis at each point"""
# Arcane hack that seems to work, at least in 3d... hope
axis = self.get_axis_number(axis)
return np.meshgrid(*self.bin_centers(), indexing='ij')[axi... | [
"def",
"all_axis_bin_centers",
"(",
"self",
",",
"axis",
")",
":",
"# Arcane hack that seems to work, at least in 3d... hope",
"axis",
"=",
"self",
".",
"get_axis_number",
"(",
"axis",
")",
"return",
"np",
".",
"meshgrid",
"(",
"*",
"self",
".",
"bin_centers",
"("... | 63.6 | 0.009317 |
def write_all(fd, s, deadline=None):
"""Arrange for all of bytestring `s` to be written to the file descriptor
`fd`.
:param int fd:
File descriptor to write to.
:param bytes s:
Bytestring to write to file descriptor.
:param float deadline:
If not :data:`None`, absolute UNIX ... | [
"def",
"write_all",
"(",
"fd",
",",
"s",
",",
"deadline",
"=",
"None",
")",
":",
"timeout",
"=",
"None",
"written",
"=",
"0",
"poller",
"=",
"PREFERRED_POLLER",
"(",
")",
"poller",
".",
"start_transmit",
"(",
"fd",
")",
"try",
":",
"while",
"written",
... | 32.5 | 0.000679 |
def start_batch(job, input_args):
"""
This function will administer 5 jobs at a time then recursively call itself until subset is empty
"""
samples = parse_sra(input_args['sra'])
# for analysis_id in samples:
job.addChildJobFn(download_and_transfer_sample, input_args, samples, cores=1, disk='30'... | [
"def",
"start_batch",
"(",
"job",
",",
"input_args",
")",
":",
"samples",
"=",
"parse_sra",
"(",
"input_args",
"[",
"'sra'",
"]",
")",
"# for analysis_id in samples:",
"job",
".",
"addChildJobFn",
"(",
"download_and_transfer_sample",
",",
"input_args",
",",
"sampl... | 45 | 0.009346 |
def check_palette(palette):
"""
Check a palette argument (to the :class:`Writer` class) for validity.
Returns the palette as a list if okay;
raises an exception otherwise.
"""
# None is the default and is allowed.
if palette is None:
return None
p = list(palette)
if not (0 ... | [
"def",
"check_palette",
"(",
"palette",
")",
":",
"# None is the default and is allowed.",
"if",
"palette",
"is",
"None",
":",
"return",
"None",
"p",
"=",
"list",
"(",
"palette",
")",
"if",
"not",
"(",
"0",
"<",
"len",
"(",
"p",
")",
"<=",
"256",
")",
... | 33.65625 | 0.000903 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.