text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_root( self, key ):
"""Retrieve the given root by type-key"""
if key not in self.roots:
root,self.rows = load( self.filename, include_interpreter = self.include_interpreter )
self.roots[key] = root
return self.roots[key] | [
"def",
"get_root",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"roots",
":",
"root",
",",
"self",
".",
"rows",
"=",
"load",
"(",
"self",
".",
"filename",
",",
"include_interpreter",
"=",
"self",
".",
"include_interpreter",... | 45 | 15.833333 |
def bookmarks_index_changed(self):
"""Update the UI when the bookmarks combobox has changed."""
index = self.bookmarks_list.currentIndex()
if index >= 0:
self.tool.reset()
rectangle = self.bookmarks_list.itemData(index)
self.tool.set_rectangle(rectangle)
... | [
"def",
"bookmarks_index_changed",
"(",
"self",
")",
":",
"index",
"=",
"self",
".",
"bookmarks_list",
".",
"currentIndex",
"(",
")",
"if",
"index",
">=",
"0",
":",
"self",
".",
"tool",
".",
"reset",
"(",
")",
"rectangle",
"=",
"self",
".",
"bookmarks_lis... | 41.090909 | 9.818182 |
def remove(self, level, logger):
""" Given a level, remove a given logger function
if it is a member of that level, closing the logger
function either way."""
self.config[level].discard(logger)
logger.close() | [
"def",
"remove",
"(",
"self",
",",
"level",
",",
"logger",
")",
":",
"self",
".",
"config",
"[",
"level",
"]",
".",
"discard",
"(",
"logger",
")",
"logger",
".",
"close",
"(",
")"
] | 41.833333 | 8.5 |
def _serialize_call(self, format_, call):
"""Return serialized version of the Call using the record's FORMAT'"""
if isinstance(call, record.UnparsedCall):
return call.unparsed_data
else:
result = [
format_value(self.header.get_format_field_info(key), call.... | [
"def",
"_serialize_call",
"(",
"self",
",",
"format_",
",",
"call",
")",
":",
"if",
"isinstance",
"(",
"call",
",",
"record",
".",
"UnparsedCall",
")",
":",
"return",
"call",
".",
"unparsed_data",
"else",
":",
"result",
"=",
"[",
"format_value",
"(",
"se... | 42 | 15.4 |
def ssn(self):
"""
Returns a 9 digits Dutch SSN called "burgerservicenummer (BSN)".
the Dutch "burgerservicenummer (BSN)" needs to pass the "11-proef",
which is a check digit approach; this function essentially reverses
the checksum steps to create a random valid BSN (which is 9... | [
"def",
"ssn",
"(",
"self",
")",
":",
"# see http://nl.wikipedia.org/wiki/Burgerservicenummer (in Dutch)",
"def",
"_checksum",
"(",
"digits",
")",
":",
"factors",
"=",
"(",
"9",
",",
"8",
",",
"7",
",",
"6",
",",
"5",
",",
"4",
",",
"3",
",",
"2",
",",
... | 39.935484 | 19.548387 |
def dump_data(request):
"""Exports data from whole project.
"""
# Try to grab app_label data
app_label = request.GET.get('app_label', [])
if app_label:
app_label = app_label.split(',')
return dump_to_response(request, app_label=app_label,
exclude=settings.SMUG... | [
"def",
"dump_data",
"(",
"request",
")",
":",
"# Try to grab app_label data",
"app_label",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'app_label'",
",",
"[",
"]",
")",
"if",
"app_label",
":",
"app_label",
"=",
"app_label",
".",
"split",
"(",
"','",
")",... | 36.666667 | 11.111111 |
def reboot(name, call=None):
'''
Reboot a linode.
.. versionadded:: 2015.8.0
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
if call != 'action':
raise SaltCloudException(
'The show_instance ac... | [
"def",
"reboot",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudException",
"(",
"'The show_instance action must be called with -a or --action.'",
")",
"node_id",
"=",
"get_linode_id_from_name",
"(",
"name",
... | 21.866667 | 23.466667 |
def _expectation(p, mean1, none1, mean2, none2, nghp=None):
"""
Compute the expectation:
expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n)
- m1(.) :: Identity mean function
- m2(.) :: Linear mean function
:return: NxDxQ
"""
with params_as_tensors_for(mean2):
N = tf.shape(p.mu)... | [
"def",
"_expectation",
"(",
"p",
",",
"mean1",
",",
"none1",
",",
"mean2",
",",
"none2",
",",
"nghp",
"=",
"None",
")",
":",
"with",
"params_as_tensors_for",
"(",
"mean2",
")",
":",
"N",
"=",
"tf",
".",
"shape",
"(",
"p",
".",
"mu",
")",
"[",
"0"... | 35.25 | 16.5 |
def _generate_hex_for_uris(self, uris):
"""Given uris, generate and return hex version of it
Parameters
----------
uris : list
Containing all uris
Returns
-------
str
Hexed uris
"""
return sha256((":".join(uris) + str(time... | [
"def",
"_generate_hex_for_uris",
"(",
"self",
",",
"uris",
")",
":",
"return",
"sha256",
"(",
"(",
"\":\"",
".",
"join",
"(",
"uris",
")",
"+",
"str",
"(",
"time",
"(",
")",
")",
")",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")"
] | 23.785714 | 20.428571 |
def __get_event(self, block=True, timeout=1):
"""
Retrieves an event. If self._exceeding_event is not None, it'll be
returned. Otherwise, an event is dequeued from the event buffer. If
The event which was retrieved is bigger than the permitted batch size,
it'll be omitted, and th... | [
"def",
"__get_event",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"1",
")",
":",
"while",
"True",
":",
"if",
"self",
".",
"_exceeding_event",
":",
"# An event was omitted from last batch",
"event",
"=",
"self",
".",
"_exceeding_event",
"self",... | 48.25 | 20.5 |
def prepare_method(self, method):
"""Prepares the given HTTP method."""
self.method = method
if self.method is not None:
self.method = self.method.upper() | [
"def",
"prepare_method",
"(",
"self",
",",
"method",
")",
":",
"self",
".",
"method",
"=",
"method",
"if",
"self",
".",
"method",
"is",
"not",
"None",
":",
"self",
".",
"method",
"=",
"self",
".",
"method",
".",
"upper",
"(",
")"
] | 37.2 | 5.8 |
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
packet = cls()
# Convert to ConstBitStream (if not already provided)
if not isinstance(bitstream, ConstBitStream):
if isinstance(bitstream, Bits):
... | [
"def",
"from_bytes",
"(",
"cls",
",",
"bitstream",
")",
":",
"packet",
"=",
"cls",
"(",
")",
"# Convert to ConstBitStream (if not already provided)",
"if",
"not",
"isinstance",
"(",
"bitstream",
",",
"ConstBitStream",
")",
":",
"if",
"isinstance",
"(",
"bitstream"... | 31.052632 | 18.842105 |
def reflect(self, data, width):
"""
reflect a data word, i.e. reverts the bit order.
"""
x = data & 0x01
for i in range(width - 1):
data >>= 1
x = (x << 1) | (data & 0x01)
return x | [
"def",
"reflect",
"(",
"self",
",",
"data",
",",
"width",
")",
":",
"x",
"=",
"data",
"&",
"0x01",
"for",
"i",
"in",
"range",
"(",
"width",
"-",
"1",
")",
":",
"data",
">>=",
"1",
"x",
"=",
"(",
"x",
"<<",
"1",
")",
"|",
"(",
"data",
"&",
... | 27.111111 | 10 |
def _find_relations(self):
"""Find all relevant relation elements and return them in a list."""
# Get all extractions
extractions = \
list(self.tree.execute("$.extractions[(@.@type is 'Extraction')]"))
# Get relations from extractions
relations = []
for e in ... | [
"def",
"_find_relations",
"(",
"self",
")",
":",
"# Get all extractions",
"extractions",
"=",
"list",
"(",
"self",
".",
"tree",
".",
"execute",
"(",
"\"$.extractions[(@.@type is 'Extraction')]\"",
")",
")",
"# Get relations from extractions",
"relations",
"=",
"[",
"]... | 43.357143 | 15.928571 |
def GetMessages(self, files):
"""Gets all the messages from a specified file.
This will find and resolve dependencies, failing if the descriptor
pool cannot satisfy them.
Args:
files: The file names to extract messages from.
Returns:
A dictionary mapping proto names to the message cla... | [
"def",
"GetMessages",
"(",
"self",
",",
"files",
")",
":",
"result",
"=",
"{",
"}",
"for",
"file_name",
"in",
"files",
":",
"file_desc",
"=",
"self",
".",
"pool",
".",
"FindFileByName",
"(",
"file_name",
")",
"for",
"name",
",",
"msg",
"in",
"file_desc... | 40.275 | 22.675 |
def get_readme():
"""Generate long description"""
pandoc = None
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
pandoc = os.path.join(path, 'pandoc')
if os.path.isfile(pandoc) and os.access(pandoc, os.X_OK):
break
else:
pandoc ... | [
"def",
"get_readme",
"(",
")",
":",
"pandoc",
"=",
"None",
"for",
"path",
"in",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"path",
"=",
"path",
".",
"strip",
"(",
"'\"'",
")",
"pandoc",
"=",
"os... | 31.578947 | 17.315789 |
def get_file(fname, datapath=datapath):
"""Return path of an example data file
Return the full path to an example data file name.
If the file does not exist in the `datapath` directory,
tries to download it from the ODTbrain GitHub repository.
"""
# download location
datapath = pathlib.Path... | [
"def",
"get_file",
"(",
"fname",
",",
"datapath",
"=",
"datapath",
")",
":",
"# download location",
"datapath",
"=",
"pathlib",
".",
"Path",
"(",
"datapath",
")",
"datapath",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"... | 34.285714 | 15.761905 |
def redata(self, *args, **kwargs):
"""Update my ``data`` to match what's in my ``store``"""
select_name = kwargs.get('select_name')
if not self.store:
Clock.schedule_once(self.redata)
return
self.data = list(map(self.munge, enumerate(self._iter_keys())))
i... | [
"def",
"redata",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"select_name",
"=",
"kwargs",
".",
"get",
"(",
"'select_name'",
")",
"if",
"not",
"self",
".",
"store",
":",
"Clock",
".",
"schedule_once",
"(",
"self",
".",
"redata",... | 41.888889 | 12.333333 |
def cdfNormal(z):
"""
Robust implementations of cdf of a standard normal.
@see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]]
in C from Matthias Seeger.
*/
"""
if (abs(z) < ERF_CODY_LIMIT1):
# Phi(z) approx (1+y ... | [
"def",
"cdfNormal",
"(",
"z",
")",
":",
"if",
"(",
"abs",
"(",
"z",
")",
"<",
"ERF_CODY_LIMIT1",
")",
":",
"# Phi(z) approx (1+y R_3(y^2))/2, y=z/sqrt(2)",
"return",
"0.5",
"*",
"(",
"1.0",
"+",
"(",
"z",
"/",
"M_SQRT2",
")",
"*",
"_erfRationalHelperR3",
"... | 39.125 | 23.75 |
def run(self, request, tempdir, opts):
"""
Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
... | [
"def",
"run",
"(",
"self",
",",
"request",
",",
"tempdir",
",",
"opts",
")",
":",
"wftype",
"=",
"request",
"[",
"'workflow_type'",
"]",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"version",
"=",
"request",
"[",
"'workflow_type_version'",
"]",
"if... | 41.82 | 24.34 |
def get_category(category_id):
"""Return a PYBOSSA Category for the category_id.
:param category_id: PYBOSSA Category ID
:type category_id: integer
:rtype: PYBOSSA Category
:returns: A PYBOSSA Category object
"""
try:
res = _pybossa_req('get', 'category', category_id)
if re... | [
"def",
"get_category",
"(",
"category_id",
")",
":",
"try",
":",
"res",
"=",
"_pybossa_req",
"(",
"'get'",
",",
"'category'",
",",
"category_id",
")",
"if",
"res",
".",
"get",
"(",
"'id'",
")",
":",
"return",
"Category",
"(",
"res",
")",
"else",
":",
... | 25.411765 | 15.882353 |
def right_associative_infix_rule(operator, grammar_rule):
"""Semantic action for rules like 'A = B (C B)*'."""
def semantic_action(self, node, (result, remaining)):
while remaining:
op, rhs = remaining.pop(0)
result = operator(Attr(result, Name(self.aliases[op])), [rhs], op)
... | [
"def",
"right_associative_infix_rule",
"(",
"operator",
",",
"grammar_rule",
")",
":",
"def",
"semantic_action",
"(",
"self",
",",
"node",
",",
"(",
"result",
",",
"remaining",
")",
")",
":",
"while",
"remaining",
":",
"op",
",",
"rhs",
"=",
"remaining",
"... | 47.375 | 14.625 |
def commit_file(self, message, path, content):
"""
Add a new file as blob in the storage, add its tree entry into the index and commit the index.
:param message: str
:param path: str
:param content: str
:return:
"""
if self.git_batch_commit:
... | [
"def",
"commit_file",
"(",
"self",
",",
"message",
",",
"path",
",",
"content",
")",
":",
"if",
"self",
".",
"git_batch_commit",
":",
"self",
".",
"add_file",
"(",
"path",
",",
"content",
")",
"self",
".",
"git_batch_commit_messages",
".",
"append",
"(",
... | 30.85 | 17.05 |
def refresh_plugin(self):
"""Refresh tabwidget"""
if self.tabwidget.count():
editor = self.tabwidget.currentWidget()
else:
editor = None
self.find_widget.set_editor(editor) | [
"def",
"refresh_plugin",
"(",
"self",
")",
":",
"if",
"self",
".",
"tabwidget",
".",
"count",
"(",
")",
":",
"editor",
"=",
"self",
".",
"tabwidget",
".",
"currentWidget",
"(",
")",
"else",
":",
"editor",
"=",
"None",
"self",
".",
"find_widget",
".",
... | 32.571429 | 10.571429 |
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of ... | [
"def",
"add_interface_router",
"(",
"router",
",",
"subnet",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"add_interface_router",
"(",
"router",
",",
"subnet",
")"
] | 29 | 22.058824 |
def default_gateway():
'''
Populates grains which describe whether a server has a default gateway
configured or not. Uses `ip -4 route show` and `ip -6 route show` and greps
for a `default` at the beginning of any line. Assuming the standard
`default via <ip>` format for default gateways, it will al... | [
"def",
"default_gateway",
"(",
")",
":",
"grains",
"=",
"{",
"}",
"ip_bin",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'ip'",
")",
"if",
"not",
"ip_bin",
":",
"return",
"{",
"}",
"grains",
"[",
"'ip_gw'",
"]",
"=",
"False",
"grains... | 38.045455 | 21.909091 |
def move(self, path, destination):
"""
Move a path to destination
:param path: source
:param destination: destination
:return:
"""
args = {
'path': path,
'destination': destination,
}
return self._client.json('filesystem.m... | [
"def",
"move",
"(",
"self",
",",
"path",
",",
"destination",
")",
":",
"args",
"=",
"{",
"'path'",
":",
"path",
",",
"'destination'",
":",
"destination",
",",
"}",
"return",
"self",
".",
"_client",
".",
"json",
"(",
"'filesystem.move'",
",",
"args",
")... | 22.714286 | 15.571429 |
def plot_loglogs(cls, loc=None, iloc=None, show_censors=False, censor_styles=None, **kwargs):
"""
Specifies a plot of the log(-log(SV)) versus log(time) where SV is the estimated survival function.
"""
def loglog(s):
return np.log(-np.log(s))
if (loc is not None) and (iloc is not None):
... | [
"def",
"plot_loglogs",
"(",
"cls",
",",
"loc",
"=",
"None",
",",
"iloc",
"=",
"None",
",",
"show_censors",
"=",
"False",
",",
"censor_styles",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"loglog",
"(",
"s",
")",
":",
"return",
"np",
".",... | 33.894737 | 24.736842 |
def main(argString=None):
"""The main function of the module..
Here are the steps for duplicated samples:
1. Prints the options.
2. Reads the ``map`` file to gather marker's position
(:py:func:`readMAP`).
3. Reads the ``tfam`` file (:py:func:`readTFAM`).
4. Finds the unique markers... | [
"def",
"main",
"(",
"argString",
"=",
"None",
")",
":",
"# Getting and checking the options",
"args",
"=",
"parseArgs",
"(",
"argString",
")",
"checkArgs",
"(",
"args",
")",
"logger",
".",
"info",
"(",
"\"Options used:\"",
")",
"for",
"key",
",",
"value",
"i... | 40.51773 | 20.12766 |
def _rank(self, ranking, n):
""" return the first n sentences with highest ranking """
return nlargest(n, ranking, key=ranking.get) | [
"def",
"_rank",
"(",
"self",
",",
"ranking",
",",
"n",
")",
":",
"return",
"nlargest",
"(",
"n",
",",
"ranking",
",",
"key",
"=",
"ranking",
".",
"get",
")"
] | 45.666667 | 6.666667 |
def base_definition_post_delete(sender, instance, **kwargs):
"""
Make sure to delete fields inherited from an abstract model base.
"""
if hasattr(instance._state, '_deletion'):
# Make sure to flatten abstract bases since Django
# migrations can't deal with them.
model = popattr(i... | [
"def",
"base_definition_post_delete",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"instance",
".",
"_state",
",",
"'_deletion'",
")",
":",
"# Make sure to flatten abstract bases since Django",
"# migrations can't deal with th... | 44.2 | 10.8 |
def _text_or_file(input_):
'''
Determines if input is a path to a file, or a string with the
content to be parsed.
'''
if _isfile(input_):
with salt.utils.files.fopen(input_) as fp_:
out = salt.utils.stringutils.to_str(fp_.read())
else:
out = salt.utils.stringutils.to... | [
"def",
"_text_or_file",
"(",
"input_",
")",
":",
"if",
"_isfile",
"(",
"input_",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"input_",
")",
"as",
"fp_",
":",
"out",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"t... | 28.083333 | 22.916667 |
def send(self, request, **kw):
"""
Send a request. Use the request information to see if it
exists in the cache and cache the response if we need to and can.
"""
if request.method == 'GET':
cached_response = self.controller.cached_request(request)
if cache... | [
"def",
"send",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kw",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"cached_response",
"=",
"self",
".",
"controller",
".",
"cached_request",
"(",
"request",
")",
"if",
"cached_response",
":",
... | 37.105263 | 20.894737 |
def gen_lt(self):
"""Generate a new LoginTicket and add it to the list of valid LT for the user"""
self.request.session['lt'] = self.request.session.get('lt', []) + [utils.gen_lt()]
if len(self.request.session['lt']) > 100:
self.request.session['lt'] = self.request.session['lt'][-100... | [
"def",
"gen_lt",
"(",
"self",
")",
":",
"self",
".",
"request",
".",
"session",
"[",
"'lt'",
"]",
"=",
"self",
".",
"request",
".",
"session",
".",
"get",
"(",
"'lt'",
",",
"[",
"]",
")",
"+",
"[",
"utils",
".",
"gen_lt",
"(",
")",
"]",
"if",
... | 63.6 | 23.2 |
def load_all_methods(self):
r'''Method to initialize the object by precomputing any values which
may be used repeatedly and by retrieving mixture-specific variables.
All data are stored as attributes. This method also sets :obj:`Tmin`,
:obj:`Tmax`, and :obj:`all_methods` as a set of met... | [
"def",
"load_all_methods",
"(",
"self",
")",
":",
"methods",
"=",
"[",
"SIMPLE",
"]",
"if",
"none_and_length_check",
"(",
"[",
"self",
".",
"Tcs",
",",
"self",
".",
"Vcs",
",",
"self",
".",
"omegas",
",",
"self",
".",
"CASs",
"]",
")",
":",
"methods"... | 52.833333 | 24.111111 |
def iter(self, keyed=False, extended=False, cast=True, relations=False):
"""https://github.com/frictionlessdata/tableschema-py#schema
"""
# Prepare unique checks
if cast:
unique_fields_cache = {}
if self.schema:
unique_fields_cache = _create_uniqu... | [
"def",
"iter",
"(",
"self",
",",
"keyed",
"=",
"False",
",",
"extended",
"=",
"False",
",",
"cast",
"=",
"True",
",",
"relations",
"=",
"False",
")",
":",
"# Prepare unique checks",
"if",
"cast",
":",
"unique_fields_cache",
"=",
"{",
"}",
"if",
"self",
... | 40.098361 | 20.868852 |
def command_help_long(self):
"""
Return command help for use in global parser usage string
@TODO update to support self.current_indent from formatter
"""
indent = " " * 2 # replace with current_indent
help = "Command must be one of:\n"
for action_name in self.parser.valid_commands... | [
"def",
"command_help_long",
"(",
"self",
")",
":",
"indent",
"=",
"\" \"",
"*",
"2",
"# replace with current_indent",
"help",
"=",
"\"Command must be one of:\\n\"",
"for",
"action_name",
"in",
"self",
".",
"parser",
".",
"valid_commands",
":",
"help",
"+=",
"\"%s%... | 44.833333 | 22.5 |
def post_data(api_key=None, name='OpsGenie Execution Module', reason=None,
action_type=None):
'''
Post data to OpsGenie. It's designed for Salt's Event Reactor.
After configuring the sls reaction file as shown above, you can trigger the
module with your designated tag (og-tag in this case... | [
"def",
"post_data",
"(",
"api_key",
"=",
"None",
",",
"name",
"=",
"'OpsGenie Execution Module'",
",",
"reason",
"=",
"None",
",",
"action_type",
"=",
"None",
")",
":",
"if",
"api_key",
"is",
"None",
"or",
"reason",
"is",
"None",
":",
"raise",
"salt",
".... | 34.547945 | 21.616438 |
def _get_NTLMv1_response(password, server_challenge):
"""
[MS-NLMP] v28.0 2016-07-14
2.2.2.6 NTLM v1 Response: NTLM_RESPONSE
The NTLM_RESPONSE strucutre defines the NTLM v1 authentication NtChallengeResponse
in the AUTHENTICATE_MESSAGE. This response is only used when NTLM v1 au... | [
"def",
"_get_NTLMv1_response",
"(",
"password",
",",
"server_challenge",
")",
":",
"ntlm_hash",
"=",
"comphash",
".",
"_ntowfv1",
"(",
"password",
")",
"response",
"=",
"ComputeResponse",
".",
"_calc_resp",
"(",
"ntlm_hash",
",",
"server_challenge",
")",
"session_... | 46.8 | 28.1 |
def recover_constants(py_source,
replacements): #now has n^2 complexity. improve to n
'''Converts identifiers representing Js constants to the PyJs constants
PyJsNumberConst_1_ which has the true value of 5 will be converted to PyJsNumber(5)'''
for identifier, value in replacements.it... | [
"def",
"recover_constants",
"(",
"py_source",
",",
"replacements",
")",
":",
"#now has n^2 complexity. improve to n",
"for",
"identifier",
",",
"value",
"in",
"replacements",
".",
"iteritems",
"(",
")",
":",
"if",
"identifier",
".",
"startswith",
"(",
"'PyJsConstant... | 55.5 | 23.357143 |
def follow_request_authorize(self, id):
"""
Accept an incoming follow request.
"""
id = self.__unpack_id(id)
url = '/api/v1/follow_requests/{0}/authorize'.format(str(id))
self.__api_request('POST', url) | [
"def",
"follow_request_authorize",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/follow_requests/{0}/authorize'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"self",
".",
"__api_request",
... | 34.857143 | 5.714286 |
def build_filter(date_min=None, date_max=None, obj_event=None, obj_id=None, obj_type=None, utc_offset=None):
"""Returns a query filter that can be passed into EventLogManager.get_event_logs
:param string date_min: Lower bound date in MM/DD/YYYY format
:param string date_max: Upper bound date in... | [
"def",
"build_filter",
"(",
"date_min",
"=",
"None",
",",
"date_max",
"=",
"None",
",",
"obj_event",
"=",
"None",
",",
"obj_id",
"=",
"None",
",",
"obj_type",
"=",
"None",
",",
"utc_offset",
"=",
"None",
")",
":",
"if",
"not",
"any",
"(",
"[",
"date_... | 42.567568 | 31.189189 |
def run_init(args):
"""
Run project initialization.
This will ask the user for input.
Parameters
----------
args : argparse named arguments
"""
root = args.root
if root is None:
root = '.'
root = os.path.abspath(root)
project_data = _get_package_data()
project_... | [
"def",
"run_init",
"(",
"args",
")",
":",
"root",
"=",
"args",
".",
"root",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"'.'",
"root",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"root",
")",
"project_data",
"=",
"_get_package_data",
"(",
")",
"... | 39.016667 | 17.05 |
def remote_ssh(self, host):
""" Execute a command on SSH. Takes a paramiko host dict """
logger.info('Starting remote execution of task {0} on host {1}'.format(self.name, host['hostname']))
try:
self.remote_client = paramiko.SSHClient()
self.remote_client.load_system_host... | [
"def",
"remote_ssh",
"(",
"self",
",",
"host",
")",
":",
"logger",
".",
"info",
"(",
"'Starting remote execution of task {0} on host {1}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"host",
"[",
"'hostname'",
"]",
")",
")",
"try",
":",
"self",
".",
"re... | 56.137931 | 21.793103 |
async def loop(self):
"""
Return bot's main loop as coroutine. Use with asyncio.
:Example:
>>> loop = asyncio.get_event_loop()
>>> loop.run_until_complete(bot.loop())
or
>>> loop = asyncio.get_event_loop()
>>> loop.create_task(bot.loop())
"""
... | [
"async",
"def",
"loop",
"(",
"self",
")",
":",
"self",
".",
"_running",
"=",
"True",
"while",
"self",
".",
"_running",
":",
"updates",
"=",
"await",
"self",
".",
"api_call",
"(",
"\"getUpdates\"",
",",
"offset",
"=",
"self",
".",
"_offset",
"+",
"1",
... | 26.85 | 18.05 |
def s2time(secs, show_secs=True, show_fracs=True):
"""Converts seconds to time"""
try:
secs = float(secs)
except:
return "--:--:--.--"
wholesecs = int(secs)
centisecs = int((secs - wholesecs) * 100)
hh = int(wholesecs / 3600)
hd = int(hh % 24)
mm = int((wholesecs / 60) - ... | [
"def",
"s2time",
"(",
"secs",
",",
"show_secs",
"=",
"True",
",",
"show_fracs",
"=",
"True",
")",
":",
"try",
":",
"secs",
"=",
"float",
"(",
"secs",
")",
"except",
":",
"return",
"\"--:--:--.--\"",
"wholesecs",
"=",
"int",
"(",
"secs",
")",
"centisecs... | 28.944444 | 12.944444 |
def p_statement_break(p):
'''statement : BREAK SEMI
| BREAK expr SEMI'''
if len(p) == 3:
p[0] = ast.Break(None, lineno=p.lineno(1))
else:
p[0] = ast.Break(p[2], lineno=p.lineno(1)) | [
"def",
"p_statement_break",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Break",
"(",
"None",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"else",
":",
"p",
"[",
"0",
... | 31.285714 | 14.428571 |
def install_egg(self, egg_name):
""" Install an egg into the egg directory """
if not os.path.exists(self.egg_directory):
os.makedirs(self.egg_directory)
self.requirement_set.add_requirement(
InstallRequirement.from_line(egg_name, None))
try:
self.requ... | [
"def",
"install_egg",
"(",
"self",
",",
"egg_name",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"egg_directory",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"egg_directory",
")",
"self",
".",
"requirement_set",
"."... | 47.25 | 14.166667 |
def queue(self, queue, message, params={}, uids=[]):
"""
Queue a job in Rhumba
"""
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid in uids:
... | [
"def",
"queue",
"(",
"self",
",",
"queue",
",",
"message",
",",
"params",
"=",
"{",
"}",
",",
"uids",
"=",
"[",
"]",
")",
":",
"d",
"=",
"{",
"'id'",
":",
"uuid",
".",
"uuid1",
"(",
")",
".",
"get_hex",
"(",
")",
",",
"'version'",
":",
"1",
... | 26.947368 | 18 |
def rmtree_errorhandler(func, path, exc_info):
"""On Windows, the files in .svn are read-only, so when rmtree() tries to
remove them, an exception is thrown. We catch that here, remove the
read-only attribute, and hopefully continue without problems."""
# if file type currently read only
if os.stat... | [
"def",
"rmtree_errorhandler",
"(",
"func",
",",
"path",
",",
"exc_info",
")",
":",
"# if file type currently read only",
"if",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mode",
"&",
"stat",
".",
"S_IREAD",
":",
"# convert to read/write",
"os",
".",
"chmod",... | 40.461538 | 13.923077 |
def talkerIndication():
"""TALKER INDICATION Section 9.1.44"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0x11) # 00010001
c = MobileStationClassmark2()
d = MobileId()
packet = a / b / c / d
return packet | [
"def",
"talkerIndication",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x6",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x11",
")",
"# 00010001",
"c",
"=",
"MobileStationClassmark2",
"(",
")",
"d",
"=",
"MobileId",
"(",
")",
"packet",
... | 28 | 13.5 |
def subdivide(self, N=1, method=0):
"""Increase the number of vertices of a surface mesh.
:param int N: number of subdivisions.
:param int method: Loop(0), Linear(1), Adaptive(2), Butterfly(3)
.. hint:: |tutorial_subdivide| |tutorial.py|_
"""
triangles = vtk.vtkTriangle... | [
"def",
"subdivide",
"(",
"self",
",",
"N",
"=",
"1",
",",
"method",
"=",
"0",
")",
":",
"triangles",
"=",
"vtk",
".",
"vtkTriangleFilter",
"(",
")",
"triangles",
".",
"SetInputData",
"(",
"self",
".",
"polydata",
"(",
")",
")",
"triangles",
".",
"Upd... | 36.321429 | 14.392857 |
def create(context, name, team_id, data, active):
"""create(context, name, team_id, data, active)
Create a Remote CI
>>> dcictl remoteci-create [OPTIONS]
:param string name: Name of the Remote CI [required]
:param string team_id: ID of the team to associate this remote CI with
[required]
... | [
"def",
"create",
"(",
"context",
",",
"name",
",",
"team_id",
",",
"data",
",",
"active",
")",
":",
"state",
"=",
"utils",
".",
"active_string",
"(",
"active",
")",
"team_id",
"=",
"team_id",
"or",
"identity",
".",
"my_team_id",
"(",
"context",
")",
"r... | 37.05 | 18.25 |
def fit_quadrature(orth, nodes, weights, solves, retall=False, norms=None, **kws):
"""
Using spectral projection to create a polynomial approximation over
distribution space.
Args:
orth (chaospy.poly.base.Poly):
Orthogonal polynomial expansion. Must be orthogonal for the
... | [
"def",
"fit_quadrature",
"(",
"orth",
",",
"nodes",
",",
"weights",
",",
"solves",
",",
"retall",
"=",
"False",
",",
"norms",
"=",
"None",
",",
"*",
"*",
"kws",
")",
":",
"orth",
"=",
"chaospy",
".",
"poly",
".",
"Poly",
"(",
"orth",
")",
"nodes",
... | 37.929825 | 21.192982 |
def _extract_future_flags(globs):
"""
Return the compiler-flags associated with the future features that
have been imported into the given namespace (globs).
"""
flags = 0
for fname in __future__.all_feature_names:
feature = globs.get(fname, None)
if feature is getattr(__future__... | [
"def",
"_extract_future_flags",
"(",
"globs",
")",
":",
"flags",
"=",
"0",
"for",
"fname",
"in",
"__future__",
".",
"all_feature_names",
":",
"feature",
"=",
"globs",
".",
"get",
"(",
"fname",
",",
"None",
")",
"if",
"feature",
"is",
"getattr",
"(",
"__f... | 34.454545 | 11 |
def analisar_retorno(retorno,
classe_resposta=RespostaSAT, campos=RespostaSAT.CAMPOS,
campos_alternativos=[], funcao=None, manter_verbatim=True):
"""Analisa o retorno (supostamente um retorno de uma função do SAT) conforme
o padrão e campos esperados. O retorno deverá possuir dados separados ent... | [
"def",
"analisar_retorno",
"(",
"retorno",
",",
"classe_resposta",
"=",
"RespostaSAT",
",",
"campos",
"=",
"RespostaSAT",
".",
"CAMPOS",
",",
"campos_alternativos",
"=",
"[",
"]",
",",
"funcao",
"=",
"None",
",",
"manter_verbatim",
"=",
"True",
")",
":",
"if... | 38.617021 | 24.776596 |
def make_cookies(self, response, request):
"""Return sequence of Cookie objects extracted from response object."""
# get cookie-attributes for RFC 2965 and Netscape protocols
headers = response.info()
rfc2965_hdrs = headers.get_all("Set-Cookie2", [])
ns_hdrs = headers.get_all("Se... | [
"def",
"make_cookies",
"(",
"self",
",",
"response",
",",
"request",
")",
":",
"# get cookie-attributes for RFC 2965 and Netscape protocols",
"headers",
"=",
"response",
".",
"info",
"(",
")",
"rfc2965_hdrs",
"=",
"headers",
".",
"get_all",
"(",
"\"Set-Cookie2\"",
"... | 40.566038 | 19.075472 |
def set_pkg_file_name(self, doc, name):
"""Sets the package file name, if not already set.
name - Any string.
Raises CardinalityError if already has a file_name.
Raises OrderError if no pacakge previously defined.
"""
self.assert_package_exists()
if not self.packa... | [
"def",
"set_pkg_file_name",
"(",
"self",
",",
"doc",
",",
"name",
")",
":",
"self",
".",
"assert_package_exists",
"(",
")",
"if",
"not",
"self",
".",
"package_file_name_set",
":",
"self",
".",
"package_file_name_set",
"=",
"True",
"doc",
".",
"package",
".",... | 38.923077 | 9.461538 |
def app_restart(name, profile, **kwargs):
"""
Restart application.
Executes ```cocaine-tool app pause``` and ```cocaine-tool app start``` sequentially.
It can be used to quickly change application profile.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:restart', **{
'node': ct... | [
"def",
"app_restart",
"(",
"name",
",",
"profile",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'app:restart'",
",",
"*",
"*",
"{",
"'node'",
":",
"ctx",
".",
"repo",
".... | 28.8 | 17.733333 |
def full_file_list(scan_path):
"""
Returns a list of all files in a folder and its subfolders (only files).
"""
file_list = []
path = os.path.abspath(scan_path)
for root, dirs, files in os.walk(path):
if len(files) != 0 and not '.svn' in root and not '.git' in root:
for f in ... | [
"def",
"full_file_list",
"(",
"scan_path",
")",
":",
"file_list",
"=",
"[",
"]",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"scan_path",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"if",
... | 35.727273 | 14.090909 |
def _create_action(factory_self, action_model, resource_name,
service_context, is_load=False):
"""
Creates a new method which makes a request to the underlying
AWS service.
"""
# Create the action in in this closure but before the ``do_action``
# me... | [
"def",
"_create_action",
"(",
"factory_self",
",",
"action_model",
",",
"resource_name",
",",
"service_context",
",",
"is_load",
"=",
"False",
")",
":",
"# Create the action in in this closure but before the ``do_action``",
"# method below is invoked, which allows instances of the ... | 41.793103 | 17.758621 |
def convert(model, input_features, output_features):
"""Convert a _imputer model to the protobuf spec.
Parameters
----------
model: Imputer
A trained Imputer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Retur... | [
"def",
"convert",
"(",
"model",
",",
"input_features",
",",
"output_features",
")",
":",
"_INTERMEDIATE_FEATURE_NAME",
"=",
"\"__sparse_vector_features__\"",
"n_dimensions",
"=",
"len",
"(",
"model",
".",
"feature_names_",
")",
"input_features",
"=",
"process_or_validat... | 34.216216 | 23.756757 |
def _remember_videos(page, fetches, stitch_ups=None):
'''
Saves info about videos captured by youtube-dl in `page.videos`.
'''
if not 'videos' in page:
page.videos = []
for fetch in fetches or []:
content_type = fetch['response_headers'].get_content_type()
if (content_type.st... | [
"def",
"_remember_videos",
"(",
"page",
",",
"fetches",
",",
"stitch_ups",
"=",
"None",
")",
":",
"if",
"not",
"'videos'",
"in",
"page",
":",
"page",
".",
"videos",
"=",
"[",
"]",
"for",
"fetch",
"in",
"fetches",
"or",
"[",
"]",
":",
"content_type",
... | 44.692308 | 15.512821 |
def focusOutEvent(self, event):
"""Reimplement Qt method to send focus change notification"""
self.focus_changed.emit()
return super(ShellWidget, self).focusOutEvent(event) | [
"def",
"focusOutEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"focus_changed",
".",
"emit",
"(",
")",
"return",
"super",
"(",
"ShellWidget",
",",
"self",
")",
".",
"focusOutEvent",
"(",
"event",
")"
] | 48.25 | 9 |
def send(signal):
"""Send signal.
The signal has a unique identifier that is computed from (1) the id
of the actor or task sending this signal (i.e., the actor or task calling
this function), and (2) an index that is incremented every time this
source sends a signal. This index starts from 1.
... | [
"def",
"send",
"(",
"signal",
")",
":",
"if",
"hasattr",
"(",
"ray",
".",
"worker",
".",
"global_worker",
",",
"\"actor_creation_task_id\"",
")",
":",
"source_key",
"=",
"ray",
".",
"worker",
".",
"global_worker",
".",
"actor_id",
".",
"hex",
"(",
")",
"... | 40.95 | 24.75 |
def patch_cluster_custom_object(self, group, version, plural, name, body, **kwargs): # noqa: E501
"""patch_cluster_custom_object # noqa: E501
patch the specified cluster scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous... | [
"def",
"patch_cluster_custom_object",
"(",
"self",
",",
"group",
",",
"version",
",",
"plural",
",",
"name",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"... | 57.08 | 30.88 |
def before_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add a before request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.before_request
def func():
...
Argum... | [
"def",
"before_request",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"name",
":",
"AppOrBlueprintKey",
"=",
"None",
")",
"->",
"Callable",
":",
"handler",
"=",
"ensure_coroutine",
"(",
"func",
")",
"self",
".",
"before_request_funcs",
"[",
"name",
"]",
... | 29.888889 | 20.333333 |
def raise_expired_not_yet_valid(certificate):
"""
Raises a TLSVerificationError due to certificate being expired, or not yet
being valid
:param certificate:
An asn1crypto.x509.Certificate object
:raises:
TLSVerificationError
"""
validity = certificate['tbs_certificate']['v... | [
"def",
"raise_expired_not_yet_valid",
"(",
"certificate",
")",
":",
"validity",
"=",
"certificate",
"[",
"'tbs_certificate'",
"]",
"[",
"'validity'",
"]",
"not_after",
"=",
"validity",
"[",
"'not_after'",
"]",
".",
"native",
"not_before",
"=",
"validity",
"[",
"... | 34.192308 | 24.192308 |
def from_text(text, origin = root):
"""Convert text into a Name object.
@rtype: dns.name.Name object
"""
if not isinstance(text, str):
if isinstance(text, unicode) and sys.hexversion >= 0x02030000:
return from_unicode(text, origin)
else:
raise ValueError("input t... | [
"def",
"from_text",
"(",
"text",
",",
"origin",
"=",
"root",
")",
":",
"if",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"unicode",
")",
"and",
"sys",
".",
"hexversion",
">=",
"0x02030000",
":",
"retu... | 30.466667 | 13.333333 |
def demo():
"""Outline basic demo."""
A = poisson((100, 100), format='csr') # 2D FD Poisson problem
B = None # no near-null spaces guesses for SA
b = sp.rand(A.shape[0], 1) # a random right-hand side
# use AMG based on Smoothed Aggregation (SA) and display in... | [
"def",
"demo",
"(",
")",
":",
"A",
"=",
"poisson",
"(",
"(",
"100",
",",
"100",
")",
",",
"format",
"=",
"'csr'",
")",
"# 2D FD Poisson problem",
"B",
"=",
"None",
"# no near-null spaces guesses for SA",
"b",
"=",
"sp",
".",
"rand",
"(",
"A",
".",
"sha... | 38.829787 | 22.468085 |
def parse_on_event(self, node):
"""
Parses <OnEvent>
@param node: Node containing the <OnEvent> element
@type node: xml.etree.Element
"""
try:
port = node.lattrib['port']
except:
self.raise_error('<OnEvent> must specify a port.')
... | [
"def",
"parse_on_event",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"port",
"=",
"node",
".",
"lattrib",
"[",
"'port'",
"]",
"except",
":",
"self",
".",
"raise_error",
"(",
"'<OnEvent> must specify a port.'",
")",
"event_handler",
"=",
"OnEvent",
"(",
... | 26.9 | 17.3 |
def pagination(self):
"""Return all page parameters as a dict.
:return dict: a dict of pagination information
To allow multiples strategies, all parameters starting with `page` will be included. e.g::
{
"number": '25',
"size": '150',
}
... | [
"def",
"pagination",
"(",
"self",
")",
":",
"# check values type",
"result",
"=",
"self",
".",
"_get_key_values",
"(",
"'page'",
")",
"for",
"key",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"(",
"'number'",
",... | 41.189189 | 28.513514 |
def finalize(self):
"""
Add title and modify axes to make the image ready for display.
"""
self.set_title(
'{} Manifold (fit in {:0.2f} seconds)'.format(
self._name, self.fit_time_.interval
)
)
self.ax.set_xticklabels([])
se... | [
"def",
"finalize",
"(",
"self",
")",
":",
"self",
".",
"set_title",
"(",
"'{} Manifold (fit in {:0.2f} seconds)'",
".",
"format",
"(",
"self",
".",
"_name",
",",
"self",
".",
"fit_time_",
".",
"interval",
")",
")",
"self",
".",
"ax",
".",
"set_xticklabels",
... | 32.473684 | 17.315789 |
def create(env_dir, system_site_packages=False, clear=False,
symlinks=False, with_pip=False, prompt=None):
"""Create a virtual environment in a directory."""
builder = ExtendedEnvBuilder(system_site_packages=system_site_packages,
clear=clear, symlinks=symlink... | [
"def",
"create",
"(",
"env_dir",
",",
"system_site_packages",
"=",
"False",
",",
"clear",
"=",
"False",
",",
"symlinks",
"=",
"False",
",",
"with_pip",
"=",
"False",
",",
"prompt",
"=",
"None",
")",
":",
"builder",
"=",
"ExtendedEnvBuilder",
"(",
"system_s... | 54.625 | 19.625 |
def format_num(num, unit='bytes'):
"""
Returns a human readable string of a byte-value.
If 'num' is bits, set unit='bits'.
"""
if unit == 'bytes':
extension = 'B'
else:
# if it's not bytes, it's bits
extension = 'Bit'
for dimension in (unit, 'K', 'M', 'G', 'T'):
... | [
"def",
"format_num",
"(",
"num",
",",
"unit",
"=",
"'bytes'",
")",
":",
"if",
"unit",
"==",
"'bytes'",
":",
"extension",
"=",
"'B'",
"else",
":",
"# if it's not bytes, it's bits",
"extension",
"=",
"'Bit'",
"for",
"dimension",
"in",
"(",
"unit",
",",
"'K'"... | 31.294118 | 11.176471 |
def set(self, oid, typevalue):
"""
Call the default or user setter function if available
"""
success = False
type_ = typevalue.split()[0]
value = typevalue.lstrip(type_).strip().strip('"')
ret_value = self.get_setter(oid)(oid, type_, value)
if ret_value:
if ret_value in ErrorValues or ret_value == '... | [
"def",
"set",
"(",
"self",
",",
"oid",
",",
"typevalue",
")",
":",
"success",
"=",
"False",
"type_",
"=",
"typevalue",
".",
"split",
"(",
")",
"[",
"0",
"]",
"value",
"=",
"typevalue",
".",
"lstrip",
"(",
"type_",
")",
".",
"strip",
"(",
")",
"."... | 28.578947 | 16.157895 |
def subscribe(self, topic, qos):
"""Subscribe to some topic."""
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN
self.logger.info("SUBSCRIBE: %s", topic)
return self.send_subscribe(False, [(utf8encode(topic), qos)]) | [
"def",
"subscribe",
"(",
"self",
",",
"topic",
",",
"qos",
")",
":",
"if",
"self",
".",
"sock",
"==",
"NC",
".",
"INVALID_SOCKET",
":",
"return",
"NC",
".",
"ERR_NO_CONN",
"self",
".",
"logger",
".",
"info",
"(",
"\"SUBSCRIBE: %s\"",
",",
"topic",
")",... | 38.571429 | 12.285714 |
def parse_entry(self, soup):
"""
Given:
soup: a bs4 element containing a row from the current media list
Return a tuple:
(media object, dict of this row's parseable attributes)
"""
# parse the media object first.
media_attrs = self.parse_entry_media_attributes(soup)
medi... | [
"def",
"parse_entry",
"(",
"self",
",",
"soup",
")",
":",
"# parse the media object first.",
"media_attrs",
"=",
"self",
".",
"parse_entry_media_attributes",
"(",
"soup",
")",
"media_id",
"=",
"media_attrs",
"[",
"u'id'",
"]",
"del",
"media_attrs",
"[",
"u'id'",
... | 30.150943 | 25.132075 |
def check_config_options(_class, required_options, optional_options, options):
"""Helper method to check options.
Arguments:
_class -- the original class that takes received the options.
required_options -- the options that are required. If they are not
present, a Conf... | [
"def",
"check_config_options",
"(",
"_class",
",",
"required_options",
",",
"optional_options",
",",
"options",
")",
":",
"for",
"opt",
"in",
"required_options",
":",
"if",
"opt",
"not",
"in",
"options",
":",
"msg",
"=",
"\"Required option missing: {0}\"",
"raise"... | 43 | 21.269231 |
def sigma_fltr(dem, n=3):
"""sigma * factor filter
Useful for outlier removal
These are min/max percentile ranges for different sigma values:
1: 15.865, 84.135
2: 2.275, 97.725
3: 0.135, 99.865
"""
std = dem.std()
u = dem.mean()
print('Excluding values outside of range: {1:... | [
"def",
"sigma_fltr",
"(",
"dem",
",",
"n",
"=",
"3",
")",
":",
"std",
"=",
"dem",
".",
"std",
"(",
")",
"u",
"=",
"dem",
".",
"mean",
"(",
")",
"print",
"(",
"'Excluding values outside of range: {1:0.2f} +/- {0}*{2:0.2f}'",
".",
"format",
"(",
"n",
",",
... | 27.25 | 19.6875 |
def clone_data(self, data_path):
"""
Clones data for given data_path:
:param str data_path: Git url (git/http/https) or local directory path
"""
self.data_path = data_path
data_url = urlparse.urlparse(self.data_path)
if data_url.scheme in SCHEMES or (data_url.sch... | [
"def",
"clone_data",
"(",
"self",
",",
"data_path",
")",
":",
"self",
".",
"data_path",
"=",
"data_path",
"data_url",
"=",
"urlparse",
".",
"urlparse",
"(",
"self",
".",
"data_path",
")",
"if",
"data_url",
".",
"scheme",
"in",
"SCHEMES",
"or",
"(",
"data... | 54.225 | 27 |
def find_all(self, cls):
"""Required functionality."""
final_results = []
table = self.get_class_table(cls)
for db_result in table.scan():
obj = cls.from_data(db_result['value'])
final_results.append(obj)
return final_results | [
"def",
"find_all",
"(",
"self",
",",
"cls",
")",
":",
"final_results",
"=",
"[",
"]",
"table",
"=",
"self",
".",
"get_class_table",
"(",
"cls",
")",
"for",
"db_result",
"in",
"table",
".",
"scan",
"(",
")",
":",
"obj",
"=",
"cls",
".",
"from_data",
... | 31.333333 | 11 |
def _tup_and_byte(obj):
""" wat """
# if this is a unicode string, return its string representation
if isinstance(obj, unicode):
return obj.encode('utf-8')
# if this is a list of values, return list of byteified values
if isinstance(obj, list):
return [_tup_and_byte(item) for item i... | [
"def",
"_tup_and_byte",
"(",
"obj",
")",
":",
"# if this is a unicode string, return its string representation",
"if",
"isinstance",
"(",
"obj",
",",
"unicode",
")",
":",
"return",
"obj",
".",
"encode",
"(",
"'utf-8'",
")",
"# if this is a list of values, return list of b... | 34.391304 | 20.434783 |
def stage_pywbem_result(self, ret, exc):
"""
Log result return or exception parameter. This method provides varied
type of formatting based on the detail_level parameter and the
data in ret.
"""
def format_result(ret, max_len):
""" format ret as repr while cli... | [
"def",
"stage_pywbem_result",
"(",
"self",
",",
"ret",
",",
"exc",
")",
":",
"def",
"format_result",
"(",
"ret",
",",
"max_len",
")",
":",
"\"\"\" format ret as repr while clipping it to max_len if\n max_len is not None.\n \"\"\"",
"# Format the 'summa... | 41.415094 | 16.745283 |
def predict(self, n_periods=10, exogenous=None,
return_conf_int=False, alpha=0.05, **kwargs):
"""Forecast future (transformed) values
Generate predictions (forecasts) ``n_periods`` in the future.
Note that if ``exogenous`` variables were used in the model fit, they
will ... | [
"def",
"predict",
"(",
"self",
",",
"n_periods",
"=",
"10",
",",
"exogenous",
"=",
"None",
",",
"return_conf_int",
"=",
"False",
",",
"alpha",
"=",
"0.05",
",",
"*",
"*",
"kwargs",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"\"steps_\"",
")",
"# Pu... | 45.789474 | 24.578947 |
def new_autorow(self, row=None):
"""
Sets the auto-add row. If row=None, increments by 1
"""
if row==None: self._auto_row += 1
else: self._auto_row = row
self._auto_column=0
return self | [
"def",
"new_autorow",
"(",
"self",
",",
"row",
"=",
"None",
")",
":",
"if",
"row",
"==",
"None",
":",
"self",
".",
"_auto_row",
"+=",
"1",
"else",
":",
"self",
".",
"_auto_row",
"=",
"row",
"self",
".",
"_auto_column",
"=",
"0",
"return",
"self"
] | 26.888889 | 11.555556 |
def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs):
'''
Execute a single state orchestration routine
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run state.orchestrate_high '{
stage_one:
{salt.state: [{tgt: "db*"}, {... | [
"def",
"orchestrate_high",
"(",
"data",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"pillar",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"pillar",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"pillar",
",",
"dict",
... | 30.676471 | 21.029412 |
def get_discrete_grid(self):
"""
Computes a Numpy array with the grid of points that results after crossing the possible outputs of the discrete
variables
"""
sets_grid = []
for d in self.space:
if d.type == 'discrete':
sets_grid.extend([d.doma... | [
"def",
"get_discrete_grid",
"(",
"self",
")",
":",
"sets_grid",
"=",
"[",
"]",
"for",
"d",
"in",
"self",
".",
"space",
":",
"if",
"d",
".",
"type",
"==",
"'discrete'",
":",
"sets_grid",
".",
"extend",
"(",
"[",
"d",
".",
"domain",
"]",
"*",
"d",
... | 39.3 | 18.9 |
def get_match_history(start_at_match_id=None, player_name=None, hero_id=None,
skill=0, date_min=None, date_max=None, account_id=None,
league_id=None, matches_requested=None, game_mode=None,
min_players=None, tournament_games_only=None,
... | [
"def",
"get_match_history",
"(",
"start_at_match_id",
"=",
"None",
",",
"player_name",
"=",
"None",
",",
"hero_id",
"=",
"None",
",",
"skill",
"=",
"0",
",",
"date_min",
"=",
"None",
",",
"date_max",
"=",
"None",
",",
"account_id",
"=",
"None",
",",
"lea... | 36.12 | 17.64 |
def send_command(self, command: str, *args, **kwargs):
"""
For request bot to perform some action
"""
info = 'send command `%s` to bot. Args: %s | Kwargs: %s'
self._messaging_logger.command.info(info, command, args, kwargs)
command = command.encode('utf8')
# targ... | [
"def",
"send_command",
"(",
"self",
",",
"command",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"info",
"=",
"'send command `%s` to bot. Args: %s | Kwargs: %s'",
"self",
".",
"_messaging_logger",
".",
"command",
".",
"info",
"(",
"info",
... | 41.052632 | 16 |
def __trim_outputspeech(self, speech_output=None):
# type: (Union[str, None]) -> str
"""Trims the output speech if it already has the
<speak></speak> tag.
:param speech_output: the output speech sent back to user.
:type speech_output: str
:return: the trimmed output spee... | [
"def",
"__trim_outputspeech",
"(",
"self",
",",
"speech_output",
"=",
"None",
")",
":",
"# type: (Union[str, None]) -> str",
"if",
"speech_output",
"is",
"None",
":",
"return",
"\"\"",
"speech",
"=",
"speech_output",
".",
"strip",
"(",
")",
"if",
"speech",
".",
... | 36.5 | 11.6875 |
def _lex_fortran(self, match, ctx=None):
"""Lex a line just as free form fortran without line break."""
lexer = FortranLexer()
text = match.group(0) + "\n"
for index, token, value in lexer.get_tokens_unprocessed(text):
value = value.replace('\n', '')
if value != '... | [
"def",
"_lex_fortran",
"(",
"self",
",",
"match",
",",
"ctx",
"=",
"None",
")",
":",
"lexer",
"=",
"FortranLexer",
"(",
")",
"text",
"=",
"match",
".",
"group",
"(",
"0",
")",
"+",
"\"\\n\"",
"for",
"index",
",",
"token",
",",
"value",
"in",
"lexer... | 44.625 | 7.625 |
def predict(self,
data,
param_list=None,
return_long_probs=True,
choice_col=None,
num_draws=None,
seed=None):
"""
Parameters
----------
data : string or pandas dataframe.
If string... | [
"def",
"predict",
"(",
"self",
",",
"data",
",",
"param_list",
"=",
"None",
",",
"return_long_probs",
"=",
"True",
",",
"choice_col",
"=",
"None",
",",
"num_draws",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"# Get the dataframe of observations we'll be ... | 51.298969 | 22.597938 |
def _mkanchors(ws, hs, x_ctr, y_ctr):
"""
Given a vector of widths (ws) and heights (hs) around a center
(x_ctr, y_ctr), output a set of anchors (windows).
"""
ws = ws[:, np.newaxis]
hs = hs[:, np.newaxis]
anchors = np.hstack((x_ctr - 0.5 * (ws - 1),
... | [
"def",
"_mkanchors",
"(",
"ws",
",",
"hs",
",",
"x_ctr",
",",
"y_ctr",
")",
":",
"ws",
"=",
"ws",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"hs",
"=",
"hs",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"anchors",
"=",
"np",
".",
"hstack",
"(",
... | 39.833333 | 11.5 |
def create(
project: 'projects.Project',
include_path: str
) -> COMPONENT:
"""
Creates a COMPONENT instance for the project component specified by the
include path
:param project:
The project in which the component resides
:param include_path:
The relative path withi... | [
"def",
"create",
"(",
"project",
":",
"'projects.Project'",
",",
"include_path",
":",
"str",
")",
"->",
"COMPONENT",
":",
"source_path",
"=",
"environ",
".",
"paths",
".",
"clean",
"(",
"os",
".",
"path",
".",
"join",
"(",
"project",
".",
"source_directory... | 29.075 | 20.225 |
def list_sig_ok(self, signature: str):
"""
return if a signature is indeed a list and all objects are intact
:param signature:
:return:
"""
list_filename = self.get_list_filename(signature)
if list_filename not in self.name_cache:
return False
... | [
"def",
"list_sig_ok",
"(",
"self",
",",
"signature",
":",
"str",
")",
":",
"list_filename",
"=",
"self",
".",
"get_list_filename",
"(",
"signature",
")",
"if",
"list_filename",
"not",
"in",
"self",
".",
"name_cache",
":",
"return",
"False",
"for",
"_object_n... | 36.076923 | 14.384615 |
def delete_editor(userid):
"""
:param userid: a string representing the user's UW NetID
:return: True if request is successful, False otherwise.
raise DataFailureException or a corresponding TrumbaException
if the request failed or an error code has been returned.
"""
url = _make_del_account... | [
"def",
"delete_editor",
"(",
"userid",
")",
":",
"url",
"=",
"_make_del_account_url",
"(",
"userid",
")",
"return",
"_process_resp",
"(",
"url",
",",
"get_sea_resource",
"(",
"url",
")",
",",
"_is_editor_deleted",
")"
] | 39.166667 | 11.333333 |
def expect(self, f, *args):
"""Like 'accept' but throws a parse error if 'f' doesn't match."""
match = self.accept(f, *args)
if match:
return match
try:
func_name = f.func_name
except AttributeError:
func_name = "<unnamed grammar function>"
... | [
"def",
"expect",
"(",
"self",
",",
"f",
",",
"*",
"args",
")",
":",
"match",
"=",
"self",
".",
"accept",
"(",
"f",
",",
"*",
"args",
")",
"if",
"match",
":",
"return",
"match",
"try",
":",
"func_name",
"=",
"f",
".",
"func_name",
"except",
"Attri... | 34.133333 | 15.733333 |
def remove(self, func):
"""Remove any provisioned log sink if auto created"""
if not self.data['name'].startswith(self.prefix):
return
parent = self.get_parent(self.get_log())
_, sink_path, _ = self.get_sink()
client = self.session.client(
'logging', 'v2',... | [
"def",
"remove",
"(",
"self",
",",
"func",
")",
":",
"if",
"not",
"self",
".",
"data",
"[",
"'name'",
"]",
".",
"startswith",
"(",
"self",
".",
"prefix",
")",
":",
"return",
"parent",
"=",
"self",
".",
"get_parent",
"(",
"self",
".",
"get_log",
"("... | 38.357143 | 12.285714 |
def _collect_conflicts_within(
context, # type: ValidationContext
conflicts, # type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], L... | [
"def",
"_collect_conflicts_within",
"(",
"context",
",",
"# type: ValidationContext",
"conflicts",
",",
"# type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]",
"cached_fields_and_fragment_names",
",",
"# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, Gr... | 50.96875 | 23.40625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.