text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def add_file_patterns(self, patterns, blacklist):
"""Adds a list of file patterns to either the black- or white-list.
Note that this pattern is applied to the absolute path of the file
that will be delivered. For including or excluding folders use
`add_folder_mask` or `add_folde... | [
"def",
"add_file_patterns",
"(",
"self",
",",
"patterns",
",",
"blacklist",
")",
":",
"bl",
"=",
"self",
".",
"_pattern_black",
"if",
"blacklist",
"else",
"self",
".",
"_pattern_white",
"for",
"pattern",
"in",
"patterns",
":",
"bl",
".",
"append",
"(",
"pa... | 52.333333 | 15.666667 |
def run(**options):
"""
_run_
Run the dockerstache process to render templates
based on the options provided
If extend_context is passed as options it will be used to
extend the context with the contents of the dictionary provided
via context.update(extend_context)
"""
with Dotfil... | [
"def",
"run",
"(",
"*",
"*",
"options",
")",
":",
"with",
"Dotfile",
"(",
"options",
")",
"as",
"conf",
":",
"if",
"conf",
"[",
"'context'",
"]",
"is",
"None",
":",
"msg",
"=",
"\"No context file has been provided\"",
"LOGGER",
".",
"error",
"(",
"msg",
... | 32.361702 | 17.085106 |
def main(forward=26944, host='127.0.0.1', listen=5555):
'''
Args:
- forward(int): local forward port
- host(string): local forward host
- listen(int): listen port
'''
# HTTP->HTTP: On your computer, browse to "http://127.0.0.1:81/" and you'll get http://www.google.com
server ... | [
"def",
"main",
"(",
"forward",
"=",
"26944",
",",
"host",
"=",
"'127.0.0.1'",
",",
"listen",
"=",
"5555",
")",
":",
"# HTTP->HTTP: On your computer, browse to \"http://127.0.0.1:81/\" and you'll get http://www.google.com",
"server",
"=",
"maproxy",
".",
"proxyserver",
"."... | 43.384615 | 21.538462 |
def _ddns(self, ip):
"""
curl -X POST https://dnsapi.cn/Record.Ddns -d 'login_token=LOGIN_TOKEN&format=json&domain_id=2317346&record_id=16894439&record_line=默认&sub_domain=www'
:return:
"""
headers = {"Accept": "text/json", "User-Agent": "ddns/0.1.0 (imaguowei@gmail.com)"}
... | [
"def",
"_ddns",
"(",
"self",
",",
"ip",
")",
":",
"headers",
"=",
"{",
"\"Accept\"",
":",
"\"text/json\"",
",",
"\"User-Agent\"",
":",
"\"ddns/0.1.0 (imaguowei@gmail.com)\"",
"}",
"data",
"=",
"{",
"'login_token'",
":",
"self",
".",
"login_token",
",",
"'forma... | 34.809524 | 22.619048 |
def get_val(self):
"""
Gets attribute's value.
@return: stored value.
@rtype: int
@raise IOError: if corresponding file in /proc/sys cannot be read.
"""
with open(os.path.join(self._base, self._attr), 'r') as file_obj:
return int(file_obj.readline()) | [
"def",
"get_val",
"(",
"self",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_base",
",",
"self",
".",
"_attr",
")",
",",
"'r'",
")",
"as",
"file_obj",
":",
"return",
"int",
"(",
"file_obj",
".",
"readline",
"(... | 31 | 17.2 |
def is_deaf(self):
"""
Глухая ли согласная.
"""
if not self.is_consonant():
return False
if self.letter in self.forever_deaf:
return True
if self.letter in self.forever_sonorus:
return False
if self.__forsed_sonorus:
... | [
"def",
"is_deaf",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_consonant",
"(",
")",
":",
"return",
"False",
"if",
"self",
".",
"letter",
"in",
"self",
".",
"forever_deaf",
":",
"return",
"True",
"if",
"self",
".",
"letter",
"in",
"self",
"."... | 28.444444 | 10.333333 |
def _get_ax_layer(cls, ax, primary=True):
"""get left (primary) or right (secondary) axes"""
if primary:
return getattr(ax, 'left_ax', ax)
else:
return getattr(ax, 'right_ax', ax) | [
"def",
"_get_ax_layer",
"(",
"cls",
",",
"ax",
",",
"primary",
"=",
"True",
")",
":",
"if",
"primary",
":",
"return",
"getattr",
"(",
"ax",
",",
"'left_ax'",
",",
"ax",
")",
"else",
":",
"return",
"getattr",
"(",
"ax",
",",
"'right_ax'",
",",
"ax",
... | 37 | 10 |
def get(name, default=None, allow_default=True):
""" Shortcut method for getting a setting value.
:param str name: Setting key name.
:param default: Default value of setting if it's not explicitly
set. Defaults to `None`
:param bool allow_default: If true, use the pa... | [
"def",
"get",
"(",
"name",
",",
"default",
"=",
"None",
",",
"allow_default",
"=",
"True",
")",
":",
"return",
"Config",
"(",
")",
".",
"get",
"(",
"name",
",",
"default",
",",
"allow_default",
"=",
"allow_default",
")"
] | 48.692308 | 18.769231 |
def getColors(self):
"""
Overrideable function that generates the colors to be used by various borderstyles.
Should return a 5-tuple of ``(bg,o,i,s,h)``\ .
``bg`` is the base color of the background.
``o`` is the outer color, it is usually the same as t... | [
"def",
"getColors",
"(",
"self",
")",
":",
"bg",
"=",
"self",
".",
"submenu",
".",
"bg",
"[",
":",
"3",
"]",
"if",
"isinstance",
"(",
"self",
".",
"submenu",
".",
"bg",
",",
"list",
")",
"or",
"isinstance",
"(",
"self",
".",
"submenu",
".",
"bg",... | 47.904762 | 32.47619 |
def killCells(self, percent=0.05):
"""
Changes the percentage of cells that are now considered dead. The first
time you call this method a permutation list is set up. Calls change the
number of cells considered dead.
"""
numColumns = numpy.prod(self.getColumnDimensions())
if self.zombiePerm... | [
"def",
"killCells",
"(",
"self",
",",
"percent",
"=",
"0.05",
")",
":",
"numColumns",
"=",
"numpy",
".",
"prod",
"(",
"self",
".",
"getColumnDimensions",
"(",
")",
")",
"if",
"self",
".",
"zombiePermutation",
"is",
"None",
":",
"self",
".",
"zombiePermut... | 33.55 | 20.25 |
def delete_license_request(request):
"""Submission to remove a license acceptance request."""
uuid_ = request.matchdict['uuid']
posted_uids = [x['uid'] for x in request.json.get('licensors', [])]
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
remove_license_requests(... | [
"def",
"delete_license_request",
"(",
"request",
")",
":",
"uuid_",
"=",
"request",
".",
"matchdict",
"[",
"'uuid'",
"]",
"posted_uids",
"=",
"[",
"x",
"[",
"'uid'",
"]",
"for",
"x",
"in",
"request",
".",
"json",
".",
"get",
"(",
"'licensors'",
",",
"[... | 33.916667 | 16.75 |
def serialize_attribute(attribute): # noqa: C901 pylint: disable=too-many-locals
# type: (dynamodb_types.RAW_ATTRIBUTE) -> bytes
"""Serializes a raw attribute to a byte string as defined for the DynamoDB Client-Side Encryption Standard.
:param dict attribute: Item attribute value
:returns: Serialized ... | [
"def",
"serialize_attribute",
"(",
"attribute",
")",
":",
"# noqa: C901 pylint: disable=too-many-locals",
"# type: (dynamodb_types.RAW_ATTRIBUTE) -> bytes",
"def",
"_transform_binary_value",
"(",
"value",
")",
":",
"# type: (dynamodb_types.BINARY) -> bytes",
"\"\"\"\n :param val... | 37.2 | 15.561905 |
def _connect(self, server_info):
"""Connect to the workbench server"""
# First we do a temp connect with a short heartbeat
_tmp_connect = zerorpc.Client(timeout=300, heartbeat=2)
_tmp_connect.connect('tcp://'+server_info['server']+':'+server_info['port'])
try:
_tmp_c... | [
"def",
"_connect",
"(",
"self",
",",
"server_info",
")",
":",
"# First we do a temp connect with a short heartbeat",
"_tmp_connect",
"=",
"zerorpc",
".",
"Client",
"(",
"timeout",
"=",
"300",
",",
"heartbeat",
"=",
"2",
")",
"_tmp_connect",
".",
"connect",
"(",
... | 47.619048 | 24.142857 |
def import_settings(dotted_path):
"""Import settings instance from python dotted path.
Last item in dotted path must be settings instace.
Example: import_settings('path.to.settings')
"""
if "." in dotted_path:
module, name = dotted_path.rsplit(".", 1)
else:
raise click.UsageErr... | [
"def",
"import_settings",
"(",
"dotted_path",
")",
":",
"if",
"\".\"",
"in",
"dotted_path",
":",
"module",
",",
"name",
"=",
"dotted_path",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"else",
":",
"raise",
"click",
".",
"UsageError",
"(",
"\"invalid path t... | 29.428571 | 16.428571 |
def run(self, input_files, url=None, verbose=0):
"""
run the headless browser with given input
if url given, the proc will only run hlb with given url and ignore input_list.
:param url:
:param input_files: the name of the file in "index url" format. i.e.
1, www.fa... | [
"def",
"run",
"(",
"self",
",",
"input_files",
",",
"url",
"=",
"None",
",",
"verbose",
"=",
"0",
")",
":",
"if",
"not",
"url",
"and",
"not",
"input_files",
":",
"logging",
".",
"warning",
"(",
"\"No input file\"",
")",
"return",
"{",
"\"error\"",
":",... | 35.428571 | 19.673469 |
def add(self, obj):
"""Add a object
Args:
Object: Object will be added
Returns:
Object: Object with id
Raises:
TypeError: If add object is not a dict
MultipleInvalid: If input object is invaild
"""
... | [
"def",
"add",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"Add object should be a dict object\"",
")",
"obj",
"=",
"self",
".",
"validation",
"(",
"obj",
")",
"obj",
"[",
... | 31.75 | 12.45 |
def install(name=None, refresh=False, version=None, pkgs=None, **kwargs):
'''
Install packages using the pkgutil tool.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package_name>
salt '*' pkg.install SMClgcc346
Multiple Package Installation Options:
pkgs
A... | [
"def",
"install",
"(",
"name",
"=",
"None",
",",
"refresh",
"=",
"False",
",",
"version",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"refresh",
":",
"refresh_db",
"(",
")",
"try",
":",
"# Ignore 'sources' argument",... | 27.2 | 23.633333 |
def all(self, list_id, subscriber_hash, **queryparams):
"""
Get the last 50 events of a member’s activity on a specific list,
including opens, clicks, and unsubscribes.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param subscriber_hash: The... | [
"def",
"all",
"(",
"self",
",",
"list_id",
",",
"subscriber_hash",
",",
"*",
"*",
"queryparams",
")",
":",
"subscriber_hash",
"=",
"check_subscriber_hash",
"(",
"subscriber_hash",
")",
"self",
".",
"list_id",
"=",
"list_id",
"self",
".",
"subscriber_hash",
"="... | 46.722222 | 16.611111 |
def start_fsweep(self, start=None, stop=None, step=None):
"""Starts a frequency sweep.
:param start: Sets the start frequency.
:param stop: Sets the target frequency.
:param step: Sets the frequency step.
"""
if start:
self.frequency_start = start
if... | [
"def",
"start_fsweep",
"(",
"self",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"step",
"=",
"None",
")",
":",
"if",
"start",
":",
"self",
".",
"frequency_start",
"=",
"start",
"if",
"stop",
":",
"self",
".",
"frequency_stop",
"=",
"sto... | 30 | 12.866667 |
def get_unweighted_sources(graph: BELGraph, key: Optional[str] = None) -> Iterable[BaseEntity]:
"""Get nodes on the periphery of the sub-graph that do not have a annotation for the given key.
:param graph: A BEL graph
:param key: The key in the node data dictionary representing the experimental data
:r... | [
"def",
"get_unweighted_sources",
"(",
"graph",
":",
"BELGraph",
",",
"key",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Iterable",
"[",
"BaseEntity",
"]",
":",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"WEIGHT",
"for",
"node",
"in",
... | 42.076923 | 25.923077 |
def p_annotation_ref(self, p):
"""annotation_ref : AT ID NL
| AT ID DOT ID NL"""
if len(p) < 5:
p[0] = AstAnnotationRef(self.path, p.lineno(1), p.lexpos(1), p[2], None)
else:
p[0] = AstAnnotationRef(self.path, p.lineno(1), p.lexpos(1), p[4], p[2]... | [
"def",
"p_annotation_ref",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"<",
"5",
":",
"p",
"[",
"0",
"]",
"=",
"AstAnnotationRef",
"(",
"self",
".",
"path",
",",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"p",
".",
"lexpos",
"("... | 45 | 20.428571 |
def update_lun(self, add_luns=None, remove_luns=None):
"""Updates the LUNs in CG, adding the ones in `add_luns` and removing
the ones in `remove_luns`"""
if not add_luns and not remove_luns:
log.debug("Empty add_luns and remove_luns passed in, "
"skip update_lun... | [
"def",
"update_lun",
"(",
"self",
",",
"add_luns",
"=",
"None",
",",
"remove_luns",
"=",
"None",
")",
":",
"if",
"not",
"add_luns",
"and",
"not",
"remove_luns",
":",
"log",
".",
"debug",
"(",
"\"Empty add_luns and remove_luns passed in, \"",
"\"skip update_lun.\""... | 52.5 | 12 |
def browse(self, cat=None, subCat=None):
"""Browse categories. If neither cat nor subcat are specified,
return a list of categories, otherwise it return a list of apps
using cat (category ID) and subCat (subcategory ID) as filters."""
path = BROWSE_URL + "?c=3"
if cat is not None... | [
"def",
"browse",
"(",
"self",
",",
"cat",
"=",
"None",
",",
"subCat",
"=",
"None",
")",
":",
"path",
"=",
"BROWSE_URL",
"+",
"\"?c=3\"",
"if",
"cat",
"is",
"not",
"None",
":",
"path",
"+=",
"\"&cat={}\"",
".",
"format",
"(",
"requests",
".",
"utils",... | 48.75 | 14.916667 |
def dtcurrent(self, value):
"""Set value of `dtcurrent`, update derivatives if needed."""
assert isinstance(value, bool)
if value and self.dparamscurrent:
raise RuntimeError("Can't set both dparamscurrent and dtcurrent True")
if value != self.dtcurrent:
self._dtcu... | [
"def",
"dtcurrent",
"(",
"self",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"bool",
")",
"if",
"value",
"and",
"self",
".",
"dparamscurrent",
":",
"raise",
"RuntimeError",
"(",
"\"Can't set both dparamscurrent and dtcurrent True\"",
")",
... | 45.25 | 9.125 |
def _flatterm_iter(cls, expression: Expression) -> Iterator[TermAtom]:
"""Generator that yields the atoms of the expressions in prefix notation with operation end markers."""
if isinstance(expression, Operation):
yield type(expression)
for operand in op_iter(expression):
... | [
"def",
"_flatterm_iter",
"(",
"cls",
",",
"expression",
":",
"Expression",
")",
"->",
"Iterator",
"[",
"TermAtom",
"]",
":",
"if",
"isinstance",
"(",
"expression",
",",
"Operation",
")",
":",
"yield",
"type",
"(",
"expression",
")",
"for",
"operand",
"in",... | 51.615385 | 14.461538 |
def lightcurve(self, name, **kwargs):
"""Generate a lightcurve for the named source. The function will
complete the basic analysis steps for each bin and perform a
likelihood fit for each bin. Extracted values (along with
errors) are Integral Flux, spectral model, Spectral index, TS
... | [
"def",
"lightcurve",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"self",
".",
"roi",
".",
"get_source_by_name",
"(",
"name",
")",
".",
"name",
"# Create schema for method configuration",
"schema",
"=",
"ConfigSchema",
"(",
"self... | 35.27451 | 23.137255 |
def _init_po_files(target, source, env):
""" Action function for `POInit` builder. """
nop = lambda target, source, env: 0
if 'POAUTOINIT' in env:
autoinit = env['POAUTOINIT']
else:
autoinit = False
# Well, if everything outside works well, this loop should do single
# iteration.... | [
"def",
"_init_po_files",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"nop",
"=",
"lambda",
"target",
",",
"source",
",",
"env",
":",
"0",
"if",
"'POAUTOINIT'",
"in",
"env",
":",
"autoinit",
"=",
"env",
"[",
"'POAUTOINIT'",
"]",
"else",
":",
"... | 41.954545 | 16.909091 |
def parse_epoch(self, epoch_str):
"""
Converts epoch field to a float value (adding 24... prefix), or
``None`` if there is no epoch in GCVS record.
"""
epoch = epoch_str.translate(TRANSLATION_MAP)[:10].strip()
return 2400000.0 + float(epoch) if epoch else None | [
"def",
"parse_epoch",
"(",
"self",
",",
"epoch_str",
")",
":",
"epoch",
"=",
"epoch_str",
".",
"translate",
"(",
"TRANSLATION_MAP",
")",
"[",
":",
"10",
"]",
".",
"strip",
"(",
")",
"return",
"2400000.0",
"+",
"float",
"(",
"epoch",
")",
"if",
"epoch",... | 43.142857 | 13.428571 |
def import_and_get_class(path_to_pex, python_class_name):
"""Imports and load a class from a given pex file path and python class name
For example, if you want to get a class called `Sample` in
/some-path/sample.pex/heron/examples/src/python/sample.py,
``path_to_pex`` needs to be ``/some-path/sample.pex``, and... | [
"def",
"import_and_get_class",
"(",
"path_to_pex",
",",
"python_class_name",
")",
":",
"abs_path_to_pex",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path_to_pex",
")",
"Log",
".",
"debug",
"(",
"\"Add a pex to the path: %s\"",
"%",
"abs_path_to_pex",
")",
"Log"... | 43.793103 | 22.793103 |
def load_config_module():
"""
If the config.py file exists, import it as a module. If it does not exist,
call sys.exit() with a request to run oaepub configure.
"""
import imp
config_path = config_location()
try:
config = imp.load_source('config', config_path)
except IOError:
... | [
"def",
"load_config_module",
"(",
")",
":",
"import",
"imp",
"config_path",
"=",
"config_location",
"(",
")",
"try",
":",
"config",
"=",
"imp",
".",
"load_source",
"(",
"'config'",
",",
"config_path",
")",
"except",
"IOError",
":",
"log",
".",
"critical",
... | 36.2 | 20.466667 |
def create_group(self, data):
"""Create a Group."""
# http://teampasswordmanager.com/docs/api-groups/#create_group
log.info('Create group with %s' % data)
NewID = self.post('groups.json', data).get('id')
log.info('Group has been created with ID %s' % NewID)
return NewID | [
"def",
"create_group",
"(",
"self",
",",
"data",
")",
":",
"# http://teampasswordmanager.com/docs/api-groups/#create_group",
"log",
".",
"info",
"(",
"'Create group with %s'",
"%",
"data",
")",
"NewID",
"=",
"self",
".",
"post",
"(",
"'groups.json'",
",",
"data",
... | 44.571429 | 15 |
def fit_transform(self, X, y=None):
"""Encode categorical columns into label encoded columns
Args:
X (pandas.DataFrame): categorical columns to encode
Returns:
X (pandas.DataFrame): label encoded columns
"""
self.label_encoders = [None] * X.shape[1]
... | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"self",
".",
"label_encoders",
"=",
"[",
"None",
"]",
"*",
"X",
".",
"shape",
"[",
"1",
"]",
"self",
".",
"label_maxes",
"=",
"[",
"None",
"]",
"*",
"X",
".",
"shap... | 30.65 | 22.9 |
def insert_many(cls, documents):
"""Insert a list of documents"""
from mongoframes.queries import to_refs
# Ensure all documents have been converted to frames
frames = cls._ensure_frames(documents)
# Send insert signal
signal('insert').send(cls, frames=frames)
... | [
"def",
"insert_many",
"(",
"cls",
",",
"documents",
")",
":",
"from",
"mongoframes",
".",
"queries",
"import",
"to_refs",
"# Ensure all documents have been converted to frames",
"frames",
"=",
"cls",
".",
"_ensure_frames",
"(",
"documents",
")",
"# Send insert signal",
... | 29.25 | 19.666667 |
def _sensoryComputeInferenceMode(self, anchorInput):
"""
Infer the location from sensory input. Activate any cells with enough active
synapses to this sensory input. Deactivate all other cells.
@param anchorInput (numpy array)
A sensory input. This will often come from a feature-location pair layer... | [
"def",
"_sensoryComputeInferenceMode",
"(",
"self",
",",
"anchorInput",
")",
":",
"if",
"len",
"(",
"anchorInput",
")",
"==",
"0",
":",
"return",
"overlaps",
"=",
"self",
".",
"connections",
".",
"computeActivity",
"(",
"anchorInput",
",",
"self",
".",
"conn... | 38.555556 | 19.925926 |
def get_week_start_end_day():
"""
Get the week start date and end date
"""
t = date.today()
wd = t.weekday()
return (t - timedelta(wd), t + timedelta(6 - wd)) | [
"def",
"get_week_start_end_day",
"(",
")",
":",
"t",
"=",
"date",
".",
"today",
"(",
")",
"wd",
"=",
"t",
".",
"weekday",
"(",
")",
"return",
"(",
"t",
"-",
"timedelta",
"(",
"wd",
")",
",",
"t",
"+",
"timedelta",
"(",
"6",
"-",
"wd",
")",
")"
... | 25.142857 | 9.142857 |
def _get_language_with_alpha2_fallback(language_code):
"""
Lookup language code `language_code` (string) in the internal language codes,
and if that fails, try to map map `language_code` to the internal represention
using the `getlang_by_alpha2` helper method.
Returns either a le-utils Language obje... | [
"def",
"_get_language_with_alpha2_fallback",
"(",
"language_code",
")",
":",
"# 1. try to lookup `language` using internal representation",
"language_obj",
"=",
"languages",
".",
"getlang",
"(",
"language_code",
")",
"# if language_obj not None, we know `language` is a valid language_i... | 51.928571 | 20.785714 |
def uninstall_ruby(ruby, runas=None):
'''
Uninstall a ruby implementation.
ruby
The version of ruby to uninstall. Should match one of the versions
listed by :py:func:`rbenv.versions <salt.modules.rbenv.versions>`.
runas
The user under which to run rbenv. If not specified, then ... | [
"def",
"uninstall_ruby",
"(",
"ruby",
",",
"runas",
"=",
"None",
")",
":",
"ruby",
"=",
"re",
".",
"sub",
"(",
"r'^ruby-'",
",",
"''",
",",
"ruby",
")",
"_rbenv_exec",
"(",
"[",
"'uninstall'",
",",
"'--force'",
",",
"ruby",
"]",
",",
"runas",
"=",
... | 27.714286 | 26.095238 |
def get_medium_url(self):
"""Returns the medium size image URL."""
if self.is_gif():
return self.get_absolute_url()
return '%s%s-%s.jpg' % (settings.MEDIA_URL, self.get_name(), 'medium') | [
"def",
"get_medium_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_gif",
"(",
")",
":",
"return",
"self",
".",
"get_absolute_url",
"(",
")",
"return",
"'%s%s-%s.jpg'",
"%",
"(",
"settings",
".",
"MEDIA_URL",
",",
"self",
".",
"get_name",
"(",
")",
... | 43.6 | 14 |
def po_file(self):
"""Return the parsed .po file that is currently being translated/viewed.
(Note that this parsing also involves marking up each entry with a hash
of its contents.)
"""
if self.po_file_is_writable:
# If we can write changes to file, then we pull it u... | [
"def",
"po_file",
"(",
"self",
")",
":",
"if",
"self",
".",
"po_file_is_writable",
":",
"# If we can write changes to file, then we pull it up fresh with",
"# each request.",
"# XXX: brittle; what if this path doesn't exist? Isn't a .po file?",
"po_file",
"=",
"pofile",
"(",
"sel... | 49.97561 | 19.121951 |
def get_trusted_subjects():
"""Get set of subjects that have unlimited access to all SciObj and APIs on this
node."""
cert_subj = _get_client_side_certificate_subject()
return (
d1_gmn.app.node_registry.get_cn_subjects()
| django.conf.settings.DATAONE_TRUSTED_SUBJECTS
| {cert_sub... | [
"def",
"get_trusted_subjects",
"(",
")",
":",
"cert_subj",
"=",
"_get_client_side_certificate_subject",
"(",
")",
"return",
"(",
"d1_gmn",
".",
"app",
".",
"node_registry",
".",
"get_cn_subjects",
"(",
")",
"|",
"django",
".",
"conf",
".",
"settings",
".",
"DA... | 33.636364 | 14.909091 |
def get_related_synsets(self,relation):
"""Retrieves all the synsets which are related by given relation.
Parameters
----------
relation : str
Name of the relation via which the sought synsets are linked.
Returns
-------
list of Synsets
Synse... | [
"def",
"get_related_synsets",
"(",
"self",
",",
"relation",
")",
":",
"results",
"=",
"[",
"]",
"for",
"relation_candidate",
"in",
"self",
".",
"_raw_synset",
".",
"internalLinks",
":",
"if",
"relation_candidate",
".",
"name",
"==",
"relation",
":",
"linked_sy... | 33.409091 | 22.681818 |
def extractClips(self, specsFilePathOrStr, outputDir=None, zipOutput=False):
"""Extract clips according to the specification file or string.
Arguments:
specsFilePathOrStr (str): Specification file path or string
outputDir (str): Location of the extracted clips
... | [
"def",
"extractClips",
"(",
"self",
",",
"specsFilePathOrStr",
",",
"outputDir",
"=",
"None",
",",
"zipOutput",
"=",
"False",
")",
":",
"clips",
"=",
"SpecsParser",
".",
"parse",
"(",
"specsFilePathOrStr",
")",
"# Output to current working directory if no outputDir wa... | 34.695652 | 22.652174 |
def restore_node(self, node):
"""
Restores a previously hidden node back into the graph and restores
all of its incoming and outgoing edges.
"""
try:
self.nodes[node], all_edges = self.hidden_nodes[node]
for edge in all_edges:
self.restore_... | [
"def",
"restore_node",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"self",
".",
"nodes",
"[",
"node",
"]",
",",
"all_edges",
"=",
"self",
".",
"hidden_nodes",
"[",
"node",
"]",
"for",
"edge",
"in",
"all_edges",
":",
"self",
".",
"restore_edge",
"... | 36.583333 | 11.916667 |
def _get_standard_tc_matches(text, full_text, options):
'''
get the standard tab completions.
These are the options which could complete the full_text.
'''
final_matches = [o for o in options if o.startswith(full_text)]
return final_matches | [
"def",
"_get_standard_tc_matches",
"(",
"text",
",",
"full_text",
",",
"options",
")",
":",
"final_matches",
"=",
"[",
"o",
"for",
"o",
"in",
"options",
"if",
"o",
".",
"startswith",
"(",
"full_text",
")",
"]",
"return",
"final_matches"
] | 36.857143 | 21.142857 |
def compute(self, inputs, outputs):
"""
Get the next record from the queue and encode it. The fields for inputs and
outputs are as defined in the spec above.
"""
if len(self.queue) > 0:
# Take the top element of the data queue
data = self.queue.pop()
else:
raise Exception("Raw... | [
"def",
"compute",
"(",
"self",
",",
"inputs",
",",
"outputs",
")",
":",
"if",
"len",
"(",
"self",
".",
"queue",
")",
">",
"0",
":",
"# Take the top element of the data queue",
"data",
"=",
"self",
".",
"queue",
".",
"pop",
"(",
")",
"else",
":",
"raise... | 33.478261 | 15.304348 |
def get_next_create_state(self, state, ret):
"""Return the next create state from previous state. """
if ret:
if state == fw_const.FABRIC_PREPARE_DONE_STATE:
return state
else:
return state + 1
else:
return state | [
"def",
"get_next_create_state",
"(",
"self",
",",
"state",
",",
"ret",
")",
":",
"if",
"ret",
":",
"if",
"state",
"==",
"fw_const",
".",
"FABRIC_PREPARE_DONE_STATE",
":",
"return",
"state",
"else",
":",
"return",
"state",
"+",
"1",
"else",
":",
"return",
... | 32.888889 | 14.888889 |
def putRequest(self, request, block=True, timeout=0):
"""Put work request into work queue and save its id for later."""
# don't reuse old work requests
# print '\tthread pool putting work request %s'%request
self._requests_queue.put(request, block, timeout)
self.workRequests[requ... | [
"def",
"putRequest",
"(",
"self",
",",
"request",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"0",
")",
":",
"# don't reuse old work requests",
"# print '\\tthread pool putting work request %s'%request",
"self",
".",
"_requests_queue",
".",
"put",
"(",
"request",
... | 56.5 | 11.333333 |
def setup(self):
"""Initialize the consumer, setting up needed attributes and connecting
to RabbitMQ.
"""
LOGGER.info('Initializing for %s', self.name)
if 'consumer' not in self.consumer_config:
return self.on_startup_error(
'"consumer" not specified... | [
"def",
"setup",
"(",
"self",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Initializing for %s'",
",",
"self",
".",
"name",
")",
"if",
"'consumer'",
"not",
"in",
"self",
".",
"consumer_config",
":",
"return",
"self",
".",
"on_startup_error",
"(",
"'\"consumer\" no... | 32.695652 | 16.608696 |
def get_song_by_url(self, song_url, song_name, folder, lyric_info):
"""Download a song and save it to disk.
:params song_url: download address.
:params song_name: song name.
:params folder: storage path.
:params lyric: lyric info.
"""
if not os.path.exists(folde... | [
"def",
"get_song_by_url",
"(",
"self",
",",
"song_url",
",",
"song_name",
",",
"folder",
",",
"lyric_info",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"folder",
")",
":",
"os",
".",
"makedirs",
"(",
"folder",
")",
"fpath",
"=",
"os... | 42.641026 | 18.076923 |
def get_event_public_discount(self, id, discount_id, **data):
"""
GET /events/:id/public_discounts/:discount_id/
Gets a public :format:`discount` by ID as the key ``discount``.
"""
return self.get("/events/{0}/public_discounts/{0}/".format(id,discount_id), data=data) | [
"def",
"get_event_public_discount",
"(",
"self",
",",
"id",
",",
"discount_id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"get",
"(",
"\"/events/{0}/public_discounts/{0}/\"",
".",
"format",
"(",
"id",
",",
"discount_id",
")",
",",
"data",
"=",
... | 44.285714 | 21.714286 |
def __branch_point_dfs_recursive(u, large_n, b, stem, dfs_data):
"""A recursive implementation of the BranchPtDFS function, as defined on page 14 of the paper."""
first_vertex = dfs_data['adj'][u][0]
large_w = wt(u, first_vertex, dfs_data)
if large_w % 2 == 0:
large_w += 1
v_I = 0
v_II =... | [
"def",
"__branch_point_dfs_recursive",
"(",
"u",
",",
"large_n",
",",
"b",
",",
"stem",
",",
"dfs_data",
")",
":",
"first_vertex",
"=",
"dfs_data",
"[",
"'adj'",
"]",
"[",
"u",
"]",
"[",
"0",
"]",
"large_w",
"=",
"wt",
"(",
"u",
",",
"first_vertex",
... | 36.948276 | 13.482759 |
def j1(x, context=None):
"""
Return the value of the first kind Bessel function of order 1 at x.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_j1,
(BigFloat._implicit_convert(x),),
context,
) | [
"def",
"j1",
"(",
"x",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_j1",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
")",
",",
"context",
",",
")"
... | 23.181818 | 17.727273 |
def remove_file_from_tree(tree, file_path):
"""Remove a file from a tree.
Args:
tree
A list of dicts containing info about each blob in a tree.
file_path
The path of a file to remove from a tree.
Returns:
The provided tree, but with the item matching the s... | [
"def",
"remove_file_from_tree",
"(",
"tree",
",",
"file_path",
")",
":",
"match",
"=",
"None",
"for",
"item",
"in",
"tree",
":",
"if",
"item",
".",
"get",
"(",
"\"path\"",
")",
"==",
"file_path",
":",
"match",
"=",
"item",
"break",
"if",
"match",
":",
... | 21.75 | 22.75 |
def keep_absolute_impute__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Absolute (impute)
xlabel = "Max fraction of features kept"
ylabel = "ROC AUC"
transform = "identity"
sort_order = 19
"""
return __run_measure(measures.keep_mask, X, y, model_generator, method_name... | [
"def",
"keep_absolute_impute__roc_auc",
"(",
"X",
",",
"y",
",",
"model_generator",
",",
"method_name",
",",
"num_fcounts",
"=",
"11",
")",
":",
"return",
"__run_measure",
"(",
"measures",
".",
"keep_mask",
",",
"X",
",",
"y",
",",
"model_generator",
",",
"m... | 45.125 | 23.75 |
def _find_exits(self, src_block, target_block):
"""
Source block has more than one exit, and through some of those exits, the control flow can eventually go to
the target block. This method returns exits that lead to the target block.
:param src_block: The block that has multiple ... | [
"def",
"_find_exits",
"(",
"self",
",",
"src_block",
",",
"target_block",
")",
":",
"# Enumerate all statements and find exit statements",
"# Since we don't have a state, we have to rely on the pyvex block instead of SimIRSB",
"# Just create the block from pyvex again - not a big deal",
"i... | 44.333333 | 25.550725 |
def print_cmd_line(self, s, target, source, env):
"""
In python 3, and in some of our tests, sys.stdout is
a String io object, and it takes unicode strings only
In other cases it's a regular Python 2.x file object
which takes strings (bytes), and if you pass those a
unico... | [
"def",
"print_cmd_line",
"(",
"self",
",",
"s",
",",
"target",
",",
"source",
",",
"env",
")",
":",
"try",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"s",
"+",
"u\"\\n\"",
")",
"except",
"UnicodeDecodeError",
":",
"sys",
".",
"stdout",
".",
"write... | 43.2 | 12.933333 |
def update(self, ttl=values.unset, collection_ttl=values.unset):
"""
Update the SyncMapInstance
:param unicode ttl: Alias for collection_ttl
:param unicode collection_ttl: New time-to-live of this Map in seconds.
:returns: Updated SyncMapInstance
:rtype: twilio.rest.syn... | [
"def",
"update",
"(",
"self",
",",
"ttl",
"=",
"values",
".",
"unset",
",",
"collection_ttl",
"=",
"values",
".",
"unset",
")",
":",
"return",
"self",
".",
"_proxy",
".",
"update",
"(",
"ttl",
"=",
"ttl",
",",
"collection_ttl",
"=",
"collection_ttl",
"... | 39.545455 | 20.454545 |
def _is_ctype(self, ctype):
"""Return True iff content is valid and of the given type."""
if not self.valid:
return False
mime = self.content_type
return self.ContentMimetypes.get(mime) == ctype | [
"def",
"_is_ctype",
"(",
"self",
",",
"ctype",
")",
":",
"if",
"not",
"self",
".",
"valid",
":",
"return",
"False",
"mime",
"=",
"self",
".",
"content_type",
"return",
"self",
".",
"ContentMimetypes",
".",
"get",
"(",
"mime",
")",
"==",
"ctype"
] | 38.833333 | 11 |
def _evaluate(self):
"""Scan for orphaned records and retrieve any records that have not already been grabbed"""
retrieved_records = SortedDict()
for record_id, record in six.iteritems(self._elements):
if record is self._field._unset:
# Record has not yet been retri... | [
"def",
"_evaluate",
"(",
"self",
")",
":",
"retrieved_records",
"=",
"SortedDict",
"(",
")",
"for",
"record_id",
",",
"record",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_elements",
")",
":",
"if",
"record",
"is",
"self",
".",
"_field",
".",
"_... | 40.75 | 23.2 |
def config(name='ckeditor', custom_config='', **kwargs):
"""Config CKEditor.
:param name: The target input field's name. If you use Flask-WTF/WTForms, it need to set
to field's name. Default to ``'ckeditor'``.
:param custom_config: The addition config, for example ``uiColor: '#9AB8F... | [
"def",
"config",
"(",
"name",
"=",
"'ckeditor'",
",",
"custom_config",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"extra_plugins",
"=",
"kwargs",
".",
"get",
"(",
"'extra_plugins'",
",",
"current_app",
".",
"config",
"[",
"'CKEDITOR_EXTRA_PLUGINS'",
"]",
... | 44.109589 | 28.410959 |
def _queue_dag(self, name, *, data=None):
""" Add a new dag to the queue.
If the stop workflow flag is set, no new dag can be queued.
Args:
name (str): The name of the dag that should be queued.
data (MultiTaskData): The data that should be passed on to the new dag.
... | [
"def",
"_queue_dag",
"(",
"self",
",",
"name",
",",
"*",
",",
"data",
"=",
"None",
")",
":",
"if",
"self",
".",
"_stop_workflow",
":",
"return",
"None",
"if",
"name",
"not",
"in",
"self",
".",
"_dags_blueprint",
":",
"raise",
"DagNameUnknown",
"(",
")"... | 32.857143 | 22.571429 |
def get_all_eip_addresses(addresses=None, allocation_ids=None, region=None,
key=None, keyid=None, profile=None):
'''
Get public addresses of some, or all EIPs associated with the current account.
addresses
(list) - Optional list of addresses. If provided, only the addres... | [
"def",
"get_all_eip_addresses",
"(",
"addresses",
"=",
"None",
",",
"allocation_ids",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"return",
"[",
"x",
".",
"public_i... | 34.36 | 29.32 |
def update(device_id, **params):
'''
Updates device information in Server Density. For more information see the
`API docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Updating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.update 51f7eafcdba4bb235e0... | [
"def",
"update",
"(",
"device_id",
",",
"*",
"*",
"params",
")",
":",
"params",
"=",
"_clean_salt_variables",
"(",
"params",
")",
"api_response",
"=",
"requests",
".",
"put",
"(",
"'https://api.serverdensity.io/inventory/devices/'",
"+",
"device_id",
",",
"params"... | 35.055556 | 26.833333 |
def kraken_request(self, method, endpoint, **kwargs):
"""Make a request to one of the kraken api endpoints.
Headers are automatically set to accept :data:`TWITCH_HEADER_ACCEPT`.
Also the client id from :data:`CLIENT_ID` will be set.
The url will be constructed of :data:`TWITCH_KRAKENURL... | [
"def",
"kraken_request",
"(",
"self",
",",
"method",
",",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"TWITCH_KRAKENURL",
"+",
"endpoint",
"headers",
"=",
"kwargs",
".",
"setdefault",
"(",
"'headers'",
",",
"{",
"}",
")",
"headers",
"[",
... | 46.434783 | 16.26087 |
def enable_autocenter(self, option):
"""Set ``autocenter`` behavior.
Parameters
----------
option : {'on', 'override', 'once', 'off'}
Option for auto-center behavior. A list of acceptable options can
also be obtained by :meth:`get_autocenter_options`.
Ra... | [
"def",
"enable_autocenter",
"(",
"self",
",",
"option",
")",
":",
"option",
"=",
"option",
".",
"lower",
"(",
")",
"assert",
"(",
"option",
"in",
"self",
".",
"autocenter_options",
")",
",",
"ImageViewError",
"(",
"\"Bad autocenter option '%s': must be one of %s\"... | 32.5 | 18.6 |
def create_body(action, params):
"""Create http body for rest request."""
body = {}
body['action'] = action
if params is not None:
body['params'] = params
return body | [
"def",
"create_body",
"(",
"action",
",",
"params",
")",
":",
"body",
"=",
"{",
"}",
"body",
"[",
"'action'",
"]",
"=",
"action",
"if",
"params",
"is",
"not",
"None",
":",
"body",
"[",
"'params'",
"]",
"=",
"params",
"return",
"body"
] | 30.285714 | 10.857143 |
def chrome_tracing_object_transfer_dump(self, filename=None):
"""Return a list of transfer events that can viewed as a timeline.
To view this information as a timeline, simply dump it as a json file
by passing in "filename" or using using json.dump, and then load go to
chrome://tracing ... | [
"def",
"chrome_tracing_object_transfer_dump",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"client_id_to_address",
"=",
"{",
"}",
"for",
"client_info",
"in",
"ray",
".",
"global_state",
".",
"client_table",
"(",
")",
":",
"client_id_to_address",
"[",
"cl... | 44.577778 | 22.366667 |
def __map_axis(self, axis):
"""Get the linux xpad code from the Windows xinput code."""
start_code, start_value = axis
value = start_value
code = self.manager.codes['xpad'][start_code]
return code, value | [
"def",
"__map_axis",
"(",
"self",
",",
"axis",
")",
":",
"start_code",
",",
"start_value",
"=",
"axis",
"value",
"=",
"start_value",
"code",
"=",
"self",
".",
"manager",
".",
"codes",
"[",
"'xpad'",
"]",
"[",
"start_code",
"]",
"return",
"code",
",",
"... | 39.666667 | 9.166667 |
def on_drag(self, cursor_x, cursor_y):
""" Mouse cursor is moving
Glut calls this function (when mouse button is down)
and pases the mouse cursor postion in window coords as the mouse moves.
"""
from blmath.geometry.transform.rodrigues import as_rotation_matrix
if... | [
"def",
"on_drag",
"(",
"self",
",",
"cursor_x",
",",
"cursor_y",
")",
":",
"from",
"blmath",
".",
"geometry",
".",
"transform",
".",
"rodrigues",
"import",
"as_rotation_matrix",
"if",
"self",
".",
"isdragging",
":",
"mouse_pt",
"=",
"arcball",
".",
"Point2fT... | 54.190476 | 20.142857 |
def scroll_backward_vertically(self, steps=10, *args, **selectors):
"""
Perform scroll backward (vertically)action on the object which has *selectors* attributes.
Return whether the object can be Scroll or not.
See `Scroll Forward Vertically` for more details.
"""
retur... | [
"def",
"scroll_backward_vertically",
"(",
"self",
",",
"steps",
"=",
"10",
",",
"*",
"args",
",",
"*",
"*",
"selectors",
")",
":",
"return",
"self",
".",
"device",
"(",
"*",
"*",
"selectors",
")",
".",
"scroll",
".",
"vert",
".",
"backward",
"(",
"st... | 41.333333 | 25.555556 |
def reflect_image(image, axis=None, tx=None, metric='mattes'):
"""
Reflect an image along an axis
ANTsR function: `reflectImage`
Arguments
---------
image : ANTsImage
image to reflect
axis : integer (optional)
which dimension to reflect across, numbered from 0 to image... | [
"def",
"reflect_image",
"(",
"image",
",",
"axis",
"=",
"None",
",",
"tx",
"=",
"None",
",",
"metric",
"=",
"'mattes'",
")",
":",
"if",
"axis",
"is",
"None",
":",
"axis",
"=",
"image",
".",
"dimension",
"-",
"1",
"if",
"(",
"axis",
">",
"image",
... | 26.3 | 23.06 |
def decompile_pyc(bin_pyc, output=sys.stdout):
'''
decompile apython pyc or pyo binary file.
:param bin_pyc: input file objects
:param output: output file objects
'''
from turicreate.meta.asttools import python_source
bin = bin_pyc.read()
code = marshal.loads(bin[8:])... | [
"def",
"decompile_pyc",
"(",
"bin_pyc",
",",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"from",
"turicreate",
".",
"meta",
".",
"asttools",
"import",
"python_source",
"bin",
"=",
"bin_pyc",
".",
"read",
"(",
")",
"code",
"=",
"marshal",
".",
"loads",... | 22.705882 | 20.235294 |
def from_credentials(credentials):
"""Returns a new API object from an existing Credentials object.
:param credentials: The existing saved credentials.
:type credentials: Credentials
:return: A new API object populated with MyGeotab credentials.
:rtype: API
"""
r... | [
"def",
"from_credentials",
"(",
"credentials",
")",
":",
"return",
"API",
"(",
"username",
"=",
"credentials",
".",
"username",
",",
"password",
"=",
"credentials",
".",
"password",
",",
"database",
"=",
"credentials",
".",
"database",
",",
"session_id",
"=",
... | 46.545455 | 18.818182 |
def set_password(self, user, password):
"""
Sets the password for the passed user.
Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/support/users#set-a-users-password>`__.
:param user: User object or id
:param password: new password
"""
url = s... | [
"def",
"set_password",
"(",
"self",
",",
"user",
",",
"password",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"self",
".",
"endpoint",
".",
"set_password",
"(",
"id",
"=",
"user",
")",
")",
"return",
"self",
".",
"_post",
"(",
"url",
",",
... | 42.6 | 17.6 |
def _attach_endpoints(self):
"""Dynamically attaches endpoint callables to this client"""
for name, value in inspect.getmembers(self):
if inspect.isclass(value) and issubclass(value, self._Endpoint) and (value is not self._Endpoint):
endpoint_instance = value(self.requester)
... | [
"def",
"_attach_endpoints",
"(",
"self",
")",
":",
"for",
"name",
",",
"value",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"value",
")",
"and",
"issubclass",
"(",
"value",
",",
"self",
".",
"_Endpoi... | 69.611111 | 29.388889 |
def addAccount(self, username, domain, password, avatars=None,
protocol=u'email', disabled=0, internal=False,
verified=True):
"""
Create a user account, add it to this LoginBase, and return it.
This method must be called within a transaction in my store.
... | [
"def",
"addAccount",
"(",
"self",
",",
"username",
",",
"domain",
",",
"password",
",",
"avatars",
"=",
"None",
",",
"protocol",
"=",
"u'email'",
",",
"disabled",
"=",
"0",
",",
"internal",
"=",
"False",
",",
"verified",
"=",
"True",
")",
":",
"# unico... | 38.463768 | 20.811594 |
def get_key_name(self, environ, response_interception, exception=None):
"""Get the timer key name.
:param environ: wsgi environment
:type environ: dict
:param response_interception: dictionary in form
{'status': '<response status>', 'response_headers': [<response headers], '... | [
"def",
"get_key_name",
"(",
"self",
",",
"environ",
",",
"response_interception",
",",
"exception",
"=",
"None",
")",
":",
"status",
"=",
"response_interception",
".",
"get",
"(",
"'status'",
")",
"status_code",
"=",
"status",
".",
"split",
"(",
")",
"[",
... | 49.652174 | 24.130435 |
def limit(self, max=30):
""" The speed limit for a boid.
Boids can momentarily go very fast,
something that is impossible for real animals.
"""
if abs(self.vx) > max:
self.vx = self.vx/abs(self.vx)*max
if abs(self.vy) > max... | [
"def",
"limit",
"(",
"self",
",",
"max",
"=",
"30",
")",
":",
"if",
"abs",
"(",
"self",
".",
"vx",
")",
">",
"max",
":",
"self",
".",
"vx",
"=",
"self",
".",
"vx",
"/",
"abs",
"(",
"self",
".",
"vx",
")",
"*",
"max",
"if",
"abs",
"(",
"se... | 28.933333 | 13.733333 |
def not_(self):
''' Negates this instance's query expression using MongoDB's ``$not``
operator
**Example**: ``(User.name == 'Jeff').not_()``
.. note:: Another usage is via an operator, but parens are needed
to get past precedence issues: ``~ (User.name == 'J... | [
"def",
"not_",
"(",
"self",
")",
":",
"ret_obj",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"obj",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"ret_obj",
"[",
"k",
"]",
"=",
"{",
"'$... | 34.034483 | 20.517241 |
def hook():
"""Install or remove GitHub webhook."""
repo_id = request.json['id']
github = GitHubAPI(user_id=current_user.id)
repos = github.account.extra_data['repos']
if repo_id not in repos:
abort(404)
if request.method == 'DELETE':
try:
if github.remove_hook(rep... | [
"def",
"hook",
"(",
")",
":",
"repo_id",
"=",
"request",
".",
"json",
"[",
"'id'",
"]",
"github",
"=",
"GitHubAPI",
"(",
"user_id",
"=",
"current_user",
".",
"id",
")",
"repos",
"=",
"github",
".",
"account",
".",
"extra_data",
"[",
"'repos'",
"]",
"... | 26.6 | 18.633333 |
def top_class(self):
"""reference to a parent class, which contains this class and defined
within a namespace
if this class is defined under a namespace, self will be returned"""
curr = self
parent = self.parent
while isinstance(parent, class_t):
curr = paren... | [
"def",
"top_class",
"(",
"self",
")",
":",
"curr",
"=",
"self",
"parent",
"=",
"self",
".",
"parent",
"while",
"isinstance",
"(",
"parent",
",",
"class_t",
")",
":",
"curr",
"=",
"parent",
"parent",
"=",
"parent",
".",
"parent",
"return",
"curr"
] | 33.272727 | 13.727273 |
def reduce_operators(source):
"""
Remove spaces between operators in *source* and returns the result.
Example::
def foo(foo, bar, blah):
test = "This is a %s" % foo
Will become::
def foo(foo,bar,blah):
test="This is a %s"%foo
.. note::
Also remov... | [
"def",
"reduce_operators",
"(",
"source",
")",
":",
"io_obj",
"=",
"io",
".",
"StringIO",
"(",
"source",
")",
"prev_tok",
"=",
"None",
"out_tokens",
"=",
"[",
"]",
"out",
"=",
"\"\"",
"last_lineno",
"=",
"-",
"1",
"last_col",
"=",
"0",
"nl_types",
"=",... | 37.291667 | 17.041667 |
def set_list(self, mutagen_file, values):
"""Set all values for the field using this style. `values`
should be an iterable.
"""
self.store(mutagen_file, [self.serialize(value) for value in values]) | [
"def",
"set_list",
"(",
"self",
",",
"mutagen_file",
",",
"values",
")",
":",
"self",
".",
"store",
"(",
"mutagen_file",
",",
"[",
"self",
".",
"serialize",
"(",
"value",
")",
"for",
"value",
"in",
"values",
"]",
")"
] | 45 | 9.6 |
def is_multisig_script(script, blockchain='bitcoin', **blockchain_opts):
"""
Is the given script a multisig script?
"""
if blockchain == 'bitcoin':
return btc_is_multisig_script(script, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) | [
"def",
"is_multisig_script",
"(",
"script",
",",
"blockchain",
"=",
"'bitcoin'",
",",
"*",
"*",
"blockchain_opts",
")",
":",
"if",
"blockchain",
"==",
"'bitcoin'",
":",
"return",
"btc_is_multisig_script",
"(",
"script",
",",
"*",
"*",
"blockchain_opts",
")",
"... | 37.75 | 16 |
def _post_deactivate_injection(self):
"""
Injects functions after the deactivation routine of child classes got called
:return: None
"""
# Lets be sure that active is really set to false.
self.active = False
self.app.signals.send("plugin_deactivate_post", self)
... | [
"def",
"_post_deactivate_injection",
"(",
"self",
")",
":",
"# Lets be sure that active is really set to false.",
"self",
".",
"active",
"=",
"False",
"self",
".",
"app",
".",
"signals",
".",
"send",
"(",
"\"plugin_deactivate_post\"",
",",
"self",
")",
"# After all re... | 54 | 24.615385 |
def user_info(self, username):
"""
Get info of a specific user.
:param username: the username of the user to get info about
:return:
"""
request_url = "{}/api/0/user/{}".format(self.instance, username)
return_value = self._call_api(request_url)
return re... | [
"def",
"user_info",
"(",
"self",
",",
"username",
")",
":",
"request_url",
"=",
"\"{}/api/0/user/{}\"",
".",
"format",
"(",
"self",
".",
"instance",
",",
"username",
")",
"return_value",
"=",
"self",
".",
"_call_api",
"(",
"request_url",
")",
"return",
"retu... | 29.090909 | 18.181818 |
def build_agency(relation, nodes):
"""Extract agency information."""
# TODO: find out the operator for routes without operator tag.
# See: http://wiki.openstreetmap.org/wiki/Key:operator
# Quote from the above link:
#
# If the vast majority of a certain object in an area is operated by a cert... | [
"def",
"build_agency",
"(",
"relation",
",",
"nodes",
")",
":",
"# TODO: find out the operator for routes without operator tag.",
"# See: http://wiki.openstreetmap.org/wiki/Key:operator",
"# Quote from the above link:",
"#",
"# If the vast majority of a certain object in an area is operat... | 43.85 | 29 |
def display_the_graphic_connection(self):
"""
The following permits to attribute the function "display_the_graphic" to the slider.
Because, to make a connection, we can not have parameters for the function, but "display_the_graphic" has some.
"""
self.display_the_graphic(self.num... | [
"def",
"display_the_graphic_connection",
"(",
"self",
")",
":",
"self",
".",
"display_the_graphic",
"(",
"self",
".",
"num_line",
",",
"self",
".",
"wavelength",
",",
"self",
".",
"data_wanted",
",",
"self",
".",
"information",
")"
] | 62.333333 | 32 |
def add_account_certificate(self, account_id, body, **kwargs): # noqa: E501
"""Upload new trusted certificate. # noqa: E501
An endpoint for uploading new trusted certificates. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/trusted-certificates -d {\"nam... | [
"def",
"add_account_certificate",
"(",
"self",
",",
"account_id",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"retur... | 67 | 40.5 |
def distort(value):
"""
Distorts a string by randomly replacing characters in it.
:param value: a string to distort.
:return: a distored string.
"""
value = value.lower()
if (RandomBoolean.chance(1, 5)):
value = value[0:1].upper() + value[1:]
... | [
"def",
"distort",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"if",
"(",
"RandomBoolean",
".",
"chance",
"(",
"1",
",",
"5",
")",
")",
":",
"value",
"=",
"value",
"[",
"0",
":",
"1",
"]",
".",
"upper",
"(",
")",
"+"... | 24.294118 | 17.941176 |
def unify_ips():
"""
Unifies the currently saved IPs.
Unification is based on last IP segment.
So if there are is e.g. 192.168.128.121 and 192.168.128.122 tthey will be merged to 192.168.128.121.
This is a little aggressive but the spammers are aggressive, too.
:return: n... | [
"def",
"unify_ips",
"(",
")",
":",
"processed_ips",
"=",
"0",
"ips",
"=",
"{",
"}",
"# query for the IPs, also includes the starred IPs",
"for",
"ip",
"in",
"IP",
".",
"objects",
".",
"raw",
"(",
"'select distinct a.id, a.seg_0, a.seg_1, a.seg_2 '",
"'from ip_assembler_... | 36.756098 | 19.341463 |
def set_webhook(self, webhook_path: Optional[str] = None, request_handler: Any = WebhookRequestHandler,
route_name: str = DEFAULT_ROUTE_NAME, web_app: Optional[Application] = None):
"""
Set webhook for bot
:param webhook_path: Optional[str] (default: None)
:param req... | [
"def",
"set_webhook",
"(",
"self",
",",
"webhook_path",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"request_handler",
":",
"Any",
"=",
"WebhookRequestHandler",
",",
"route_name",
":",
"str",
"=",
"DEFAULT_ROUTE_NAME",
",",
"web_app",
":",
"Optional",
... | 52.538462 | 28.846154 |
def send_command(
self, command, callback=True, command_type=QRTPacketType.PacketCommand
):
""" Sends commands to QTM """
if self.transport is not None:
cmd_length = len(command)
LOG.debug("S: %s", command)
self.transport.write(
struct.pack... | [
"def",
"send_command",
"(",
"self",
",",
"command",
",",
"callback",
"=",
"True",
",",
"command_type",
"=",
"QRTPacketType",
".",
"PacketCommand",
")",
":",
"if",
"self",
".",
"transport",
"is",
"not",
"None",
":",
"cmd_length",
"=",
"len",
"(",
"command",... | 31.6 | 14.52 |
def get_scms_for_path(path):
"""
Returns all scm's found at the given path. If no scm is recognized
- empty list is returned.
:param path: path to directory which should be checked. May be callable.
:raises VCSError: if given ``path`` is not a directory
"""
from vcs.backends import get_bac... | [
"def",
"get_scms_for_path",
"(",
"path",
")",
":",
"from",
"vcs",
".",
"backends",
"import",
"get_backend",
"if",
"hasattr",
"(",
"path",
",",
"'__call__'",
")",
":",
"path",
"=",
"path",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"... | 29.588235 | 17.294118 |
def main():
"""
Entry point for GNS3 server
"""
if not sys.platform.startswith("win"):
if "--daemon" in sys.argv:
daemonize()
from gns3server.run import run
run() | [
"def",
"main",
"(",
")",
":",
"if",
"not",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"if",
"\"--daemon\"",
"in",
"sys",
".",
"argv",
":",
"daemonize",
"(",
")",
"from",
"gns3server",
".",
"run",
"import",
"run",
"run",
"(",... | 19.8 | 14 |
def draw_plot(self, metrics, labels=None, ylabel=""):
"""
metrics: One or more metrics parameters. Each represents the history
of one metric.
"""
metrics = metrics if isinstance(metrics, list) else [metrics]
# Loop through metrics
title = ""
for i, m i... | [
"def",
"draw_plot",
"(",
"self",
",",
"metrics",
",",
"labels",
"=",
"None",
",",
"ylabel",
"=",
"\"\"",
")",
":",
"metrics",
"=",
"metrics",
"if",
"isinstance",
"(",
"metrics",
",",
"list",
")",
"else",
"[",
"metrics",
"]",
"# Loop through metrics",
"ti... | 43.166667 | 15.5 |
def setVehicleClass(self, typeID, clazz):
"""setVehicleClass(string, string) -> None
Sets the class of vehicles of this type.
"""
self._connection._sendStringCmd(
tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_VEHICLECLASS, typeID, clazz) | [
"def",
"setVehicleClass",
"(",
"self",
",",
"typeID",
",",
"clazz",
")",
":",
"self",
".",
"_connection",
".",
"_sendStringCmd",
"(",
"tc",
".",
"CMD_SET_VEHICLETYPE_VARIABLE",
",",
"tc",
".",
"VAR_VEHICLECLASS",
",",
"typeID",
",",
"clazz",
")"
] | 38.571429 | 12.714286 |
def dispatch(self, request):
"""
View to handle final steps of OAuth based authentication where the user
gets redirected back to from the service provider
"""
login_done_url = reverse(self.adapter.provider_id + "_callback")
client = self._get_client(request, login_done_ur... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
")",
":",
"login_done_url",
"=",
"reverse",
"(",
"self",
".",
"adapter",
".",
"provider_id",
"+",
"\"_callback\"",
")",
"client",
"=",
"self",
".",
"_get_client",
"(",
"request",
",",
"login_done_url",
")",
"... | 43.236842 | 13.657895 |
def addStep(self, callback, *args, **kwargs):
'''
Add rollback step with optional arguments. If a rollback is
triggered, each step is called in LIFO order.
'''
self.steps.append((callback, args, kwargs)) | [
"def",
"addStep",
"(",
"self",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"steps",
".",
"append",
"(",
"(",
"callback",
",",
"args",
",",
"kwargs",
")",
")"
] | 36.333333 | 18.333333 |
def clean_file(in_file, data, prefix="", bedprep_dir=None, simple=None):
"""Prepare a clean sorted input BED file without headers
"""
# Remove non-ascii characters. Used in coverage analysis, to support JSON code in one column
# and be happy with sambamba:
simple = "iconv -c -f utf-8 -t ascii | se... | [
"def",
"clean_file",
"(",
"in_file",
",",
"data",
",",
"prefix",
"=",
"\"\"",
",",
"bedprep_dir",
"=",
"None",
",",
"simple",
"=",
"None",
")",
":",
"# Remove non-ascii characters. Used in coverage analysis, to support JSON code in one column",
"# and be happy with sambam... | 57.833333 | 23.733333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.