text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def bootstrap(name, user=None, silent=True):
'''
Bootstraps a node.js application.
Will execute 'npm install --json' on the specified directory.
user
The user to run NPM with
.. versionadded:: 0.17.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
i... | [
"def",
"bootstrap",
"(",
"name",
",",
"user",
"=",
"None",
",",
"silent",
"=",
"True",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"__opt... | 34.352941 | 0.00222 |
def read_property_from_xml(root, path):
"""
Get the text from an XML property.
Whitespaces, tabs and new lines are trimmed
:param root: container in which we search
:type root: ElementTree.Element
:param path: path to search in root
:type path: str
:return: the text of the element at t... | [
"def",
"read_property_from_xml",
"(",
"root",
",",
"path",
")",
":",
"element",
"=",
"root",
".",
"find",
"(",
"path",
",",
"XML_NS",
")",
"try",
":",
"return",
"element",
".",
"text",
".",
"strip",
"(",
"' \\t\\n\\r'",
")",
"except",
"AttributeError",
"... | 26.944444 | 0.001992 |
def get_group_policy(self, group_name, policy_name):
"""
Retrieves the specified policy document for the specified group.
:type group_name: string
:param group_name: The name of the group the policy is associated with.
:type policy_name: string
:param policy_name: The p... | [
"def",
"get_group_policy",
"(",
"self",
",",
"group_name",
",",
"policy_name",
")",
":",
"params",
"=",
"{",
"'GroupName'",
":",
"group_name",
",",
"'PolicyName'",
":",
"policy_name",
"}",
"return",
"self",
".",
"get_response",
"(",
"'GetGroupPolicy'",
",",
"p... | 36.571429 | 0.009524 |
def plot_rebit_modelparams(modelparams, rebit_axes=REBIT_AXES, **kwargs):
"""
Given model parameters representing rebits, plots the
rebit states as a scatter plot. Additional keyword arguments
are passed to :ref:`plt.scatter`.
:param np.ndarray modelparams: Model parameters representing
reb... | [
"def",
"plot_rebit_modelparams",
"(",
"modelparams",
",",
"rebit_axes",
"=",
"REBIT_AXES",
",",
"*",
"*",
"kwargs",
")",
":",
"mps",
"=",
"modelparams",
"[",
":",
",",
"rebit_axes",
"]",
"*",
"np",
".",
"sqrt",
"(",
"2",
")",
"plt",
".",
"scatter",
"("... | 39.692308 | 0.001894 |
def semimajor(P,mstar=1):
"""Returns semimajor axis in AU given P in days, mstar in solar masses.
"""
return ((P*DAY/2/np.pi)**2*G*mstar*MSUN)**(1./3)/AU | [
"def",
"semimajor",
"(",
"P",
",",
"mstar",
"=",
"1",
")",
":",
"return",
"(",
"(",
"P",
"*",
"DAY",
"/",
"2",
"/",
"np",
".",
"pi",
")",
"**",
"2",
"*",
"G",
"*",
"mstar",
"*",
"MSUN",
")",
"**",
"(",
"1.",
"/",
"3",
")",
"/",
"AU"
] | 40.5 | 0.012121 |
def save_cards(cards, filename=None):
"""
Save the given cards, in plain text, to a txt file.
:arg cards:
The cards to save. Can be a ``Stack``, ``Deck``, or ``list``.
:arg str filename:
The filename to use for the cards file. If no filename given,
defaults to "cards-YYYYMMDD.tx... | [
"def",
"save_cards",
"(",
"cards",
",",
"filename",
"=",
"None",
")",
":",
"filename",
"=",
"filename",
"or",
"\"cards-%s.txt\"",
"%",
"(",
"time",
".",
"strftime",
"(",
"\"%Y%m%d\"",
")",
")",
"with",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
... | 37.526316 | 0.001368 |
def auth_as(self, user):
"""auth as a user temporarily"""
old_user = self._user
self.auth(user)
try:
yield
finally:
self.auth(old_user) | [
"def",
"auth_as",
"(",
"self",
",",
"user",
")",
":",
"old_user",
"=",
"self",
".",
"_user",
"self",
".",
"auth",
"(",
"user",
")",
"try",
":",
"yield",
"finally",
":",
"self",
".",
"auth",
"(",
"old_user",
")"
] | 24 | 0.01005 |
def execute(self, command, *args, encoding=_NOTSET):
"""Executes redis command and returns Future waiting for the answer.
Raises:
* TypeError if any of args can not be encoded as bytes.
* ReplyError on redis '-ERR' responses.
* ProtocolError when response can not be decoded mean... | [
"def",
"execute",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"encoding",
"=",
"_NOTSET",
")",
":",
"if",
"self",
".",
"_reader",
"is",
"None",
"or",
"self",
".",
"_reader",
".",
"at_eof",
"(",
")",
":",
"msg",
"=",
"self",
".",
"_close_msg... | 43.021739 | 0.000988 |
def is_status_temporarily_current(self):
"""
A status is temporarily current when the subscription is canceled with the ``at_period_end`` flag.
The subscription is still active, but is technically canceled and we're just waiting for it to run out.
You could use this method to give customers limited service aft... | [
"def",
"is_status_temporarily_current",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"canceled_at",
"and",
"self",
".",
"start",
"<",
"self",
".",
"canceled_at",
"and",
"self",
".",
"cancel_at_period_end",
")"
] | 46.153846 | 0.027778 |
def projects(self, task, params={}, **options):
"""Returns a compact representation of all of the projects the task is in.
Parameters
----------
task : {Id} The task to get projects on.
[params] : {Object} Parameters for the request
"""
path = "/tasks/%s/project... | [
"def",
"projects",
"(",
"self",
",",
"task",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/tasks/%s/projects\"",
"%",
"(",
"task",
")",
"return",
"self",
".",
"client",
".",
"get_collection",
"(",
"path",
",",
"pa... | 38.9 | 0.01005 |
def parse_meta(meta):
"""
Parse metadata of API
Args:
meta: metadata of API
Returns:
tuple(url_prefix, auth_header, resources)
"""
resources = {}
for name in meta:
if name.startswith("$"):
continue
resources[name] = resource = {}
for actio... | [
"def",
"parse_meta",
"(",
"meta",
")",
":",
"resources",
"=",
"{",
"}",
"for",
"name",
"in",
"meta",
":",
"if",
"name",
".",
"startswith",
"(",
"\"$\"",
")",
":",
"continue",
"resources",
"[",
"name",
"]",
"=",
"resource",
"=",
"{",
"}",
"for",
"ac... | 27.791667 | 0.001449 |
def getsuffix(subject):
"""
Returns the suffix of a filename. If the file has no suffix, returns None.
Can return an empty string if the filenam ends with a period.
"""
index = subject.rfind('.')
if index > subject.replace('\\', '/').rfind('/'):
return subject[index+1:]
return None | [
"def",
"getsuffix",
"(",
"subject",
")",
":",
"index",
"=",
"subject",
".",
"rfind",
"(",
"'.'",
")",
"if",
"index",
">",
"subject",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
".",
"rfind",
"(",
"'/'",
")",
":",
"return",
"subject",
"[",
"inde... | 29.2 | 0.016611 |
def create_temp_file(self, suffix, content):
"""
Creates file, because environment variables are by default escaped it
encodes and then decodes them before write so \n etc. work correctly.
"""
temp = tempfile.NamedTemporaryFile(suffix=suffix)
temp.write(content.encode('l... | [
"def",
"create_temp_file",
"(",
"self",
",",
"suffix",
",",
"content",
")",
":",
"temp",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"suffix",
")",
"temp",
".",
"write",
"(",
"content",
".",
"encode",
"(",
"'latin1'",
")",
".",
"decod... | 48.333333 | 0.011287 |
def rule_update(self, rule_id, rule):
"""Update the rule. """
if rule_id not in self.rules:
LOG.error("Rule ID not present %s", rule_id)
return
self.rules[rule_id].update(rule) | [
"def",
"rule_update",
"(",
"self",
",",
"rule_id",
",",
"rule",
")",
":",
"if",
"rule_id",
"not",
"in",
"self",
".",
"rules",
":",
"LOG",
".",
"error",
"(",
"\"Rule ID not present %s\"",
",",
"rule_id",
")",
"return",
"self",
".",
"rules",
"[",
"rule_id"... | 36.5 | 0.008929 |
def _filterSearchPhenotypesRequest(self, request):
"""
Filters request for phenotype search requests
"""
filters = []
if request.id:
filters.append("?phenotype = <{}>".format(request.id))
if request.description:
filters.append(
're... | [
"def",
"_filterSearchPhenotypesRequest",
"(",
"self",
",",
"request",
")",
":",
"filters",
"=",
"[",
"]",
"if",
"request",
".",
"id",
":",
"filters",
".",
"append",
"(",
"\"?phenotype = <{}>\"",
".",
"format",
"(",
"request",
".",
"id",
")",
")",
"if",
"... | 42.413793 | 0.00159 |
def create_block_storage(kwargs=None, call=None):
'''
Create a block storage
'''
if call == 'action':
raise SaltCloudSystemExit(
'The create_block_storage function must be called with '
'-f or --function'
)
conn = get_conn()
# Assemble the composite bloc... | [
"def",
"create_block_storage",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_block_storage function must be called with '",
"'-f or --function'",
")",
"conn",
"=",... | 26.055556 | 0.002058 |
def build_address_distance(number=None, street=None, city=None, state=None,
zip_code=None):
"""
Construct a composite distance appropriate for matching address data. NOTE:
this utility function does not guarantee that the output composite distance
will work with a particular d... | [
"def",
"build_address_distance",
"(",
"number",
"=",
"None",
",",
"street",
"=",
"None",
",",
"city",
"=",
"None",
",",
"state",
"=",
"None",
",",
"zip_code",
"=",
"None",
")",
":",
"## Validate inputs",
"for",
"param",
"in",
"[",
"number",
",",
"street"... | 33.7 | 0.002471 |
def add_to_bashrc(self,
line,
match_regexp=None,
note=None,
loglevel=logging.DEBUG):
"""Takes care of adding a line to everyone's bashrc
(/etc/bash.bashrc).
@param line: Line to add.
@param match_regexp: See add_line_to_file(... | [
"def",
"add_to_bashrc",
"(",
"self",
",",
"line",
",",
"match_regexp",
"=",
"None",
",",
"note",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"DEBUG",
")",
":",
"shutit",
"=",
"self",
".",
"shutit",
"shutit",
".",
"handle_note",
"(",
"note",
")",... | 38.625 | 0.037895 |
def cart_modify(self, items, CartId=None, HMAC=None, **kwargs):
"""CartAdd.
:param items:
A dictionary containing the items to be added to the cart.
Or a list containing these dictionaries.
example: [{'cart_item_id': 'rt2ofih3f389nwiuhf8934z87o3f4h',
'quan... | [
"def",
"cart_modify",
"(",
"self",
",",
"items",
",",
"CartId",
"=",
"None",
",",
"HMAC",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"CartId",
"or",
"not",
"HMAC",
":",
"raise",
"CartException",
"(",
"'CartId required for CartModify call'... | 36.257143 | 0.001535 |
def list_metrics(self, limit=None, marker=None, return_next=False):
"""
Returns a list of all the metrics associated with this check.
"""
return self._metrics_manager.list(limit=limit, marker=marker,
return_next=return_next) | [
"def",
"list_metrics",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"return_next",
"=",
"False",
")",
":",
"return",
"self",
".",
"_metrics_manager",
".",
"list",
"(",
"limit",
"=",
"limit",
",",
"marker",
"=",
"marker",
","... | 44.5 | 0.011029 |
def get_all_instance_status(self, instance_ids=None,
max_results=None, next_token=None,
filters=None):
"""
Retrieve all the instances in your account scheduled for maintenance.
:type instance_ids: list
:param instance_ids: ... | [
"def",
"get_all_instance_status",
"(",
"self",
",",
"instance_ids",
"=",
"None",
",",
"max_results",
"=",
"None",
",",
"next_token",
"=",
"None",
",",
"filters",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"instance_ids",
":",
"self",
".",
"bui... | 38.756098 | 0.002455 |
def _version_less(version_a, version_b):
""" Takes two version as (major, minor, patch) tuples and returns a <= b.
"""
if version_a[0] > version_b[0]:
return False
elif version_a[0] < version_b[0]:
return True
else:
if version_a[1] > version_b[1]:
return False
... | [
"def",
"_version_less",
"(",
"version_a",
",",
"version_b",
")",
":",
"if",
"version_a",
"[",
"0",
"]",
">",
"version_b",
"[",
"0",
"]",
":",
"return",
"False",
"elif",
"version_a",
"[",
"0",
"]",
"<",
"version_b",
"[",
"0",
"]",
":",
"return",
"True... | 30.714286 | 0.002257 |
def add_moc_from_URL(self, moc_URL, moc_options = {}):
""" load a MOC from a URL and display it in Aladin Lite widget
Arguments:
moc_URL: string url
moc_options: dictionary object"""
self.moc_URL = moc_URL
self.moc_options = moc_options
self.moc_from_U... | [
"def",
"add_moc_from_URL",
"(",
"self",
",",
"moc_URL",
",",
"moc_options",
"=",
"{",
"}",
")",
":",
"self",
".",
"moc_URL",
"=",
"moc_URL",
"self",
".",
"moc_options",
"=",
"moc_options",
"self",
".",
"moc_from_URL_flag",
"=",
"not",
"self",
".",
"moc_fro... | 43.625 | 0.011236 |
def lookup(img, **kwargs):
"""Assign values to channels based on a table."""
luts = np.array(kwargs['luts'], dtype=np.float32) / 255.0
def func(band_data, luts=luts, index=-1):
# NaN/null values will become 0
lut = luts[:, index] if len(luts.shape) == 2 else luts
band_data = band_da... | [
"def",
"lookup",
"(",
"img",
",",
"*",
"*",
"kwargs",
")",
":",
"luts",
"=",
"np",
".",
"array",
"(",
"kwargs",
"[",
"'luts'",
"]",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"/",
"255.0",
"def",
"func",
"(",
"band_data",
",",
"luts",
"=",
"... | 42.466667 | 0.001536 |
def convolve(image, pixel_filter, channels=3, name=None):
"""Perform a 2D pixel convolution on the given image.
Arguments:
image: A 3D `float32` `Tensor` of shape `[height, width, channels]`,
where `channels` is the third argument to this function and the
first two dimensions are arbitrary.
pix... | [
"def",
"convolve",
"(",
"image",
",",
"pixel_filter",
",",
"channels",
"=",
"3",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"'convolve'",
")",
":",
"tf",
".",
"compat",
".",
"v1",
".",
"assert_type",
"(",
... | 46.413793 | 0.002183 |
def get_functarguments(func):
"""
Recupera gli argomenti dalla funzione stessa.
"""
argspec = inspect.getargspec(func)
if argspec.defaults is not None:
args = argspec.args[:-len(argspec.defaults)]
kwargs = dict(
zip(argspec.args[-len(argspec.defaults):], argspec.defaults)... | [
"def",
"get_functarguments",
"(",
"func",
")",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"if",
"argspec",
".",
"defaults",
"is",
"not",
"None",
":",
"args",
"=",
"argspec",
".",
"args",
"[",
":",
"-",
"len",
"(",
"argspec",
... | 32.52381 | 0.000711 |
def get_event(self, client, check):
"""
Returns an event for a given client & check name.
"""
data = self._request('GET', '/events/{}/{}'.format(client, check))
return data.json() | [
"def",
"get_event",
"(",
"self",
",",
"client",
",",
"check",
")",
":",
"data",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"'/events/{}/{}'",
".",
"format",
"(",
"client",
",",
"check",
")",
")",
"return",
"data",
".",
"json",
"(",
")"
] | 35.666667 | 0.009132 |
def getsize(path, bestprefix=True, system=NIST):
"""Return a bitmath instance in the best human-readable representation
of the file size at `path`. Optionally, provide a preferred unit
system by setting `system` to either `bitmath.NIST` (default) or
`bitmath.SI`.
Optionally, set ``bestprefix`` to ``False`` to get ... | [
"def",
"getsize",
"(",
"path",
",",
"bestprefix",
"=",
"True",
",",
"system",
"=",
"NIST",
")",
":",
"_path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
"size_bytes",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"_path",
")",
"if",
... | 36.066667 | 0.001802 |
def int_element(element, name, default=0):
"""
Returns the int value of an element, or a default if it's not defined
:param element: The XML Element object
:type element: etree._Element
:param name: The name of the element to evaluate
:type name: str
:param default: The default value to ... | [
"def",
"int_element",
"(",
"element",
",",
"name",
",",
"default",
"=",
"0",
")",
":",
"element_value",
"=",
"element",
".",
"find",
"(",
"name",
")",
"if",
"element_value",
"is",
"not",
"None",
":",
"try",
":",
"return",
"int",
"(",
"element_value",
"... | 26.086957 | 0.001608 |
async def _send_plain_text(self, request: Request, stack: Stack):
"""
Sends plain text using `_send_text()`.
"""
await self._send_text(request, stack, None) | [
"async",
"def",
"_send_plain_text",
"(",
"self",
",",
"request",
":",
"Request",
",",
"stack",
":",
"Stack",
")",
":",
"await",
"self",
".",
"_send_text",
"(",
"request",
",",
"stack",
",",
"None",
")"
] | 30.666667 | 0.010582 |
def vcf_to_df(canvasvcfs, exonbed, cpus):
""" Compile a number of vcf files into tsv file for easy manipulation
"""
df = pd.DataFrame()
p = Pool(processes=cpus)
results = []
args = [(x, exonbed, i) for (i, x) in enumerate(canvasvcfs)]
r = p.map_async(vcf_to_df_worker, args,
... | [
"def",
"vcf_to_df",
"(",
"canvasvcfs",
",",
"exonbed",
",",
"cpus",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"p",
"=",
"Pool",
"(",
"processes",
"=",
"cpus",
")",
"results",
"=",
"[",
"]",
"args",
"=",
"[",
"(",
"x",
",",
"exonbed",... | 30.928571 | 0.002242 |
def extra_args_from_config(cp, section, skip_args=None, dtypes=None):
"""Gets any additional keyword in the given config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
section : str
The name of the section to read.
... | [
"def",
"extra_args_from_config",
"(",
"cp",
",",
"section",
",",
"skip_args",
"=",
"None",
",",
"dtypes",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"dtypes",
"is",
"None",
":",
"dtypes",
"=",
"{",
"}",
"if",
"skip_args",
"is",
"None",
":"... | 34.578947 | 0.00148 |
def check_config_mode(self, check_string=")#", pattern=""):
"""Checks if the device is in configuration mode"""
return super(CalixB6Base, self).check_config_mode(check_string=check_string) | [
"def",
"check_config_mode",
"(",
"self",
",",
"check_string",
"=",
"\")#\"",
",",
"pattern",
"=",
"\"\"",
")",
":",
"return",
"super",
"(",
"CalixB6Base",
",",
"self",
")",
".",
"check_config_mode",
"(",
"check_string",
"=",
"check_string",
")"
] | 67.333333 | 0.014706 |
def unpack_db_to_component_dfs(self, convert_dates=False):
"""Returns the set of known tables in the adjustments file in DataFrame
form.
Parameters
----------
convert_dates : bool, optional
By default, dates are returned in seconds since EPOCH. If
convert... | [
"def",
"unpack_db_to_component_dfs",
"(",
"self",
",",
"convert_dates",
"=",
"False",
")",
":",
"return",
"{",
"t_name",
":",
"self",
".",
"get_df_from_table",
"(",
"t_name",
",",
"convert_dates",
")",
"for",
"t_name",
"in",
"self",
".",
"_datetime_int_cols",
... | 36.181818 | 0.002448 |
def submit_jobs(job_specs):
"""Submit a job
Args:
job_spec (dict): The job specifiation (see Grid'5000 API reference)
"""
gk = get_api_client()
jobs = []
try:
for site, job_spec in job_specs:
logger.info("Submitting %s on %s" % (job_spec, site))
jobs.appe... | [
"def",
"submit_jobs",
"(",
"job_specs",
")",
":",
"gk",
"=",
"get_api_client",
"(",
")",
"jobs",
"=",
"[",
"]",
"try",
":",
"for",
"site",
",",
"job_spec",
"in",
"job_specs",
":",
"logger",
".",
"info",
"(",
"\"Submitting %s on %s\"",
"%",
"(",
"job_spec... | 28.5 | 0.001698 |
def make_bound(self, for_instance):
"""
Create a new :ref:`bound field class <api-aioxmpp.forms-bound-fields>`
or return an existing one for the given form object.
:param for_instance: The form instance to which the bound field should
be bound.
If n... | [
"def",
"make_bound",
"(",
"self",
",",
"for_instance",
")",
":",
"try",
":",
"return",
"for_instance",
".",
"_descriptor_data",
"[",
"self",
"]",
"except",
"KeyError",
":",
"bound",
"=",
"self",
".",
"create_bound",
"(",
"for_instance",
")",
"for_instance",
... | 36.84 | 0.002116 |
def get_proxy_info(
hostname, is_secure, proxy_host=None, proxy_port=0, proxy_auth=None,
no_proxy=None, proxy_type='http'):
"""
try to retrieve proxy host and port from environment
if not provided in options.
result is (proxy_host, proxy_port, proxy_auth).
proxy_auth is tuple of user... | [
"def",
"get_proxy_info",
"(",
"hostname",
",",
"is_secure",
",",
"proxy_host",
"=",
"None",
",",
"proxy_port",
"=",
"0",
",",
"proxy_auth",
"=",
"None",
",",
"no_proxy",
"=",
"None",
",",
"proxy_type",
"=",
"'http'",
")",
":",
"if",
"_is_no_proxy_host",
"(... | 35.956522 | 0.000589 |
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all cir... | [
"def",
"send_head",
"(",
"self",
")",
":",
"offerredPath",
"=",
"self",
".",
"absFilePath",
"f",
"=",
"None",
"fName",
"=",
"_path",
".",
"basename",
"(",
"offerredPath",
")",
"urlPath",
"=",
"_U2",
".",
"unquote",
"(",
"self",
".",
"path",
")",
"if",
... | 32.97619 | 0.002104 |
def hook(cls, hookname=None, erase=False):
"""Attach a method to a parsing class and register it as a parser hook.
The method is registered with its name unless hookname is provided.
"""
if not hasattr(cls, '_hooks'):
raise TypeError(
"%s didn't seems to be a BasicParser subsclas... | [
"def",
"hook",
"(",
"cls",
",",
"hookname",
"=",
"None",
",",
"erase",
"=",
"False",
")",
":",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"'_hooks'",
")",
":",
"raise",
"TypeError",
"(",
"\"%s didn't seems to be a BasicParser subsclasse\"",
"%",
"cls",
".",
... | 38.043478 | 0.00223 |
def getJsonFromApi(view, request):
"""Return json from querying Web Api
Args:
view: django view function.
request: http request object got from django.
Returns: json format dictionary
"""
jsonText = view(request)
jsonText = json.loads(jsonText.content.decode('utf-8'))
return jsonText | [
"def",
"getJsonFromApi",
"(",
"view",
",",
"request",
")",
":",
"jsonText",
"=",
"view",
"(",
"request",
")",
"jsonText",
"=",
"json",
".",
"loads",
"(",
"jsonText",
".",
"content",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"return",
"jsonText"
] | 24.583333 | 0.039216 |
def AddArguments(cls, argument_group):
"""Adds command line arguments the helper supports to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argparse._ArgumentGroup|arg... | [
"def",
"AddArguments",
"(",
"cls",
",",
"argument_group",
")",
":",
"argument_group",
".",
"add_argument",
"(",
"'--name'",
",",
"'--timeline_name'",
",",
"'--timeline-name'",
",",
"dest",
"=",
"'timeline_name'",
",",
"type",
"=",
"str",
",",
"action",
"=",
"'... | 43.475 | 0.000562 |
def main():
"""
NAME
vector_mean.py
DESCRIPTION
calculates vector mean of vector data
INPUT FORMAT
takes dec, inc, int from an input file
SYNTAX
vector_mean.py [command line options] [< filename]
OPTIONS
-h prints help message and quits
-f FILE, s... | [
"def",
"main",
"(",
")",
":",
"if",
"'-h'",
"in",
"sys",
".",
"argv",
":",
"# check if help is needed",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"# graceful quit",
"if",
"'-f'",
"in",
"sys",
".",
"argv",
":",
"dat",
"=... | 24.347826 | 0.016309 |
def work():
"""Implement a worker for write-math.com."""
global n
cmd = utils.get_project_configuration()
if 'worker_api_key' not in cmd:
return ("You need to define a 'worker_api_key' in your ~/")
chunk_size = 1000
logging.info("Start working with n=%i", n)
for _ in range(chunk_s... | [
"def",
"work",
"(",
")",
":",
"global",
"n",
"cmd",
"=",
"utils",
".",
"get_project_configuration",
"(",
")",
"if",
"'worker_api_key'",
"not",
"in",
"cmd",
":",
"return",
"(",
"\"You need to define a 'worker_api_key' in your ~/\"",
")",
"chunk_size",
"=",
"1000",
... | 37.424658 | 0.000357 |
async def main():
"""
Main code
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
# Get the node summary infos to test the connection
response = await client(bma.node.summary)
print(response)
# prompt hidden user entry
salt = getpass.getp... | [
"async",
"def",
"main",
"(",
")",
":",
"# Create Client from endpoint string in Duniter format",
"client",
"=",
"Client",
"(",
"BMAS_ENDPOINT",
")",
"# Get the node summary infos to test the connection",
"response",
"=",
"await",
"client",
"(",
"bma",
".",
"node",
".",
... | 28.415094 | 0.001926 |
def visit_tree(node, previsit, postvisit):
"""
Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion
via the function call stack to avoid hitting 'maximum recursion depth exceeded' error.
It calls ``previsit()`` and ``postvisit()`` as follows:
* ``previsit(node, par... | [
"def",
"visit_tree",
"(",
"node",
",",
"previsit",
",",
"postvisit",
")",
":",
"if",
"not",
"previsit",
":",
"previsit",
"=",
"lambda",
"node",
",",
"pvalue",
":",
"(",
"None",
",",
"None",
")",
"if",
"not",
"postvisit",
":",
"postvisit",
"=",
"lambda"... | 40.261905 | 0.016166 |
def to_neo4j(graph, neo_connection, use_tqdm=False):
"""Upload a BEL graph to a Neo4j graph database using :mod:`py2neo`.
:param pybel.BELGraph graph: A BEL Graph
:param neo_connection: A :mod:`py2neo` connection object. Refer to the
`py2neo documentation <http://py2neo.org/v3/database.html#the-graph>... | [
"def",
"to_neo4j",
"(",
"graph",
",",
"neo_connection",
",",
"use_tqdm",
"=",
"False",
")",
":",
"import",
"py2neo",
"if",
"isinstance",
"(",
"neo_connection",
",",
"str",
")",
":",
"neo_connection",
"=",
"py2neo",
".",
"Graph",
"(",
"neo_connection",
")",
... | 30.8 | 0.002359 |
def shorthand(self):
"""Return the 6-tuple (a,b,c,d,e,f) that describes this matrix"""
return (self.a, self.b, self.c, self.d, self.e, self.f) | [
"def",
"shorthand",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"a",
",",
"self",
".",
"b",
",",
"self",
".",
"c",
",",
"self",
".",
"d",
",",
"self",
".",
"e",
",",
"self",
".",
"f",
")"
] | 52 | 0.012658 |
def _layer_to_path_gen(layer):
"""Generates an SVG path from a given layer.
Args:
layer (layer): the layer to convert
Yields:
str: the next component of the path
"""
draw = False
for x, y in zip(*layer):
if np.isnan(x) or np.isnan(y):
draw = False
el... | [
"def",
"_layer_to_path_gen",
"(",
"layer",
")",
":",
"draw",
"=",
"False",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"*",
"layer",
")",
":",
"if",
"np",
".",
"isnan",
"(",
"x",
")",
"or",
"np",
".",
"isnan",
"(",
"y",
")",
":",
"draw",
"=",
"Fa... | 24.166667 | 0.002212 |
def split_dmap_overlay(obj, depth=0):
"""
Splits a DynamicMap into the original component layers it was
constructed from by traversing the graph to search for dynamically
overlaid components (i.e. constructed by using * on a DynamicMap).
Useful for assigning subplots of an OverlayPlot the streams th... | [
"def",
"split_dmap_overlay",
"(",
"obj",
",",
"depth",
"=",
"0",
")",
":",
"layers",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"obj",
",",
"DynamicMap",
")",
":",
"if",
"issubclass",
"(",
"obj",
".",
"type",
",",
"NdOverlay",
")",
"and",
"not",
"depth"... | 37.677419 | 0.000835 |
def make_code_from_pyc(filename):
"""Get a code object from a .pyc file."""
try:
fpyc = open(filename, "rb")
except IOError:
raise NoCode("No file to run: %r" % filename)
try:
# First four bytes are a version-specific magic number. It has to
# match or we won't run the ... | [
"def",
"make_code_from_pyc",
"(",
"filename",
")",
":",
"try",
":",
"fpyc",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"except",
"IOError",
":",
"raise",
"NoCode",
"(",
"\"No file to run: %r\"",
"%",
"filename",
")",
"try",
":",
"# First four bytes are ... | 31.230769 | 0.001195 |
def set_boundaries(self, feature_id, start, end, organism=None, sequence=None):
"""
Set the boundaries of a genomic feature
:type feature_id: str
:param feature_id: Feature UUID
:type start: int
:param start: Feature start
:type end: int
:param end: Fea... | [
"def",
"set_boundaries",
"(",
"self",
",",
"feature_id",
",",
"start",
",",
"end",
",",
"organism",
"=",
"None",
",",
"sequence",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'features'",
":",
"[",
"{",
"'uniquename'",
":",
"feature_id",
",",
"'location'",
... | 26.818182 | 0.002181 |
def extract_from_directory(path_in, path_out):
"""Run Eidos on a set of text files in a folder.
The output is produced in the specified output folder but
the output files aren't processed by this function.
Parameters
----------
path_in : str
Path to an input folder with some text files... | [
"def",
"extract_from_directory",
"(",
"path_in",
",",
"path_out",
")",
":",
"path_in",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path_in",
")",
")",
"path_out",
"=",
"os",
".",
"path",
".",
"realpath",
"(... | 36.888889 | 0.001468 |
def _getSignature(self, readDataInstance, dataDirectoryInstance):
"""
Returns the digital signature within a digital signed PE file.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} instance containing a PE file data.
@type dataDirector... | [
"def",
"_getSignature",
"(",
"self",
",",
"readDataInstance",
",",
"dataDirectoryInstance",
")",
":",
"signature",
"=",
"\"\"",
"if",
"readDataInstance",
"is",
"not",
"None",
"and",
"dataDirectoryInstance",
"is",
"not",
"None",
":",
"securityDirectory",
"=",
"data... | 46.035714 | 0.012918 |
def simulate_timestamps_mix(self, max_rates, populations, bg_rate,
rs=None, seed=1, chunksize=2**16,
comp_filter=None, overwrite=False,
skip_existing=False, scale=10,
path=None, t_chunksize=No... | [
"def",
"simulate_timestamps_mix",
"(",
"self",
",",
"max_rates",
",",
"populations",
",",
"bg_rate",
",",
"rs",
"=",
"None",
",",
"seed",
"=",
"1",
",",
"chunksize",
"=",
"2",
"**",
"16",
",",
"comp_filter",
"=",
"None",
",",
"overwrite",
"=",
"False",
... | 49.072165 | 0.001442 |
def drop_udf(
self,
name,
input_types=None,
database=None,
force=False,
aggregate=False,
):
"""
Drops a UDF
If only name is given, this will search
for the relevant UDF and drop it.
To delete an overloaded UDF, give only a name ... | [
"def",
"drop_udf",
"(",
"self",
",",
"name",
",",
"input_types",
"=",
"None",
",",
"database",
"=",
"None",
",",
"force",
"=",
"False",
",",
"aggregate",
"=",
"False",
",",
")",
":",
"if",
"not",
"input_types",
":",
"if",
"not",
"database",
":",
"dat... | 33.140351 | 0.001542 |
def assets(ctx):
"List Assets"
MAX_ASSET = 100000
assets = []
for i in range(0, MAX_ASSET):
try:
assets.append(Asset("1.3.{}".format(i)))
except AssetDoesNotExistsException:
break
assetTable = PrettyTable()
assetTable.field_names = ["ID", "Symbol", "... | [
"def",
"assets",
"(",
"ctx",
")",
":",
"MAX_ASSET",
"=",
"100000",
"assets",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"MAX_ASSET",
")",
":",
"try",
":",
"assets",
".",
"append",
"(",
"Asset",
"(",
"\"1.3.{}\"",
".",
"format",
"(",
... | 31.478261 | 0.009383 |
def request(self, method, url, **kwargs):
"""Constructs a :class:`requests.Request`, prepares it and sends it.
Raises HTTPErrors by default.
:param method: method for the new :class:`Request` object.
:type method: :class:`str`
:param url: URL for the new :class:`Request` object.... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"oauthlib",
".",
"oauth2",
".",
"is_secure_transport",
"(",
"url",
")",
":",
"m",
"=",
"super",
"(",
"OAuthSession",
",",
"self",
")",
".",
"request",
... | 42.571429 | 0.002188 |
def unit_key_from_name(name):
"""Return a legal python name for the given name for use as a unit key."""
result = name
for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):
result = result.replace(old, new)
# Collapse redundant underscores and convert to uppercase.
result = re.sub(r'_+', '_', result.upp... | [
"def",
"unit_key_from_name",
"(",
"name",
")",
":",
"result",
"=",
"name",
"for",
"old",
",",
"new",
"in",
"six",
".",
"iteritems",
"(",
"UNIT_KEY_REPLACEMENTS",
")",
":",
"result",
"=",
"result",
".",
"replace",
"(",
"old",
",",
"new",
")",
"# Collapse ... | 30.181818 | 0.020468 |
def install(name=None,
refresh=False,
skip_verify=False,
pkgs=None,
sources=None,
downloadonly=False,
reinstall=False,
normalize=True,
update_holds=False,
saltenv='base',
ignore_epoch=False,
... | [
"def",
"install",
"(",
"name",
"=",
"None",
",",
"refresh",
"=",
"False",
",",
"skip_verify",
"=",
"False",
",",
"pkgs",
"=",
"None",
",",
"sources",
"=",
"None",
",",
"downloadonly",
"=",
"False",
",",
"reinstall",
"=",
"False",
",",
"normalize",
"=",... | 38.59325 | 0.000538 |
def fmt_sia(sia, ces=True):
"""Format a |SystemIrreducibilityAnalysis|."""
if ces:
body = (
'{ces}'
'{partitioned_ces}'.format(
ces=fmt_ces(
sia.ces,
'Cause-effect structure'),
partitioned_ces=fmt_ces(
... | [
"def",
"fmt_sia",
"(",
"sia",
",",
"ces",
"=",
"True",
")",
":",
"if",
"ces",
":",
"body",
"=",
"(",
"'{ces}'",
"'{partitioned_ces}'",
".",
"format",
"(",
"ces",
"=",
"fmt_ces",
"(",
"sia",
".",
"ces",
",",
"'Cause-effect structure'",
")",
",",
"partit... | 34.217391 | 0.001236 |
def register_hooks(func, hooks, obj):
"""Register func on obj via hooks.
Hooks should be a tuple of (name, args, kwargs) where
name is a method name of obj. If args or kwargs are not empty,
the method will be called first and expect a new function as return.
"""
for name, args, kwargs in hooks:
... | [
"def",
"register_hooks",
"(",
"func",
",",
"hooks",
",",
"obj",
")",
":",
"for",
"name",
",",
"args",
",",
"kwargs",
"in",
"hooks",
":",
"hook",
"=",
"getattr",
"(",
"obj",
",",
"name",
")",
"force_call",
"=",
"kwargs",
".",
"pop",
"(",
"\"_force_cal... | 42.916667 | 0.001901 |
def down(self):
"""
Function operates on the IMCInterface object and configures the interface into an
administratively down state and refreshes contents of self.adminstatus
:return:
"""
set_interface_down(self.ifIndex, self.auth, self.url, devip=self.ip)
self.admi... | [
"def",
"down",
"(",
"self",
")",
":",
"set_interface_down",
"(",
"self",
".",
"ifIndex",
",",
"self",
".",
"auth",
",",
"self",
".",
"url",
",",
"devip",
"=",
"self",
".",
"ip",
")",
"self",
".",
"adminstatus",
"=",
"get_interface_details",
"(",
"self"... | 47.222222 | 0.009238 |
def diff_indexes(l1,l2):
'''
from elist.elist import *
l1 = [1,2,3,5]
l2 = [0,2,3,4]
diff_indexes(l1,l2)
'''
rslt = []
for i in range(0,l1.__len__()):
if(l1[i]!=l2[i]):
rslt.append(i)
return(rslt) | [
"def",
"diff_indexes",
"(",
"l1",
",",
"l2",
")",
":",
"rslt",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"l1",
".",
"__len__",
"(",
")",
")",
":",
"if",
"(",
"l1",
"[",
"i",
"]",
"!=",
"l2",
"[",
"i",
"]",
")",
":",
"rslt",... | 21.416667 | 0.014925 |
def service_endpoint_policy_definitions(self):
"""Instance depends on the API version:
* 2018-07-01: :class:`ServiceEndpointPolicyDefinitionsOperations<azure.mgmt.network.v2018_07_01.operations.ServiceEndpointPolicyDefinitionsOperations>`
* 2018-08-01: :class:`ServiceEndpointPolicyDefinit... | [
"def",
"service_endpoint_policy_definitions",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'service_endpoint_policy_definitions'",
")",
"if",
"api_version",
"==",
"'2018-07-01'",
":",
"from",
".",
"v2018_07_01",
".",
"operations",
... | 75.428571 | 0.008419 |
def _run_configure_script(self, script):
"""Run the script to install the Juju agent on the target machine.
:param str script: The script returned by the ProvisioningScript API
:raises: :class:`paramiko.ssh_exception.AuthenticationException`
if the upload fails
"""
... | [
"def",
"_run_configure_script",
"(",
"self",
",",
"script",
")",
":",
"_",
",",
"tmpFile",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"with",
"open",
"(",
"tmpFile",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"script",
")",
"try",
":"... | 30.026316 | 0.001698 |
def _symlink_remote_lib(self, gopath, go_remote_lib, required_links):
"""Creates symlinks from the given gopath to the source files of the given remote lib.
Also duplicates directory structure leading to source files of package within
gopath, in order to provide isolation to the package.
Adds the syml... | [
"def",
"_symlink_remote_lib",
"(",
"self",
",",
"gopath",
",",
"go_remote_lib",
",",
"required_links",
")",
":",
"def",
"source_iter",
"(",
")",
":",
"remote_lib_source_dir",
"=",
"self",
".",
"context",
".",
"products",
".",
"get_data",
"(",
"'go_remote_lib_src... | 52.235294 | 0.009956 |
def generate_map_chart_file(qtl_matrix, lod_threshold,
map_chart_file='MapChart.map'):
""" This function converts our QTL matrix file into a MapChart input
file.
:arg qtl_matrix: the path to the QTL matrix file generated by
the plugin.
:arg lod_threshold: threshold u... | [
"def",
"generate_map_chart_file",
"(",
"qtl_matrix",
",",
"lod_threshold",
",",
"map_chart_file",
"=",
"'MapChart.map'",
")",
":",
"qtl_matrix",
"=",
"read_input_file",
"(",
"qtl_matrix",
",",
"sep",
"=",
"','",
")",
"tmp_dic",
"=",
"{",
"}",
"cnt",
"=",
"1",
... | 36.219048 | 0.000768 |
def setup(self, **kwargs):
"""Set up the transient state prior rendering"""
# Keep labels in case of map
if getattr(self, 'x_labels', None) is not None:
self.x_labels = list(self.x_labels)
if getattr(self, 'y_labels', None) is not None:
self.y_labels = list(self.y... | [
"def",
"setup",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Keep labels in case of map",
"if",
"getattr",
"(",
"self",
",",
"'x_labels'",
",",
"None",
")",
"is",
"not",
"None",
":",
"self",
".",
"x_labels",
"=",
"list",
"(",
"self",
".",
"x_labe... | 39.111111 | 0.001109 |
def _sorted_nicely(self, l):
"""Return list sorted in the way that humans expect.
:param l: iterable to be sorted
:returns: sorted list
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0... | [
"def",
"_sorted_nicely",
"(",
"self",
",",
"l",
")",
":",
"convert",
"=",
"lambda",
"text",
":",
"int",
"(",
"text",
")",
"if",
"text",
".",
"isdigit",
"(",
")",
"else",
"text",
"alphanum_key",
"=",
"lambda",
"key",
":",
"[",
"convert",
"(",
"c",
"... | 41.222222 | 0.029024 |
def make_legal(move, position):
"""
Converts an incomplete move (initial ``Location`` not specified)
and the corresponding position into the a complete move
with the most likely starting point specified. If no moves match, ``None``
is returned.
:type: move: Move
:type: position: Board
:... | [
"def",
"make_legal",
"(",
"move",
",",
"position",
")",
":",
"assert",
"isinstance",
"(",
"move",
",",
"Move",
")",
"for",
"legal_move",
"in",
"position",
".",
"all_possible_moves",
"(",
"move",
".",
"color",
")",
":",
"if",
"move",
".",
"status",
"==",
... | 33.043478 | 0.001279 |
def fulfill_transaction(transaction, *, private_keys):
"""Fulfills the given transaction.
Args:
transaction (dict): The transaction to be fulfilled.
private_keys (:obj:`str` | :obj:`list` | :obj:`tuple`): One or
more private keys to be used for fulfilling the
transaction... | [
"def",
"fulfill_transaction",
"(",
"transaction",
",",
"*",
",",
"private_keys",
")",
":",
"if",
"not",
"isinstance",
"(",
"private_keys",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"private_keys",
"=",
"[",
"private_keys",
"]",
"# NOTE: Needed for the tim... | 32.878788 | 0.000895 |
def make_request(self, handle, value, timeout=DEFAULT_TIMEOUT, with_response=True):
"""Write a GATT Command without callback - not utf-8."""
try:
with self:
_LOGGER.debug("Writing %s to %s with with_response=%s", codecs.encode(value, 'hex'), handle, with_response)
... | [
"def",
"make_request",
"(",
"self",
",",
"handle",
",",
"value",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
"with_response",
"=",
"True",
")",
":",
"try",
":",
"with",
"self",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Writing %s to %s with with_response=%s\"",
"... | 58.333333 | 0.008439 |
async def turn_off(self):
"""Turn off media player."""
_LOGGER.debug("turn_off while %s", self._state)
if self._state in [State.PLAYING_LIVE_TV, State.PLAYING_RECORDED_TV,
State.PLAYING_TIMESHIFT_TV, State.UNKNOWN]:
await self.send_cmd('Power')
s... | [
"async",
"def",
"turn_off",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"turn_off while %s\"",
",",
"self",
".",
"_state",
")",
"if",
"self",
".",
"_state",
"in",
"[",
"State",
".",
"PLAYING_LIVE_TV",
",",
"State",
".",
"PLAYING_RECORDED_TV",
",... | 45.25 | 0.00813 |
def start_plasma_store(stdout_file=None,
stderr_file=None,
object_store_memory=None,
plasma_directory=None,
huge_pages=False,
plasma_store_socket_name=None):
"""This method starts an object store proce... | [
"def",
"start_plasma_store",
"(",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
",",
"object_store_memory",
"=",
"None",
",",
"plasma_directory",
"=",
"None",
",",
"huge_pages",
"=",
"False",
",",
"plasma_store_socket_name",
"=",
"None",
")",
":",... | 45.354167 | 0.00045 |
def classify_pr_synced_state(pr: PullRequestDetails) -> Optional[bool]:
"""
References:
https://developer.github.com/v3/pulls/#get-a-single-pull-request
https://developer.github.com/v4/enum/mergestatestatus/
"""
state = pr.payload['mergeable_state'].lower()
classification = {
... | [
"def",
"classify_pr_synced_state",
"(",
"pr",
":",
"PullRequestDetails",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"state",
"=",
"pr",
".",
"payload",
"[",
"'mergeable_state'",
"]",
".",
"lower",
"(",
")",
"classification",
"=",
"{",
"'behind'",
":",
"... | 33.166667 | 0.002445 |
def setColumnTypeText( self, columnTypeText ):
"""
Sets the column type for this widget based on the inputed text.
:param columnTypeText | <str>
"""
if ( not ColumnType ):
return False
try:
columnType = ColumnType[n... | [
"def",
"setColumnTypeText",
"(",
"self",
",",
"columnTypeText",
")",
":",
"if",
"(",
"not",
"ColumnType",
")",
":",
"return",
"False",
"try",
":",
"columnType",
"=",
"ColumnType",
"[",
"nativestring",
"(",
"columnTypeText",
")",
"]",
"except",
"KeyError",
":... | 29.533333 | 0.019694 |
def _get_grammar_errors(self,pos,text,tokens):
"""
Internal function to get the number of grammar errors in given text
pos - part of speech tagged text (list)
text - normal text (list)
tokens - list of lists of tokenized text
"""
word_counts = [max(len(t),1) for t... | [
"def",
"_get_grammar_errors",
"(",
"self",
",",
"pos",
",",
"text",
",",
"tokens",
")",
":",
"word_counts",
"=",
"[",
"max",
"(",
"len",
"(",
"t",
")",
",",
"1",
")",
"for",
"t",
"in",
"tokens",
"]",
"good_pos_tags",
"=",
"[",
"]",
"min_pos_seq",
"... | 48.820513 | 0.014418 |
def _do_subread_set(flag,input_file,of,negative_filter,aligned):
best = {}
cmd = 'samtools view '+flag+' '+input_file
sys.stderr.write(cmd+"\n")
p = Popen(cmd.split(),stdout=PIPE)
z = 0
for line in p.stdout:
z += 1
if z%10000==0: sys.stderr.write(str(z) + " subread alignment paths sc... | [
"def",
"_do_subread_set",
"(",
"flag",
",",
"input_file",
",",
"of",
",",
"negative_filter",
",",
"aligned",
")",
":",
"best",
"=",
"{",
"}",
"cmd",
"=",
"'samtools view '",
"+",
"flag",
"+",
"' '",
"+",
"input_file",
"sys",
".",
"stderr",
".",
"write",
... | 38.4 | 0.025395 |
def create(cls, session, record, imported=False, auto_reply=False):
"""Create a conversation.
Please note that conversation cannot be created with more than 100
threads, if attempted the API will respond with HTTP 412.
Args:
session (requests.sessions.Session): Authenticate... | [
"def",
"create",
"(",
"cls",
",",
"session",
",",
"record",
",",
"imported",
"=",
"False",
",",
"auto_reply",
"=",
"False",
")",
":",
"return",
"super",
"(",
"Conversations",
",",
"cls",
")",
".",
"create",
"(",
"session",
",",
"record",
",",
"imported... | 45.133333 | 0.001446 |
def peer_status():
'''
Return peer status information
The return value is a dictionary with peer UUIDs as keys and dicts of peer
information as values. Hostnames are listed in one list. GlusterFS separates
one of the hostnames but the only reason for this seems to be which hostname
happens to b... | [
"def",
"peer_status",
"(",
")",
":",
"root",
"=",
"_gluster_xml",
"(",
"'peer status'",
")",
"if",
"not",
"_gluster_ok",
"(",
"root",
")",
":",
"return",
"None",
"result",
"=",
"{",
"}",
"for",
"peer",
"in",
"_iter",
"(",
"root",
",",
"'peer'",
")",
... | 29.326923 | 0.001904 |
def Instance(expected, message="Not an instance of {}"):
"""
Creates a validator that checks if the given value is an instance of
``expected``.
A custom message can be specified with ``message``.
"""
@wraps(Instance)
def built(value):
if not isinstance(value, expected):
... | [
"def",
"Instance",
"(",
"expected",
",",
"message",
"=",
"\"Not an instance of {}\"",
")",
":",
"@",
"wraps",
"(",
"Instance",
")",
"def",
"built",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"expected",
")",
":",
"raise",
"Erro... | 30.153846 | 0.002475 |
def p_sum_lvl_1(self, p):
""" sum_lvl_1 : script_lvl_1
| script_lvl_1 PLUS sum_lvl_1"""
if len(p) == 4:
p[3].append(p[1])
p[0] = p[3]
else:
p[0] = [p[1]] | [
"def",
"p_sum_lvl_1",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"4",
":",
"p",
"[",
"3",
"]",
".",
"append",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"3",
"]",
"else",
":",
"p",
"[",
"0... | 28.375 | 0.008547 |
def set_attr(obj, path, value):
"""
SAME AS object.__setattr__(), BUT USES DOT-DELIMITED path
RETURN OLD VALUE
"""
try:
return _set_attr(obj, split_field(path), value)
except Exception as e:
Log = get_logger()
if PATH_NOT_FOUND in e:
Log.warning(PATH_NOT_FOUND... | [
"def",
"set_attr",
"(",
"obj",
",",
"path",
",",
"value",
")",
":",
"try",
":",
"return",
"_set_attr",
"(",
"obj",
",",
"split_field",
"(",
"path",
")",
",",
"value",
")",
"except",
"Exception",
"as",
"e",
":",
"Log",
"=",
"get_logger",
"(",
")",
"... | 31.846154 | 0.002347 |
def extract_noun_phrases(tagged_doc):
"""
(From textblob)
"""
tags = _normalize_tags(tagged_doc)
merge = True
while merge:
merge = False
for x in range(0, len(tags) - 1):
t1 = tags[x]
t2 = tags[x + 1]
key = t1[1], t2[1]
value = CFG.... | [
"def",
"extract_noun_phrases",
"(",
"tagged_doc",
")",
":",
"tags",
"=",
"_normalize_tags",
"(",
"tagged_doc",
")",
"merge",
"=",
"True",
"while",
"merge",
":",
"merge",
"=",
"False",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"tags",
")",
"... | 26.708333 | 0.001506 |
def to_zarr(self, store=None, mode='w-', synchronizer=None, group=None,
encoding=None, compute=True, consolidated=False):
"""Write dataset contents to a zarr group.
.. note:: Experimental
The Zarr backend is new and experimental. Please report any
une... | [
"def",
"to_zarr",
"(",
"self",
",",
"store",
"=",
"None",
",",
"mode",
"=",
"'w-'",
",",
"synchronizer",
"=",
"None",
",",
"group",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"compute",
"=",
"True",
",",
"consolidated",
"=",
"False",
")",
":",
... | 43.545455 | 0.001531 |
def status(self, vm_name=None):
'''
Return the results of a `vagrant status` call as a list of one or more
Status objects. A Status contains the following attributes:
- name: The VM name in a multi-vm environment. 'default' otherwise.
- state: The state of the underlying guest... | [
"def",
"status",
"(",
"self",
",",
"vm_name",
"=",
"None",
")",
":",
"# machine-readable output are CSV lines",
"output",
"=",
"self",
".",
"_run_vagrant_command",
"(",
"[",
"'status'",
",",
"'--machine-readable'",
",",
"vm_name",
"]",
")",
"return",
"self",
"."... | 58.733333 | 0.002233 |
def _rsaes_pkcs1_v1_5_decrypt(self, C):
"""
Implements RSAES-PKCS1-V1_5-DECRYPT() function described in section
7.2.2 of RFC 3447.
Input:
C: ciphertext to be decrypted, an octet string of length k, where
k is the length in octets of the RSA modulus n.
O... | [
"def",
"_rsaes_pkcs1_v1_5_decrypt",
"(",
"self",
",",
"C",
")",
":",
"# 1) Length checking",
"cLen",
"=",
"len",
"(",
"C",
")",
"k",
"=",
"self",
".",
"modulusLen",
"/",
"8",
"if",
"cLen",
"!=",
"k",
"or",
"k",
"<",
"11",
":",
"warning",
"(",
"\"Key.... | 32.45614 | 0.002099 |
def right_parallel_line(ax, scale, i, **kwargs):
"""
Draws the i-th line parallel to the right axis.
Parameters
----------
ax: Matplotlib AxesSubplot
The subplot to draw on.
scale: float
Simplex scale size.
i: float
The index of the line to draw
kwargs: Dictionar... | [
"def",
"right_parallel_line",
"(",
"ax",
",",
"scale",
",",
"i",
",",
"*",
"*",
"kwargs",
")",
":",
"p1",
"=",
"(",
"0",
",",
"scale",
"-",
"i",
",",
"i",
")",
"p2",
"=",
"(",
"scale",
"-",
"i",
",",
"0",
",",
"i",
")",
"line",
"(",
"ax",
... | 23.526316 | 0.002151 |
def create_manager(arguments):
"""A simple wrapper to JobManager() that places the statefile on the correct path by default"""
if arguments.statefile is None:
arguments.statefile = os.path.join(os.path.dirname(arguments.logdir), 'submitted.db')
arguments.statefile = os.path.realpath(arguments.statefile)
... | [
"def",
"create_manager",
"(",
"arguments",
")",
":",
"if",
"arguments",
".",
"statefile",
"is",
"None",
":",
"arguments",
".",
"statefile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"arguments",
".",
"logdir",
")... | 40.888889 | 0.018617 |
def AddBudget(self, client_customer_id, micro_amount):
"""Create a new Budget with the given microAmount.
Args:
client_customer_id: str Client Customer Id used to create Budget.
micro_amount: str The budget represented in micros.
Returns:
str BudgetId of the newly created Budget.
"""... | [
"def",
"AddBudget",
"(",
"self",
",",
"client_customer_id",
",",
"micro_amount",
")",
":",
"self",
".",
"client",
".",
"SetClientCustomerId",
"(",
"client_customer_id",
")",
"budget_service",
"=",
"self",
".",
"client",
".",
"GetService",
"(",
"'BudgetService'",
... | 28.5 | 0.001305 |
def from_string(cls, key, password='notasecret'):
"""Construct an RsaSigner instance from a string.
Args:
key: string, private key in PEM format.
password: string, password for private key file. Unused for PEM
files.
Returns:
RsaSigner ... | [
"def",
"from_string",
"(",
"cls",
",",
"key",
",",
"password",
"=",
"'notasecret'",
")",
":",
"key",
"=",
"_helpers",
".",
"_from_bytes",
"(",
"key",
")",
"# pem expects str in Py3",
"marker_id",
",",
"key_bytes",
"=",
"pem",
".",
"readPemBlocksFromFile",
"(",... | 37.588235 | 0.001526 |
def highlightBlock(self, block):
"""
Reimplements the :meth:`AbstractHighlighter.highlightBlock` method.
:param block: Text block.
:type block: QString
"""
self.highlight_text(block, 0, len(block))
self.setCurrentBlockState(0)
state = 1
for rule... | [
"def",
"highlightBlock",
"(",
"self",
",",
"block",
")",
":",
"self",
".",
"highlight_text",
"(",
"block",
",",
"0",
",",
"len",
"(",
"block",
")",
")",
"self",
".",
"setCurrentBlockState",
"(",
"0",
")",
"state",
"=",
"1",
"for",
"rule",
"in",
"self... | 44.904762 | 0.011423 |
def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return f... | [
"def",
"property_observer",
"(",
"self",
",",
"name",
")",
":",
"def",
"wrapper",
"(",
"fun",
")",
":",
"self",
".",
"observe_property",
"(",
"name",
",",
"fun",
")",
"fun",
".",
"unobserve_mpv_properties",
"=",
"lambda",
":",
"self",
".",
"unobserve_prope... | 48.428571 | 0.011594 |
def _get_function_name(self, fn, default="None"):
""" Return name of function, using default value if function not defined
"""
if fn is None:
fn_name = default
else:
fn_name = fn.__name__
return fn_name | [
"def",
"_get_function_name",
"(",
"self",
",",
"fn",
",",
"default",
"=",
"\"None\"",
")",
":",
"if",
"fn",
"is",
"None",
":",
"fn_name",
"=",
"default",
"else",
":",
"fn_name",
"=",
"fn",
".",
"__name__",
"return",
"fn_name"
] | 32.375 | 0.011278 |
def get_payload(self):
"""Return Payload."""
ret = bytes([self.status.value])
ret += bytes([self.session_id >> 8 & 255, self.session_id & 255])
return ret | [
"def",
"get_payload",
"(",
"self",
")",
":",
"ret",
"=",
"bytes",
"(",
"[",
"self",
".",
"status",
".",
"value",
"]",
")",
"ret",
"+=",
"bytes",
"(",
"[",
"self",
".",
"session_id",
">>",
"8",
"&",
"255",
",",
"self",
".",
"session_id",
"&",
"255... | 36.4 | 0.010753 |
def _field_controller_generator(self):
"""
Generates the methods called by the injected controller
"""
# Local variable, to avoid messing with "self"
stored_instance = self._ipopo_instance
def get_value(self, name):
# pylint: disable=W0613
"""
... | [
"def",
"_field_controller_generator",
"(",
"self",
")",
":",
"# Local variable, to avoid messing with \"self\"",
"stored_instance",
"=",
"self",
".",
"_ipopo_instance",
"def",
"get_value",
"(",
"self",
",",
"name",
")",
":",
"# pylint: disable=W0613",
"\"\"\"\n R... | 32.911765 | 0.001736 |
def search_converted_models(root=None):
"""
Searches for all converted models generated by
unit tests in folders tests and with function
*dump_data_and_model*.
"""
if root is None:
root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tests"))
root = os.path.normp... | [
"def",
"search_converted_models",
"(",
"root",
"=",
"None",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")"... | 35.323529 | 0.002431 |
def set_monitor_callback(cbfun):
"""
Sets the monitor configuration callback.
Wrapper for:
GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun);
"""
global _monitor_callback
previous_callback = _monitor_callback
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWmonitorfu... | [
"def",
"set_monitor_callback",
"(",
"cbfun",
")",
":",
"global",
"_monitor_callback",
"previous_callback",
"=",
"_monitor_callback",
"if",
"cbfun",
"is",
"None",
":",
"cbfun",
"=",
"0",
"c_cbfun",
"=",
"_GLFWmonitorfun",
"(",
"cbfun",
")",
"_monitor_callback",
"="... | 30.411765 | 0.001876 |
def get_macs_for_vlan(self, ip, vlan, display_progress=0, snmpobj=None, system_name=None, ifname_vbtbl=None):
'''
Return array of MAC addresses for a single VLAN from a single node at an IP
'''
ret_macs = []
if (snmpobj == None):
snmpobj = natlas_snmp(ip)
... | [
"def",
"get_macs_for_vlan",
"(",
"self",
",",
"ip",
",",
"vlan",
",",
"display_progress",
"=",
"0",
",",
"snmpobj",
"=",
"None",
",",
"system_name",
"=",
"None",
",",
"ifname_vbtbl",
"=",
"None",
")",
":",
"ret_macs",
"=",
"[",
"]",
"if",
"(",
"snmpobj... | 39.57377 | 0.010509 |
def load_contents(self):
"""
Loads contents of the tables into database.
"""
with open(METADATA_FILE) as f:
lines = f.readlines()
lines = map(lambda x: x.strip(), lines)
exclude_strings = ['<begin_table>', '<end_table>']
list_of_databases_and_co... | [
"def",
"load_contents",
"(",
"self",
")",
":",
"with",
"open",
"(",
"METADATA_FILE",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"lines",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"strip",
"(",
")",
",",
"lines",
")",... | 28.285714 | 0.002442 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.