repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
minhhoit/yacms | yacms/twitter/admin.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/twitter/admin.py#L52-L62 | def save_model(self, request, obj, form, change):
"""
Sends a tweet with the title/short_url if applicable.
"""
super(TweetableAdminMixin, self).save_model(request, obj, form, change)
if Api and request.POST.get("send_tweet", False):
auth_settings = get_auth_settings(... | [
"def",
"save_model",
"(",
"self",
",",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
":",
"super",
"(",
"TweetableAdminMixin",
",",
"self",
")",
".",
"save_model",
"(",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
"if",
"Api",
"a... | Sends a tweet with the title/short_url if applicable. | [
"Sends",
"a",
"tweet",
"with",
"the",
"title",
"/",
"short_url",
"if",
"applicable",
"."
] | python | train | 46.818182 |
pyQode/pyqode.core | pyqode/core/widgets/splittable_tab_widget.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L749-L757 | def add_context_action(self, action):
"""
Adds a custom context menu action
:param action: action to add.
"""
self.main_tab_widget.context_actions.append(action)
for child_splitter in self.child_splitters:
child_splitter.add_context_action(action) | [
"def",
"add_context_action",
"(",
"self",
",",
"action",
")",
":",
"self",
".",
"main_tab_widget",
".",
"context_actions",
".",
"append",
"(",
"action",
")",
"for",
"child_splitter",
"in",
"self",
".",
"child_splitters",
":",
"child_splitter",
".",
"add_context_... | Adds a custom context menu action
:param action: action to add. | [
"Adds",
"a",
"custom",
"context",
"menu",
"action"
] | python | train | 33.333333 |
Thermondo/django-heroku-connect | heroku_connect/models.py | https://github.com/Thermondo/django-heroku-connect/blob/f390e0fbf256ee79b30bb88f9a8c9576c6c8d9b5/heroku_connect/models.py#L173-L212 | def capture_update_from_model(cls, table_name, record_id, *, update_fields=()):
"""
Create a fresh update record from the current model state in the database.
For read-write connected models, this will lead to the attempted update of the values of
a corresponding object in Salesforce.
... | [
"def",
"capture_update_from_model",
"(",
"cls",
",",
"table_name",
",",
"record_id",
",",
"*",
",",
"update_fields",
"=",
"(",
")",
")",
":",
"include_cols",
"=",
"(",
")",
"if",
"update_fields",
":",
"model_cls",
"=",
"get_connected_model_for_table_name",
"(",
... | Create a fresh update record from the current model state in the database.
For read-write connected models, this will lead to the attempted update of the values of
a corresponding object in Salesforce.
Args:
table_name (str): The name of the table backing the connected model (witho... | [
"Create",
"a",
"fresh",
"update",
"record",
"from",
"the",
"current",
"model",
"state",
"in",
"the",
"database",
"."
] | python | train | 43.5 |
crocs-muni/roca | roca/detect.py | https://github.com/crocs-muni/roca/blob/74ad6ce63c428d83dcffce9c5e26ef7b9e30faa5/roca/detect.py#L132-L147 | def defvalkey(js, key, default=None, take_none=True):
"""
Returns js[key] if set, otherwise default. Note js[key] can be None.
:param js:
:param key:
:param default:
:param take_none:
:return:
"""
if js is None:
return default
if key not in js:
return default
... | [
"def",
"defvalkey",
"(",
"js",
",",
"key",
",",
"default",
"=",
"None",
",",
"take_none",
"=",
"True",
")",
":",
"if",
"js",
"is",
"None",
":",
"return",
"default",
"if",
"key",
"not",
"in",
"js",
":",
"return",
"default",
"if",
"js",
"[",
"key",
... | Returns js[key] if set, otherwise default. Note js[key] can be None.
:param js:
:param key:
:param default:
:param take_none:
:return: | [
"Returns",
"js",
"[",
"key",
"]",
"if",
"set",
"otherwise",
"default",
".",
"Note",
"js",
"[",
"key",
"]",
"can",
"be",
"None",
".",
":",
"param",
"js",
":",
":",
"param",
"key",
":",
":",
"param",
"default",
":",
":",
"param",
"take_none",
":",
... | python | train | 24 |
backbohne/docx-xslt | docxxslt/engines.py | https://github.com/backbohne/docx-xslt/blob/d4cc76776a75b8213660c3c1717d42afe5189e15/docxxslt/engines.py#L63-L91 | def xsl_elements(self):
"""Find all "XSL" styled runs, normalize related paragraph and returns list of XslElements"""
def append_xsl_elements(xsl_elements, r, xsl):
if r is not None:
r.xpath('.//w:t', namespaces=self.namespaces)[0].text = xsl
xe = XslElement... | [
"def",
"xsl_elements",
"(",
"self",
")",
":",
"def",
"append_xsl_elements",
"(",
"xsl_elements",
",",
"r",
",",
"xsl",
")",
":",
"if",
"r",
"is",
"not",
"None",
":",
"r",
".",
"xpath",
"(",
"'.//w:t'",
",",
"namespaces",
"=",
"self",
".",
"namespaces",... | Find all "XSL" styled runs, normalize related paragraph and returns list of XslElements | [
"Find",
"all",
"XSL",
"styled",
"runs",
"normalize",
"related",
"paragraph",
"and",
"returns",
"list",
"of",
"XslElements"
] | python | train | 46.827586 |
ultrabug/py3status | py3status/module.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/module.py#L270-L301 | def set_updated(self):
"""
Mark the module as updated.
We check if the actual content has changed and if so we trigger an
update in py3status.
"""
# get latest output
output = []
for method in self.methods.values():
data = method["last_output"]... | [
"def",
"set_updated",
"(",
"self",
")",
":",
"# get latest output",
"output",
"=",
"[",
"]",
"for",
"method",
"in",
"self",
".",
"methods",
".",
"values",
"(",
")",
":",
"data",
"=",
"method",
"[",
"\"last_output\"",
"]",
"if",
"isinstance",
"(",
"data",... | Mark the module as updated.
We check if the actual content has changed and if so we trigger an
update in py3status. | [
"Mark",
"the",
"module",
"as",
"updated",
".",
"We",
"check",
"if",
"the",
"actual",
"content",
"has",
"changed",
"and",
"if",
"so",
"we",
"trigger",
"an",
"update",
"in",
"py3status",
"."
] | python | train | 41.03125 |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L141-L146 | def projScatter(lon, lat, **kwargs):
"""
Create a scatter plot on HEALPix projected axes.
Inputs: lon (deg), lat (deg)
"""
hp.projscatter(lon, lat, lonlat=True, **kwargs) | [
"def",
"projScatter",
"(",
"lon",
",",
"lat",
",",
"*",
"*",
"kwargs",
")",
":",
"hp",
".",
"projscatter",
"(",
"lon",
",",
"lat",
",",
"lonlat",
"=",
"True",
",",
"*",
"*",
"kwargs",
")"
] | Create a scatter plot on HEALPix projected axes.
Inputs: lon (deg), lat (deg) | [
"Create",
"a",
"scatter",
"plot",
"on",
"HEALPix",
"projected",
"axes",
".",
"Inputs",
":",
"lon",
"(",
"deg",
")",
"lat",
"(",
"deg",
")"
] | python | train | 30.833333 |
rytilahti/python-songpal | songpal/device.py | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L304-L307 | async def set_custom_eq(self, target: str, value: str) -> None:
"""Set custom EQ settings."""
params = {"settings": [{"target": target, "value": value}]}
return await self.services["audio"]["setCustomEqualizerSettings"](params) | [
"async",
"def",
"set_custom_eq",
"(",
"self",
",",
"target",
":",
"str",
",",
"value",
":",
"str",
")",
"->",
"None",
":",
"params",
"=",
"{",
"\"settings\"",
":",
"[",
"{",
"\"target\"",
":",
"target",
",",
"\"value\"",
":",
"value",
"}",
"]",
"}",
... | Set custom EQ settings. | [
"Set",
"custom",
"EQ",
"settings",
"."
] | python | train | 62 |
wavycloud/pyboto3 | pyboto3/mturk.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/mturk.py#L195-L442 | def create_hit(MaxAssignments=None, AutoApprovalDelayInSeconds=None, LifetimeInSeconds=None, AssignmentDurationInSeconds=None, Reward=None, Title=None, Keywords=None, Description=None, Question=None, RequesterAnnotation=None, QualificationRequirements=None, UniqueRequestToken=None, AssignmentReviewPolicy=None, HITRevie... | [
"def",
"create_hit",
"(",
"MaxAssignments",
"=",
"None",
",",
"AutoApprovalDelayInSeconds",
"=",
"None",
",",
"LifetimeInSeconds",
"=",
"None",
",",
"AssignmentDurationInSeconds",
"=",
"None",
",",
"Reward",
"=",
"None",
",",
"Title",
"=",
"None",
",",
"Keywords... | The CreateHIT operation creates a new Human Intelligence Task (HIT). The new HIT is made available for Workers to find and accept on the Amazon Mechanical Turk website.
This operation allows you to specify a new HIT by passing in values for the properties of the HIT, such as its title, reward amount and number of a... | [
"The",
"CreateHIT",
"operation",
"creates",
"a",
"new",
"Human",
"Intelligence",
"Task",
"(",
"HIT",
")",
".",
"The",
"new",
"HIT",
"is",
"made",
"available",
"for",
"Workers",
"to",
"find",
"and",
"accept",
"on",
"the",
"Amazon",
"Mechanical",
"Turk",
"we... | python | train | 66.282258 |
jeffknupp/sandman2 | sandman2/app.py | https://github.com/jeffknupp/sandman2/blob/1ce21d6f7a6df77fa96fab694b0f9bb8469c166b/sandman2/app.py#L95-L123 | def register_service(cls, primary_key_type):
"""Register an API service endpoint.
:param cls: The class to register
:param str primary_key_type: The type (as a string) of the primary_key
field
"""
view_func = cls.as_view(cls.__name__.lower()) # pylint: disable=no-m... | [
"def",
"register_service",
"(",
"cls",
",",
"primary_key_type",
")",
":",
"view_func",
"=",
"cls",
".",
"as_view",
"(",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
")",
"# pylint: disable=no-member",
"methods",
"=",
"set",
"(",
"cls",
".",
"__model__",
... | Register an API service endpoint.
:param cls: The class to register
:param str primary_key_type: The type (as a string) of the primary_key
field | [
"Register",
"an",
"API",
"service",
"endpoint",
"."
] | python | train | 41.724138 |
wal-e/wal-e | wal_e/tar_partition.py | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/tar_partition.py#L187-L228 | def cat_extract(tar, member, targetpath):
"""Extract a regular file member using cat for async-like I/O
Mostly adapted from tarfile.py.
"""
assert member.isreg()
# Fetch the TarInfo object for the given name and build the
# destination pathname, replacing forward slashes to platform
# spe... | [
"def",
"cat_extract",
"(",
"tar",
",",
"member",
",",
"targetpath",
")",
":",
"assert",
"member",
".",
"isreg",
"(",
")",
"# Fetch the TarInfo object for the given name and build the",
"# destination pathname, replacing forward slashes to platform",
"# specific separators.",
"t... | Extract a regular file member using cat for async-like I/O
Mostly adapted from tarfile.py. | [
"Extract",
"a",
"regular",
"file",
"member",
"using",
"cat",
"for",
"async",
"-",
"like",
"I",
"/",
"O"
] | python | train | 33.047619 |
BeyondTheClouds/enoslib | enoslib/api.py | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L966-L977 | def _merge_constraints(constraints, overrides):
"""Merge the constraints avoiding duplicates
Change constraints in place.
"""
for o in overrides:
i = 0
while i < len(constraints):
c = constraints[i]
if _same(o, c):
constraints[i].update(o)
... | [
"def",
"_merge_constraints",
"(",
"constraints",
",",
"overrides",
")",
":",
"for",
"o",
"in",
"overrides",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"constraints",
")",
":",
"c",
"=",
"constraints",
"[",
"i",
"]",
"if",
"_same",
"(",
"o",
... | Merge the constraints avoiding duplicates
Change constraints in place. | [
"Merge",
"the",
"constraints",
"avoiding",
"duplicates",
"Change",
"constraints",
"in",
"place",
"."
] | python | train | 28.666667 |
Cadene/pretrained-models.pytorch | pretrainedmodels/models/torchvision_models.py | https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L205-L214 | def densenet121(num_classes=1000, pretrained='imagenet'):
r"""Densenet-121 model from
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
"""
model = models.densenet121(pretrained=False)
if pretrained is not None:
settings = pretrained_settings['densenet121'][... | [
"def",
"densenet121",
"(",
"num_classes",
"=",
"1000",
",",
"pretrained",
"=",
"'imagenet'",
")",
":",
"model",
"=",
"models",
".",
"densenet121",
"(",
"pretrained",
"=",
"False",
")",
"if",
"pretrained",
"is",
"not",
"None",
":",
"settings",
"=",
"pretrai... | r"""Densenet-121 model from
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` | [
"r",
"Densenet",
"-",
"121",
"model",
"from",
"Densely",
"Connected",
"Convolutional",
"Networks",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1608",
".",
"06993",
".",
"pdf",
">"
] | python | train | 43.7 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/broker.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/broker.py#L152-L174 | def get_preferred_partition(self, broker, sibling_distance):
"""The preferred partition belongs to the topic with the minimum
(also negative) distance between destination and source.
:param broker: Destination broker
:param sibling_distance: dict {topic: distance} negative distance sho... | [
"def",
"get_preferred_partition",
"(",
"self",
",",
"broker",
",",
"sibling_distance",
")",
":",
"# Only partitions not having replica in broker are valid",
"# Get best fit partition, based on avoiding partition from same topic",
"# and partition with least siblings in destination-broker.",
... | The preferred partition belongs to the topic with the minimum
(also negative) distance between destination and source.
:param broker: Destination broker
:param sibling_distance: dict {topic: distance} negative distance should
mean that destination broker has got less partition of a... | [
"The",
"preferred",
"partition",
"belongs",
"to",
"the",
"topic",
"with",
"the",
"minimum",
"(",
"also",
"negative",
")",
"distance",
"between",
"destination",
"and",
"source",
"."
] | python | train | 46.782609 |
OnroerendErfgoed/oe_utils | oe_utils/audit.py | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/audit.py#L40-L94 | def audit(**kwargs):
"""
use this decorator to audit an operation
"""
def wrap(fn):
@functools.wraps(fn)
def advice(parent_object, *args, **kw):
request = parent_object.request
wijziging = request.audit_manager.create_revision()
result = fn(parent_o... | [
"def",
"audit",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrap",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"advice",
"(",
"parent_object",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"request",
"=",
"pare... | use this decorator to audit an operation | [
"use",
"this",
"decorator",
"to",
"audit",
"an",
"operation"
] | python | train | 39.109091 |
konstantinstadler/pymrio | pymrio/core/mriosystem.py | https://github.com/konstantinstadler/pymrio/blob/d764aa0dd2150200e867a9713a98ddae203e12d4/pymrio/core/mriosystem.py#L1667-L1684 | def reset_all_to_coefficients(self):
""" Resets the IOSystem and all extensions to coefficients.
This method calls reset_to_coefficients for the IOSystem and for
all Extensions in the system
Note
-----
The system can not be reconstructed after this steps
becaus... | [
"def",
"reset_all_to_coefficients",
"(",
"self",
")",
":",
"self",
".",
"reset_to_coefficients",
"(",
")",
"[",
"ee",
".",
"reset_to_coefficients",
"(",
")",
"for",
"ee",
"in",
"self",
".",
"get_extensions",
"(",
"data",
"=",
"True",
")",
"]",
"self",
".",... | Resets the IOSystem and all extensions to coefficients.
This method calls reset_to_coefficients for the IOSystem and for
all Extensions in the system
Note
-----
The system can not be reconstructed after this steps
because all absolute data is removed. Save the Y data i... | [
"Resets",
"the",
"IOSystem",
"and",
"all",
"extensions",
"to",
"coefficients",
"."
] | python | train | 34.333333 |
sibirrer/lenstronomy | lenstronomy/LensModel/Profiles/dipole.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/Profiles/dipole.py#L102-L108 | def angle(self, center1_x, center1_y, center2_x, center2_y):
"""
compute the rotation angle of the dipole
:return:
"""
phi_G = np.arctan2(center2_y - center1_y, center2_x - center1_x)
return phi_G | [
"def",
"angle",
"(",
"self",
",",
"center1_x",
",",
"center1_y",
",",
"center2_x",
",",
"center2_y",
")",
":",
"phi_G",
"=",
"np",
".",
"arctan2",
"(",
"center2_y",
"-",
"center1_y",
",",
"center2_x",
"-",
"center1_x",
")",
"return",
"phi_G"
] | compute the rotation angle of the dipole
:return: | [
"compute",
"the",
"rotation",
"angle",
"of",
"the",
"dipole",
":",
"return",
":"
] | python | train | 34 |
meejah/txtorcon | txtorcon/circuit.py | https://github.com/meejah/txtorcon/blob/14053b95adf0b4bd9dd9c317bece912a26578a93/txtorcon/circuit.py#L288-L326 | def stream_via(self, reactor, host, port,
socks_endpoint,
use_tls=False):
"""
This returns an `IStreamClientEndpoint`_ that will connect to
the given ``host``, ``port`` via Tor -- and via this
parciular circuit.
We match the streams up using... | [
"def",
"stream_via",
"(",
"self",
",",
"reactor",
",",
"host",
",",
"port",
",",
"socks_endpoint",
",",
"use_tls",
"=",
"False",
")",
":",
"from",
".",
"endpoints",
"import",
"TorClientEndpoint",
"ep",
"=",
"TorClientEndpoint",
"(",
"host",
",",
"port",
",... | This returns an `IStreamClientEndpoint`_ that will connect to
the given ``host``, ``port`` via Tor -- and via this
parciular circuit.
We match the streams up using their source-ports, so even if
there are many streams in-flight to the same destination they
will align correctly. ... | [
"This",
"returns",
"an",
"IStreamClientEndpoint",
"_",
"that",
"will",
"connect",
"to",
"the",
"given",
"host",
"port",
"via",
"Tor",
"--",
"and",
"via",
"this",
"parciular",
"circuit",
"."
] | python | train | 43.333333 |
python-useful-helpers/advanced-descriptors | advanced_descriptors/log_on_access.py | https://github.com/python-useful-helpers/advanced-descriptors/blob/17ee4a35b3bfcb4adf4ed2f41e75c4c6b71cb003/advanced_descriptors/log_on_access.py#L202-L216 | def _get_logger_for_instance(self, instance: typing.Any) -> logging.Logger:
"""Get logger for log calls.
:param instance: Owner class instance. Filled only if instance created, else None.
:type instance: typing.Optional[owner]
:return: logger instance
:rtype: logging.Logger
... | [
"def",
"_get_logger_for_instance",
"(",
"self",
",",
"instance",
":",
"typing",
".",
"Any",
")",
"->",
"logging",
".",
"Logger",
":",
"if",
"self",
".",
"logger",
"is",
"not",
"None",
":",
"# pylint: disable=no-else-return",
"return",
"self",
".",
"logger",
... | Get logger for log calls.
:param instance: Owner class instance. Filled only if instance created, else None.
:type instance: typing.Optional[owner]
:return: logger instance
:rtype: logging.Logger | [
"Get",
"logger",
"for",
"log",
"calls",
"."
] | python | test | 45.2 |
jgorset/django-respite | respite/formats.py | https://github.com/jgorset/django-respite/blob/719469d11baf91d05917bab1623bd82adc543546/respite/formats.py#L69-L79 | def find_by_extension(extension):
"""
Find and return a format by extension.
:param extension: A string describing the extension of the format.
"""
for format in FORMATS:
if extension in format.extensions:
return format
raise UnknownFormat('No format found with extension "%... | [
"def",
"find_by_extension",
"(",
"extension",
")",
":",
"for",
"format",
"in",
"FORMATS",
":",
"if",
"extension",
"in",
"format",
".",
"extensions",
":",
"return",
"format",
"raise",
"UnknownFormat",
"(",
"'No format found with extension \"%s\"'",
"%",
"extension",
... | Find and return a format by extension.
:param extension: A string describing the extension of the format. | [
"Find",
"and",
"return",
"a",
"format",
"by",
"extension",
"."
] | python | train | 29.636364 |
xolox/python-vcs-repo-mgr | vcs_repo_mgr/__init__.py | https://github.com/xolox/python-vcs-repo-mgr/blob/fdad2441a3e7ba5deeeddfa1c2f5ebc00c393aed/vcs_repo_mgr/__init__.py#L935-L968 | def tags(self):
"""
A dictionary that maps tag names to :class:`Revision` objects.
Here's an example based on a mirror of the git project's repository:
>>> from pprint import pprint
>>> from vcs_repo_mgr.backends.git import GitRepo
>>> repository = GitRepo(remote='https... | [
"def",
"tags",
"(",
"self",
")",
":",
"# Make sure the local repository exists.",
"self",
".",
"create",
"(",
")",
"# Create a mapping of tag names to revisions.",
"return",
"dict",
"(",
"(",
"r",
".",
"tag",
",",
"r",
")",
"for",
"r",
"in",
"self",
".",
"find... | A dictionary that maps tag names to :class:`Revision` objects.
Here's an example based on a mirror of the git project's repository:
>>> from pprint import pprint
>>> from vcs_repo_mgr.backends.git import GitRepo
>>> repository = GitRepo(remote='https://github.com/git/git.git')
... | [
"A",
"dictionary",
"that",
"maps",
"tag",
"names",
"to",
":",
"class",
":",
"Revision",
"objects",
"."
] | python | train | 49.852941 |
hyperledger/sawtooth-core | cli/sawtooth_cli/network_command/compare.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/cli/sawtooth_cli/network_command/compare.py#L442-L459 | def print_block_num_row(block_num, cliques, next_cliques):
"""Print out a row of padding and a row with the block number. Includes
the branches prior to this block number."""
n_cliques = len(cliques)
if n_cliques == 0:
print('| {}'.format(block_num))
return
def mapper(clique):
... | [
"def",
"print_block_num_row",
"(",
"block_num",
",",
"cliques",
",",
"next_cliques",
")",
":",
"n_cliques",
"=",
"len",
"(",
"cliques",
")",
"if",
"n_cliques",
"==",
"0",
":",
"print",
"(",
"'| {}'",
".",
"format",
"(",
"block_num",
")",
")",
"return",
... | Print out a row of padding and a row with the block number. Includes
the branches prior to this block number. | [
"Print",
"out",
"a",
"row",
"of",
"padding",
"and",
"a",
"row",
"with",
"the",
"block",
"number",
".",
"Includes",
"the",
"branches",
"prior",
"to",
"this",
"block",
"number",
"."
] | python | train | 33.111111 |
treycucco/pyebnf | pyebnf/compiler.py | https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/compiler.py#L396-L406 | def _ast_op_concat_to_code(self, opr, *, ignore_whitespace, **kwargs):
"""Convert an AST concatenate op to python source code."""
hoist_target = OP_CONCAT if ignore_whitespace else OP_WS_CONCAT
operands = self._hoist_operands(opr.operands, lambda t: isinstance(t, OptreeNode) and t.opnode.operator is hoist_t... | [
"def",
"_ast_op_concat_to_code",
"(",
"self",
",",
"opr",
",",
"*",
",",
"ignore_whitespace",
",",
"*",
"*",
"kwargs",
")",
":",
"hoist_target",
"=",
"OP_CONCAT",
"if",
"ignore_whitespace",
"else",
"OP_WS_CONCAT",
"operands",
"=",
"self",
".",
"_hoist_operands",... | Convert an AST concatenate op to python source code. | [
"Convert",
"an",
"AST",
"concatenate",
"op",
"to",
"python",
"source",
"code",
"."
] | python | test | 53 |
pytroll/satpy | satpy/readers/sar_c_safe.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/sar_c_safe.py#L257-L279 | def interpolate_xarray_linear(xpoints, ypoints, values, shape, chunks=CHUNK_SIZE):
"""Interpolate linearly, generating a dask array."""
from scipy.interpolate.interpnd import (LinearNDInterpolator,
_ndim_coords_from_arrays)
if isinstance(chunks, (list, tuple)):
... | [
"def",
"interpolate_xarray_linear",
"(",
"xpoints",
",",
"ypoints",
",",
"values",
",",
"shape",
",",
"chunks",
"=",
"CHUNK_SIZE",
")",
":",
"from",
"scipy",
".",
"interpolate",
".",
"interpnd",
"import",
"(",
"LinearNDInterpolator",
",",
"_ndim_coords_from_arrays... | Interpolate linearly, generating a dask array. | [
"Interpolate",
"linearly",
"generating",
"a",
"dask",
"array",
"."
] | python | train | 40.73913 |
Pythonity/icon-font-to-png | icon_font_to_png/command_line.py | https://github.com/Pythonity/icon-font-to-png/blob/4851fe15c077402749f843d43fbc10d28f6c655d/icon_font_to_png/command_line.py#L10-L164 | def run(arguments):
"""Main function for command line usage"""
parser = argparse.ArgumentParser(
description="Exports font icons as PNG images."
)
parser.add_argument(
'--list',
action='store_true',
help="list all available icon names and exit"
)
parser.add_argume... | [
"def",
"run",
"(",
"arguments",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Exports font icons as PNG images.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--list'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=... | Main function for command line usage | [
"Main",
"function",
"for",
"command",
"line",
"usage"
] | python | train | 31.883871 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/tailf_confd_monitoring.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/tailf_confd_monitoring.py#L341-L353 | def confd_state_rest_listen_tcp_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
rest = ET.SubElement(confd_state, "rest")
listen = ET.SubElem... | [
"def",
"confd_state_rest_listen_tcp_port",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"confd_state",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"confd-state\"",
",",
"xmlns",
"=",
"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 41.692308 |
hydpy-dev/hydpy | hydpy/auxs/armatools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L257-L263 | def moments(self):
"""The first two time delay weighted statistical moments of the
MA coefficients."""
moment1 = statstools.calc_mean_time(self.delays, self.coefs)
moment2 = statstools.calc_mean_time_deviation(
self.delays, self.coefs, moment1)
return numpy.array([mom... | [
"def",
"moments",
"(",
"self",
")",
":",
"moment1",
"=",
"statstools",
".",
"calc_mean_time",
"(",
"self",
".",
"delays",
",",
"self",
".",
"coefs",
")",
"moment2",
"=",
"statstools",
".",
"calc_mean_time_deviation",
"(",
"self",
".",
"delays",
",",
"self"... | The first two time delay weighted statistical moments of the
MA coefficients. | [
"The",
"first",
"two",
"time",
"delay",
"weighted",
"statistical",
"moments",
"of",
"the",
"MA",
"coefficients",
"."
] | python | train | 47 |
thiagopbueno/pyrddl | pyrddl/rddl.py | https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/rddl.py#L214-L223 | def interm_range_type(self) -> Sequence[str]:
'''The range type of each intermediate fluent in canonical order.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent.
'''
fluents = self.domain.intermediate_fluents
ordering =... | [
"def",
"interm_range_type",
"(",
"self",
")",
"->",
"Sequence",
"[",
"str",
"]",
":",
"fluents",
"=",
"self",
".",
"domain",
".",
"intermediate_fluents",
"ordering",
"=",
"self",
".",
"domain",
".",
"interm_fluent_ordering",
"return",
"self",
".",
"_fluent_ran... | The range type of each intermediate fluent in canonical order.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent. | [
"The",
"range",
"type",
"of",
"each",
"intermediate",
"fluent",
"in",
"canonical",
"order",
"."
] | python | train | 40.4 |
Bystroushaak/pyDHTMLParser | src/dhtmlparser/htmlelement/html_parser.py | https://github.com/Bystroushaak/pyDHTMLParser/blob/4756f93dd048500b038ece2323fe26e46b6bfdea/src/dhtmlparser/htmlelement/html_parser.py#L138-L157 | def _init_tag_params(self, tag, params):
"""
Alternative constructor used when the tag parameters are added to the
HTMLElement (HTMLElement(tag, params)).
This method just creates string and then pass it to the
:meth:`_init_tag`.
Args:
tag (str): HTML tag as... | [
"def",
"_init_tag_params",
"(",
"self",
",",
"tag",
",",
"params",
")",
":",
"self",
".",
"_element",
"=",
"tag",
"self",
".",
"params",
"=",
"params",
"self",
".",
"_parseTagName",
"(",
")",
"self",
".",
"_istag",
"=",
"True",
"self",
".",
"_isendtag"... | Alternative constructor used when the tag parameters are added to the
HTMLElement (HTMLElement(tag, params)).
This method just creates string and then pass it to the
:meth:`_init_tag`.
Args:
tag (str): HTML tag as string.
params (dict): HTML tag parameters as di... | [
"Alternative",
"constructor",
"used",
"when",
"the",
"tag",
"parameters",
"are",
"added",
"to",
"the",
"HTMLElement",
"(",
"HTMLElement",
"(",
"tag",
"params",
"))",
"."
] | python | train | 30.3 |
chrismattmann/tika-python | tika/tika.py | https://github.com/chrismattmann/tika-python/blob/ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a/tika/tika.py#L741-L769 | def checkPortIsOpen(remoteServerHost=ServerHost, port = Port):
'''
Checks if the specified port is open
:param remoteServerHost: the host address
:param port: port which needs to be checked
:return: ``True`` if port is open, ``False`` otherwise
'''
remoteServerIP = socket.gethostbyname(remo... | [
"def",
"checkPortIsOpen",
"(",
"remoteServerHost",
"=",
"ServerHost",
",",
"port",
"=",
"Port",
")",
":",
"remoteServerIP",
"=",
"socket",
".",
"gethostbyname",
"(",
"remoteServerHost",
")",
"try",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".... | Checks if the specified port is open
:param remoteServerHost: the host address
:param port: port which needs to be checked
:return: ``True`` if port is open, ``False`` otherwise | [
"Checks",
"if",
"the",
"specified",
"port",
"is",
"open",
":",
"param",
"remoteServerHost",
":",
"the",
"host",
"address",
":",
"param",
"port",
":",
"port",
"which",
"needs",
"to",
"be",
"checked",
":",
"return",
":",
"True",
"if",
"port",
"is",
"open",... | python | train | 30.206897 |
bast/flanders | cmake/autocmake/configure.py | https://github.com/bast/flanders/blob/792f9eed8511cb553e67a25b6c5ce60fd6ae97bc/cmake/autocmake/configure.py#L14-L33 | def check_cmake_exists(cmake_command):
"""
Check whether CMake is installed. If not, print
informative error message and quits.
"""
from subprocess import Popen, PIPE
p = Popen(
'{0} --version'.format(cmake_command),
shell=True,
stdin=PIPE,
stdout=PIPE)
if no... | [
"def",
"check_cmake_exists",
"(",
"cmake_command",
")",
":",
"from",
"subprocess",
"import",
"Popen",
",",
"PIPE",
"p",
"=",
"Popen",
"(",
"'{0} --version'",
".",
"format",
"(",
"cmake_command",
")",
",",
"shell",
"=",
"True",
",",
"stdin",
"=",
"PIPE",
",... | Check whether CMake is installed. If not, print
informative error message and quits. | [
"Check",
"whether",
"CMake",
"is",
"installed",
".",
"If",
"not",
"print",
"informative",
"error",
"message",
"and",
"quits",
"."
] | python | train | 37.55 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_indicator.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L274-L291 | def occurrence(self, file_name=None, path=None, date=None):
"""Add a file Occurrence.
Args:
file_name (str, optional): The file name for this occurrence.
path (str, optional): The file path for this occurrence.
date (str, optional): The datetime expression for this o... | [
"def",
"occurrence",
"(",
"self",
",",
"file_name",
"=",
"None",
",",
"path",
"=",
"None",
",",
"date",
"=",
"None",
")",
":",
"if",
"self",
".",
"_indicator_data",
".",
"get",
"(",
"'type'",
")",
"!=",
"'File'",
":",
"# Indicator object has no logger to o... | Add a file Occurrence.
Args:
file_name (str, optional): The file name for this occurrence.
path (str, optional): The file path for this occurrence.
date (str, optional): The datetime expression for this occurrence.
Returns:
obj: An instance of Occurrence... | [
"Add",
"a",
"file",
"Occurrence",
"."
] | python | train | 37.333333 |
Nic30/hwtGraph | hwtGraph/elk/fromHwt/utils.py | https://github.com/Nic30/hwtGraph/blob/6b7d4fdd759f263a0fdd2736f02f123e44e4354f/hwtGraph/elk/fromHwt/utils.py#L187-L211 | def _addPort(n: LNode, lp: LPort, intf: Interface,
reverseDirection=False):
"""
add port to LPort for interface
"""
origin = originObjOfPort(intf)
d = intf._direction
d = PortTypeFromDir(d)
if reverseDirection:
d = PortType.opposite(d)
new_lp = LPort(lp, d, lp.side... | [
"def",
"_addPort",
"(",
"n",
":",
"LNode",
",",
"lp",
":",
"LPort",
",",
"intf",
":",
"Interface",
",",
"reverseDirection",
"=",
"False",
")",
":",
"origin",
"=",
"originObjOfPort",
"(",
"intf",
")",
"d",
"=",
"intf",
".",
"_direction",
"d",
"=",
"Po... | add port to LPort for interface | [
"add",
"port",
"to",
"LPort",
"for",
"interface"
] | python | train | 26.4 |
iotile/coretools | transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/native_ble/iotile_transport_native_ble/device_adapter.py#L984-L994 | def periodic_callback(self):
"""Periodic cleanup tasks to maintain this adapter, should be called every second. """
if self.stopped:
return
# Check if we should start scanning again
if not self.scanning and len(self.connections.get_connections()) == 0:
self._log... | [
"def",
"periodic_callback",
"(",
"self",
")",
":",
"if",
"self",
".",
"stopped",
":",
"return",
"# Check if we should start scanning again",
"if",
"not",
"self",
".",
"scanning",
"and",
"len",
"(",
"self",
".",
"connections",
".",
"get_connections",
"(",
")",
... | Periodic cleanup tasks to maintain this adapter, should be called every second. | [
"Periodic",
"cleanup",
"tasks",
"to",
"maintain",
"this",
"adapter",
"should",
"be",
"called",
"every",
"second",
"."
] | python | train | 42.363636 |
blockstack/blockstack-core | blockstack/lib/atlas.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2177-L2266 | def atlas_find_missing_zonefile_availability( peer_table=None, con=None, path=None, missing_zonefile_info=None ):
"""
Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
... | [
"def",
"atlas_find_missing_zonefile_availability",
"(",
"peer_table",
"=",
"None",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
",",
"missing_zonefile_info",
"=",
"None",
")",
":",
"# which zonefiles do we have?",
"bit_offset",
"=",
"0",
"bit_count",
"=",
"1... | Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
our clique (and we'll re-sync our neighborss' inventories
every so often to make sure we detect when zonefiles
becom... | [
"Find",
"the",
"set",
"of",
"missing",
"zonefiles",
"as",
"well",
"as",
"their",
"popularity",
"amongst",
"our",
"neighbors",
"."
] | python | train | 33.333333 |
drastus/unicover | unicover/unicover.py | https://github.com/drastus/unicover/blob/4702d0151c63d525c25718a838396afe62302255/unicover/unicover.py#L238-L247 | def _getCharFont(self, font_files, code_point):
"""
Returns font files containing given code point.
"""
return_font_files = []
for font_file in font_files:
face = ft.Face(font_file)
if face.get_char_index(code_point):
return_font_files.appe... | [
"def",
"_getCharFont",
"(",
"self",
",",
"font_files",
",",
"code_point",
")",
":",
"return_font_files",
"=",
"[",
"]",
"for",
"font_file",
"in",
"font_files",
":",
"face",
"=",
"ft",
".",
"Face",
"(",
"font_file",
")",
"if",
"face",
".",
"get_char_index",... | Returns font files containing given code point. | [
"Returns",
"font",
"files",
"containing",
"given",
"code",
"point",
"."
] | python | train | 35.7 |
CalebBell/thermo | thermo/heat_capacity.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/heat_capacity.py#L1517-L1557 | def Zabransky_quasi_polynomial_integral(T, Tc, a1, a2, a3, a4, a5, a6):
r'''Calculates the integral of liquid heat capacity using the
quasi-polynomial model developed in [1]_.
Parameters
----------
T : float
Temperature [K]
a1-a6 : float
Coefficients
Returns
-------
... | [
"def",
"Zabransky_quasi_polynomial_integral",
"(",
"T",
",",
"Tc",
",",
"a1",
",",
"a2",
",",
"a3",
",",
"a4",
",",
"a5",
",",
"a6",
")",
":",
"Tc2",
"=",
"Tc",
"*",
"Tc",
"Tc3",
"=",
"Tc2",
"*",
"Tc",
"term",
"=",
"T",
"-",
"Tc",
"return",
"R"... | r'''Calculates the integral of liquid heat capacity using the
quasi-polynomial model developed in [1]_.
Parameters
----------
T : float
Temperature [K]
a1-a6 : float
Coefficients
Returns
-------
H : float
Difference in enthalpy from 0 K, [J/mol]
Notes
... | [
"r",
"Calculates",
"the",
"integral",
"of",
"liquid",
"heat",
"capacity",
"using",
"the",
"quasi",
"-",
"polynomial",
"model",
"developed",
"in",
"[",
"1",
"]",
"_",
"."
] | python | valid | 30.292683 |
clalancette/pycdlib | pycdlib/pycdlib.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/pycdlib.py#L2375-L2530 | def _open_fp(self, fp):
# type: (BinaryIO) -> None
'''
An internal method to open an existing ISO for inspection and
modification. Note that the file object passed in here must stay open
for the lifetime of this object, as the PyCdlib class uses it internally
to do writi... | [
"def",
"_open_fp",
"(",
"self",
",",
"fp",
")",
":",
"# type: (BinaryIO) -> None",
"if",
"hasattr",
"(",
"fp",
",",
"'mode'",
")",
"and",
"'b'",
"not",
"in",
"fp",
".",
"mode",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInvalidInput",
"(",
"\"The file to... | An internal method to open an existing ISO for inspection and
modification. Note that the file object passed in here must stay open
for the lifetime of this object, as the PyCdlib class uses it internally
to do writing and reading operations.
Parameters:
fp - The file object c... | [
"An",
"internal",
"method",
"to",
"open",
"an",
"existing",
"ISO",
"for",
"inspection",
"and",
"modification",
".",
"Note",
"that",
"the",
"file",
"object",
"passed",
"in",
"here",
"must",
"stay",
"open",
"for",
"the",
"lifetime",
"of",
"this",
"object",
"... | python | train | 49.083333 |
google/transitfeed | transitfeed/serviceperiod.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L148-L160 | def SetDayOfWeekHasService(self, dow, has_service=True):
"""Set service as running (or not) on a day of the week. By default the
service does not run on any days.
Args:
dow: 0 for Monday through 6 for Sunday
has_service: True if this service operates on dow, False if it does not.
Returns:
... | [
"def",
"SetDayOfWeekHasService",
"(",
"self",
",",
"dow",
",",
"has_service",
"=",
"True",
")",
":",
"assert",
"(",
"dow",
">=",
"0",
"and",
"dow",
"<",
"7",
")",
"self",
".",
"day_of_week",
"[",
"dow",
"]",
"=",
"has_service"
] | Set service as running (or not) on a day of the week. By default the
service does not run on any days.
Args:
dow: 0 for Monday through 6 for Sunday
has_service: True if this service operates on dow, False if it does not.
Returns:
None | [
"Set",
"service",
"as",
"running",
"(",
"or",
"not",
")",
"on",
"a",
"day",
"of",
"the",
"week",
".",
"By",
"default",
"the",
"service",
"does",
"not",
"run",
"on",
"any",
"days",
"."
] | python | train | 30.692308 |
ska-sa/katcp-python | katcp/inspecting_client.py | https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L852-L881 | def future_check_request(self, name, update=None):
"""Check if the request exists.
Used internally by future_get_request. This method is aware of
synchronisation in progress and if inspection of the server is allowed.
Parameters
----------
name : str
Name of... | [
"def",
"future_check_request",
"(",
"self",
",",
"name",
",",
"update",
"=",
"None",
")",
":",
"exist",
"=",
"False",
"yield",
"self",
".",
"until_data_synced",
"(",
")",
"if",
"name",
"in",
"self",
".",
"_requests_index",
":",
"exist",
"=",
"True",
"els... | Check if the request exists.
Used internally by future_get_request. This method is aware of
synchronisation in progress and if inspection of the server is allowed.
Parameters
----------
name : str
Name of the request to verify.
update : bool or None, optiona... | [
"Check",
"if",
"the",
"request",
"exists",
"."
] | python | train | 36.8 |
juanifioren/django-oidc-provider | oidc_provider/lib/endpoints/authorize.py | https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/endpoints/authorize.py#L257-L271 | def client_has_user_consent(self):
"""
Check if already exists user consent for some client.
Return bool.
"""
value = False
try:
uc = UserConsent.objects.get(user=self.request.user, client=self.client)
if (set(self.params['scope']).issubset(uc.sco... | [
"def",
"client_has_user_consent",
"(",
"self",
")",
":",
"value",
"=",
"False",
"try",
":",
"uc",
"=",
"UserConsent",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"self",
".",
"request",
".",
"user",
",",
"client",
"=",
"self",
".",
"client",
")",
"... | Check if already exists user consent for some client.
Return bool. | [
"Check",
"if",
"already",
"exists",
"user",
"consent",
"for",
"some",
"client",
"."
] | python | train | 29.8 |
bspaans/python-mingus | mingus/midi/midi_track.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L190-L192 | def note_on(self, channel, note, velocity):
"""Return bytes for a 'note_on' event."""
return self.midi_event(NOTE_ON, channel, note, velocity) | [
"def",
"note_on",
"(",
"self",
",",
"channel",
",",
"note",
",",
"velocity",
")",
":",
"return",
"self",
".",
"midi_event",
"(",
"NOTE_ON",
",",
"channel",
",",
"note",
",",
"velocity",
")"
] | Return bytes for a 'note_on' event. | [
"Return",
"bytes",
"for",
"a",
"note_on",
"event",
"."
] | python | train | 52 |
google/tangent | tangent/reverse_ad.py | https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/reverse_ad.py#L945-L963 | def joint(node):
"""Merge the bodies of primal and adjoint into a single function.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
Returns:
func: A `Module` node with a single function definition containing the
combined primal and adjoin... | [
"def",
"joint",
"(",
"node",
")",
":",
"node",
",",
"_",
",",
"_",
"=",
"_fix",
"(",
"node",
")",
"body",
"=",
"node",
".",
"body",
"[",
"0",
"]",
".",
"body",
"[",
":",
"-",
"1",
"]",
"+",
"node",
".",
"body",
"[",
"1",
"]",
".",
"body",... | Merge the bodies of primal and adjoint into a single function.
Args:
node: A module with the primal and adjoint function definitions as returned
by `reverse_ad`.
Returns:
func: A `Module` node with a single function definition containing the
combined primal and adjoint. | [
"Merge",
"the",
"bodies",
"of",
"primal",
"and",
"adjoint",
"into",
"a",
"single",
"function",
"."
] | python | train | 31 |
astropy/photutils | photutils/datasets/load.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/load.py#L112-L152 | def load_spitzer_catalog(show_progress=False): # pragma: no cover
"""
Load a 4.5 micron Spitzer catalog.
The image from which this catalog was derived is returned by
:func:`load_spitzer_image`.
Parameters
----------
show_progress : bool, optional
Whether to display a progress ba... | [
"def",
"load_spitzer_catalog",
"(",
"show_progress",
"=",
"False",
")",
":",
"# pragma: no cover",
"path",
"=",
"get_path",
"(",
"'spitzer_example_catalog.xml'",
",",
"location",
"=",
"'remote'",
",",
"show_progress",
"=",
"show_progress",
")",
"table",
"=",
"Table"... | Load a 4.5 micron Spitzer catalog.
The image from which this catalog was derived is returned by
:func:`load_spitzer_image`.
Parameters
----------
show_progress : bool, optional
Whether to display a progress bar during the download (default
is `False`).
Returns
-------
... | [
"Load",
"a",
"4",
".",
"5",
"micron",
"Spitzer",
"catalog",
"."
] | python | train | 23.902439 |
Neurita/boyle | boyle/utils/validation.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/validation.py#L90-L97 | def _num_samples(x):
"""Return number of samples in array-like x."""
if not hasattr(x, '__len__') and not hasattr(x, 'shape'):
if hasattr(x, '__array__'):
x = np.asarray(x)
else:
raise TypeError("Expected sequence or array-like, got %r" % x)
return x.shape[0] if hasat... | [
"def",
"_num_samples",
"(",
"x",
")",
":",
"if",
"not",
"hasattr",
"(",
"x",
",",
"'__len__'",
")",
"and",
"not",
"hasattr",
"(",
"x",
",",
"'shape'",
")",
":",
"if",
"hasattr",
"(",
"x",
",",
"'__array__'",
")",
":",
"x",
"=",
"np",
".",
"asarra... | Return number of samples in array-like x. | [
"Return",
"number",
"of",
"samples",
"in",
"array",
"-",
"like",
"x",
"."
] | python | valid | 42.375 |
mozilla/mozdownload | mozdownload/parser.py | https://github.com/mozilla/mozdownload/blob/97796a028455bb5200434562d23b66d5a5eb537b/mozdownload/parser.py#L81-L89 | def handle_data(self, data):
"""Callback when the data of a tag has been collected."""
# Only process the data when we are in an active a tag and have an URL.
if not self.active_url:
return
# The visible text can have a final slash so strip it off
if data.strip('/') ... | [
"def",
"handle_data",
"(",
"self",
",",
"data",
")",
":",
"# Only process the data when we are in an active a tag and have an URL.",
"if",
"not",
"self",
".",
"active_url",
":",
"return",
"# The visible text can have a final slash so strip it off",
"if",
"data",
".",
"strip",... | Callback when the data of a tag has been collected. | [
"Callback",
"when",
"the",
"data",
"of",
"a",
"tag",
"has",
"been",
"collected",
"."
] | python | train | 42.222222 |
materialsproject/pymatgen | pymatgen/io/abinit/abiobjects.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/abiobjects.py#L667-L683 | def gamma_centered(cls, kpts=(1, 1, 1), use_symmetries=True, use_time_reversal=True):
"""
Convenient static constructor for an automatic Gamma centered Kpoint grid.
Args:
kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors.
use_symmetries: False if spati... | [
"def",
"gamma_centered",
"(",
"cls",
",",
"kpts",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
",",
"use_symmetries",
"=",
"True",
",",
"use_time_reversal",
"=",
"True",
")",
":",
"return",
"cls",
"(",
"kpts",
"=",
"[",
"kpts",
"]",
",",
"kpt_shifts",
"... | Convenient static constructor for an automatic Gamma centered Kpoint grid.
Args:
kpts: Subdivisions N_1, N_2 and N_3 along reciprocal lattice vectors.
use_symmetries: False if spatial symmetries should not be used
to reduce the number of independent k-points.
... | [
"Convenient",
"static",
"constructor",
"for",
"an",
"automatic",
"Gamma",
"centered",
"Kpoint",
"grid",
"."
] | python | train | 47.529412 |
softlayer/softlayer-python | SoftLayer/managers/cdn.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/cdn.py#L93-L101 | def remove_origin(self, account_id, origin_id):
"""Removes an origin pull mapping with the given origin pull ID.
:param int account_id: the CDN account ID from which the mapping should
be deleted.
:param int origin_id: the origin pull mapping ID to delete.
... | [
"def",
"remove_origin",
"(",
"self",
",",
"account_id",
",",
"origin_id",
")",
":",
"return",
"self",
".",
"account",
".",
"deleteOriginPullRule",
"(",
"origin_id",
",",
"id",
"=",
"account_id",
")"
] | Removes an origin pull mapping with the given origin pull ID.
:param int account_id: the CDN account ID from which the mapping should
be deleted.
:param int origin_id: the origin pull mapping ID to delete. | [
"Removes",
"an",
"origin",
"pull",
"mapping",
"with",
"the",
"given",
"origin",
"pull",
"ID",
"."
] | python | train | 43.555556 |
Jajcus/pyxmpp2 | pyxmpp2/roster.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L539-L548 | def groups(self):
"""Set of groups defined in the roster.
:Return: the groups
:ReturnType: `set` of `unicode`
"""
groups = set()
for item in self._items:
groups |= item.groups
return groups | [
"def",
"groups",
"(",
"self",
")",
":",
"groups",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"self",
".",
"_items",
":",
"groups",
"|=",
"item",
".",
"groups",
"return",
"groups"
] | Set of groups defined in the roster.
:Return: the groups
:ReturnType: `set` of `unicode` | [
"Set",
"of",
"groups",
"defined",
"in",
"the",
"roster",
"."
] | python | valid | 24.9 |
googlefonts/ufo2ft | Lib/ufo2ft/outlineCompiler.py | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L398-L450 | def setupTable_cmap(self):
"""
Make the cmap table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired.
"""
if "cmap" not in self.tables:
return
... | [
"def",
"setupTable_cmap",
"(",
"self",
")",
":",
"if",
"\"cmap\"",
"not",
"in",
"self",
".",
"tables",
":",
"return",
"from",
"fontTools",
".",
"ttLib",
".",
"tables",
".",
"_c_m_a_p",
"import",
"cmap_format_4",
"nonBMP",
"=",
"dict",
"(",
"(",
"k",
",",... | Make the cmap table.
**This should not be called externally.** Subclasses
may override or supplement this method to handle the
table creation in a different way if desired. | [
"Make",
"the",
"cmap",
"table",
"."
] | python | train | 36.09434 |
Iotic-Labs/py-IoticAgent | src/IoticAgent/IOT/Thing.py | https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Thing.py#L704-L732 | def _cb_created(self, payload, duplicated):
"""Indirect callback (via Client) for point & subscription creation responses"""
if payload[P_RESOURCE] in _POINT_TYPE_TO_CLASS:
store = self.__new_feeds if payload[P_RESOURCE] == R_FEED else self.__new_controls
cls = _POINT_TYPE_TO_CLA... | [
"def",
"_cb_created",
"(",
"self",
",",
"payload",
",",
"duplicated",
")",
":",
"if",
"payload",
"[",
"P_RESOURCE",
"]",
"in",
"_POINT_TYPE_TO_CLASS",
":",
"store",
"=",
"self",
".",
"__new_feeds",
"if",
"payload",
"[",
"P_RESOURCE",
"]",
"==",
"R_FEED",
"... | Indirect callback (via Client) for point & subscription creation responses | [
"Indirect",
"callback",
"(",
"via",
"Client",
")",
"for",
"point",
"&",
"subscription",
"creation",
"responses"
] | python | train | 52.206897 |
hootnot/postcode-api-wrapper | postcodepy/typedefs.py | https://github.com/hootnot/postcode-api-wrapper/blob/42359cb9402f84a06f7d58f889f1156d653f5ea9/postcodepy/typedefs.py#L55-L72 | def translate_addresstype(f):
"""decorator to translate the addressType field.
translate the value of the addressType field of the API response into a
translated type.
"""
@wraps(f)
def wr(r, pc):
at = r["addressType"]
try:
r.update({"addressType": POSTCODE_API_TYPED... | [
"def",
"translate_addresstype",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wr",
"(",
"r",
",",
"pc",
")",
":",
"at",
"=",
"r",
"[",
"\"addressType\"",
"]",
"try",
":",
"r",
".",
"update",
"(",
"{",
"\"addressType\"",
":",
"POSTCODE_AP... | decorator to translate the addressType field.
translate the value of the addressType field of the API response into a
translated type. | [
"decorator",
"to",
"translate",
"the",
"addressType",
"field",
"."
] | python | train | 27.555556 |
Scifabric/pbs | pbs.py | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/pbs.py#L202-L214 | def update_task_redundancy(config, task_id, redundancy):
"""Update task redudancy for a project."""
if task_id is None:
msg = ("Are you sure you want to update all the tasks redundancy?")
if click.confirm(msg):
res = _update_tasks_redundancy(config, task_id, redundancy)
c... | [
"def",
"update_task_redundancy",
"(",
"config",
",",
"task_id",
",",
"redundancy",
")",
":",
"if",
"task_id",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Are you sure you want to update all the tasks redundancy?\"",
")",
"if",
"click",
".",
"confirm",
"(",
"msg",
")",
... | Update task redudancy for a project. | [
"Update",
"task",
"redudancy",
"for",
"a",
"project",
"."
] | python | train | 36.538462 |
UDST/orca | orca/orca.py | https://github.com/UDST/orca/blob/07b34aeef13cc87c966b2e30cbe7e76cc9d3622c/orca/orca.py#L239-L253 | def update_col(self, column_name, series):
"""
Add or replace a column in the underlying DataFrame.
Parameters
----------
column_name : str
Column to add or replace.
series : pandas.Series or sequence
Column data.
"""
logger.debug... | [
"def",
"update_col",
"(",
"self",
",",
"column_name",
",",
"series",
")",
":",
"logger",
".",
"debug",
"(",
"'updating column {!r} in table {!r}'",
".",
"format",
"(",
"column_name",
",",
"self",
".",
"name",
")",
")",
"self",
".",
"local",
"[",
"column_name... | Add or replace a column in the underlying DataFrame.
Parameters
----------
column_name : str
Column to add or replace.
series : pandas.Series or sequence
Column data. | [
"Add",
"or",
"replace",
"a",
"column",
"in",
"the",
"underlying",
"DataFrame",
"."
] | python | train | 28.6 |
petl-developers/petl | petl/io/pickle.py | https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/io/pickle.py#L100-L112 | def appendpickle(table, source=None, protocol=-1, write_header=False):
"""
Append data to an existing pickle file. I.e.,
as :func:`petl.io.pickle.topickle` but the file is opened in append mode.
Note that no attempt is made to check that the fields or row lengths are
consistent with the existing da... | [
"def",
"appendpickle",
"(",
"table",
",",
"source",
"=",
"None",
",",
"protocol",
"=",
"-",
"1",
",",
"write_header",
"=",
"False",
")",
":",
"_writepickle",
"(",
"table",
",",
"source",
"=",
"source",
",",
"mode",
"=",
"'ab'",
",",
"protocol",
"=",
... | Append data to an existing pickle file. I.e.,
as :func:`petl.io.pickle.topickle` but the file is opened in append mode.
Note that no attempt is made to check that the fields or row lengths are
consistent with the existing data, the data rows from the table are simply
appended to the file. | [
"Append",
"data",
"to",
"an",
"existing",
"pickle",
"file",
".",
"I",
".",
"e",
".",
"as",
":",
"func",
":",
"petl",
".",
"io",
".",
"pickle",
".",
"topickle",
"but",
"the",
"file",
"is",
"opened",
"in",
"append",
"mode",
"."
] | python | train | 38.461538 |
annoviko/pyclustering | pyclustering/container/cftree.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/container/cftree.py#L1219-L1240 | def show_feature_destibution(self, data = None):
"""!
@brief Shows feature distribution.
@details Only features in 1D, 2D, 3D space can be visualized.
@param[in] data (list): List of points that will be used for visualization, if it not specified than feature will be displa... | [
"def",
"show_feature_destibution",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"visualizer",
"=",
"cluster_visualizer",
"(",
")",
"print",
"(",
"\"amount of nodes: \"",
",",
"self",
".",
"__amount_nodes",
")",
"if",
"(",
"data",
"is",
"not",
"None",
")"... | !
@brief Shows feature distribution.
@details Only features in 1D, 2D, 3D space can be visualized.
@param[in] data (list): List of points that will be used for visualization, if it not specified than feature will be displayed only. | [
"!"
] | python | valid | 40.318182 |
progrium/skypipe | skypipe/cloud.py | https://github.com/progrium/skypipe/blob/6162610a1876282ff1cc8eeca6c8669b8f605482/skypipe/cloud.py#L56-L62 | def lookup_endpoint(cli):
"""Looks up the application endpoint from dotcloud"""
url = '/applications/{0}/environment'.format(APPNAME)
environ = cli.user.get(url).item
port = environ['DOTCLOUD_SATELLITE_ZMQ_PORT']
host = socket.gethostbyname(environ['DOTCLOUD_SATELLITE_ZMQ_HOST'])
return "tcp://{... | [
"def",
"lookup_endpoint",
"(",
"cli",
")",
":",
"url",
"=",
"'/applications/{0}/environment'",
".",
"format",
"(",
"APPNAME",
")",
"environ",
"=",
"cli",
".",
"user",
".",
"get",
"(",
"url",
")",
".",
"item",
"port",
"=",
"environ",
"[",
"'DOTCLOUD_SATELLI... | Looks up the application endpoint from dotcloud | [
"Looks",
"up",
"the",
"application",
"endpoint",
"from",
"dotcloud"
] | python | train | 48.571429 |
log2timeline/dfvfs | dfvfs/compression/zlib_decompressor.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/compression/zlib_decompressor.py#L35-L57 | def Decompress(self, compressed_data):
"""Decompresses the compressed data.
Args:
compressed_data (bytes): compressed data.
Returns:
tuple(bytes, bytes): uncompressed data and remaining compressed data.
Raises:
BackEndError: if the zlib compressed stream cannot be decompressed.
... | [
"def",
"Decompress",
"(",
"self",
",",
"compressed_data",
")",
":",
"try",
":",
"uncompressed_data",
"=",
"self",
".",
"_zlib_decompressor",
".",
"decompress",
"(",
"compressed_data",
")",
"remaining_compressed_data",
"=",
"getattr",
"(",
"self",
".",
"_zlib_decom... | Decompresses the compressed data.
Args:
compressed_data (bytes): compressed data.
Returns:
tuple(bytes, bytes): uncompressed data and remaining compressed data.
Raises:
BackEndError: if the zlib compressed stream cannot be decompressed. | [
"Decompresses",
"the",
"compressed",
"data",
"."
] | python | train | 31.391304 |
inspirehep/inspire-schemas | inspire_schemas/builders/literature.py | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/literature.py#L319-L333 | def add_book_series(self, title, volume=None):
"""
:param volume: the volume of the book
:type volume: string
:param title: the title of the book
:type title: string
"""
book_series = {}
if title is not None:
book_series['title'] = title
... | [
"def",
"add_book_series",
"(",
"self",
",",
"title",
",",
"volume",
"=",
"None",
")",
":",
"book_series",
"=",
"{",
"}",
"if",
"title",
"is",
"not",
"None",
":",
"book_series",
"[",
"'title'",
"]",
"=",
"title",
"if",
"volume",
"is",
"not",
"None",
"... | :param volume: the volume of the book
:type volume: string
:param title: the title of the book
:type title: string | [
":",
"param",
"volume",
":",
"the",
"volume",
"of",
"the",
"book",
":",
"type",
"volume",
":",
"string"
] | python | train | 28.466667 |
consbio/gis-metadata-parser | gis_metadata/utils.py | https://github.com/consbio/gis-metadata-parser/blob/59eefb2e51cd4d8cc3e94623a2167499ca9ef70f/gis_metadata/utils.py#L278-L296 | def parse_complex(tree_to_parse, xpath_root, xpath_map, complex_key):
"""
Creates and returns a Dictionary data structure parsed from the metadata.
:param tree_to_parse: the XML tree compatible with element_utils to be parsed
:param xpath_root: the XPATH location of the structure inside the parent eleme... | [
"def",
"parse_complex",
"(",
"tree_to_parse",
",",
"xpath_root",
",",
"xpath_map",
",",
"complex_key",
")",
":",
"complex_struct",
"=",
"{",
"}",
"for",
"prop",
"in",
"_complex_definitions",
".",
"get",
"(",
"complex_key",
",",
"xpath_map",
")",
":",
"# Normal... | Creates and returns a Dictionary data structure parsed from the metadata.
:param tree_to_parse: the XML tree compatible with element_utils to be parsed
:param xpath_root: the XPATH location of the structure inside the parent element
:param xpath_map: a dict of XPATHs corresponding to a complex definition
... | [
"Creates",
"and",
"returns",
"a",
"Dictionary",
"data",
"structure",
"parsed",
"from",
"the",
"metadata",
".",
":",
"param",
"tree_to_parse",
":",
"the",
"XML",
"tree",
"compatible",
"with",
"element_utils",
"to",
"be",
"parsed",
":",
"param",
"xpath_root",
":... | python | train | 53 |
openstack/horizon | horizon/base.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/base.py#L937-L988 | def _process_panel_configuration(self, config):
"""Add, remove and set default panels on the dashboard."""
try:
dashboard = config.get('PANEL_DASHBOARD')
if not dashboard:
LOG.warning("Skipping %s because it doesn't have "
"PANEL_DASHBO... | [
"def",
"_process_panel_configuration",
"(",
"self",
",",
"config",
")",
":",
"try",
":",
"dashboard",
"=",
"config",
".",
"get",
"(",
"'PANEL_DASHBOARD'",
")",
"if",
"not",
"dashboard",
":",
"LOG",
".",
"warning",
"(",
"\"Skipping %s because it doesn't have \"",
... | Add, remove and set default panels on the dashboard. | [
"Add",
"remove",
"and",
"set",
"default",
"panels",
"on",
"the",
"dashboard",
"."
] | python | train | 47.461538 |
rwl/pylon | pyreto/renderer.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/renderer.py#L53-L75 | def updateData(self, data):
""" Updates the data used by the renderer.
"""
# pylab.ion()
fig = pylab.figure(1)
n_agent = len(data)
idx = 1
for i, adata in enumerate(data):
saxis = fig.add_subplot(3, n_agent, i + 1)
saxis.plot(adata[0])
... | [
"def",
"updateData",
"(",
"self",
",",
"data",
")",
":",
"# pylab.ion()",
"fig",
"=",
"pylab",
".",
"figure",
"(",
"1",
")",
"n_agent",
"=",
"len",
"(",
"data",
")",
"idx",
"=",
"1",
"for",
"i",
",",
"adata",
"in",
"enumerate",
"(",
"data",
... | Updates the data used by the renderer. | [
"Updates",
"the",
"data",
"used",
"by",
"the",
"renderer",
"."
] | python | train | 25.347826 |
lago-project/lago | lago/prefix.py | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L1501-L1512 | def is_prefix(cls, path):
"""
Check if a path is a valid prefix
Args:
path(str): path to be checked
Returns:
bool: True if the given path is a prefix
"""
lagofile = paths.Paths(path).prefix_lagofile()
return os.path.isfile(lagofile) | [
"def",
"is_prefix",
"(",
"cls",
",",
"path",
")",
":",
"lagofile",
"=",
"paths",
".",
"Paths",
"(",
"path",
")",
".",
"prefix_lagofile",
"(",
")",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"lagofile",
")"
] | Check if a path is a valid prefix
Args:
path(str): path to be checked
Returns:
bool: True if the given path is a prefix | [
"Check",
"if",
"a",
"path",
"is",
"a",
"valid",
"prefix"
] | python | train | 25.25 |
RJT1990/pyflux | pyflux/gpnarx/gpnarx.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gpnarx/gpnarx.py#L442-L465 | def predict(self, h=5):
""" Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
Returns
----------
- pd.DataFrame with predicted values
"""
... | [
"def",
"predict",
"(",
"self",
",",
"h",
"=",
"5",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
"estimated",
"is",
"False",
":",
"raise",
"Exception",
"(",
"\"No latent variables estimated!\"",
")",
"else",
":",
"predictions",
",",
"_",
",",
"_",
... | Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
Returns
----------
- pd.DataFrame with predicted values | [
"Makes",
"forecast",
"with",
"the",
"estimated",
"model",
"Parameters",
"----------",
"h",
":",
"int",
"(",
"default",
":",
"5",
")",
"How",
"many",
"steps",
"ahead",
"would",
"you",
"like",
"to",
"forecast?",
"Returns",
"----------",
"-",
"pd",
".",
"Data... | python | train | 34.666667 |
push-things/django-th | th_evernote/my_evernote.py | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_evernote/my_evernote.py#L289-L309 | def callback(self, request, **kwargs):
"""
Called from the Service when the user accept to activate it
"""
try:
client = self.get_evernote_client()
# finally we save the user auth token
# As we already stored the object ServicesActivated
... | [
"def",
"callback",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"client",
"=",
"self",
".",
"get_evernote_client",
"(",
")",
"# finally we save the user auth token",
"# As we already stored the object ServicesActivated",
"# from the UserSe... | Called from the Service when the user accept to activate it | [
"Called",
"from",
"the",
"Service",
"when",
"the",
"user",
"accept",
"to",
"activate",
"it"
] | python | train | 45.285714 |
devision-io/metasdk | metasdk/services/MetaqlService.py | https://github.com/devision-io/metasdk/blob/1a1af5ceeb8ade843fd656c9c27c8b9ff789fc68/metasdk/services/MetaqlService.py#L15-L26 | def download_data(self, configuration, output_file):
"""
Выполняет указанный в конфигурации запрос и отдает файл на скачивание
:param configuration: Конфгурация запроса
:param output_file: Место, куда надо скачать файл
:return:
"""
params = configuration
r... | [
"def",
"download_data",
"(",
"self",
",",
"configuration",
",",
"output_file",
")",
":",
"params",
"=",
"configuration",
"response",
"=",
"self",
".",
"__app",
".",
"native_api_call",
"(",
"'metaql'",
",",
"'download-data'",
",",
"params",
",",
"self",
".",
... | Выполняет указанный в конфигурации запрос и отдает файл на скачивание
:param configuration: Конфгурация запроса
:param output_file: Место, куда надо скачать файл
:return: | [
"Выполняет",
"указанный",
"в",
"конфигурации",
"запрос",
"и",
"отдает",
"файл",
"на",
"скачивание",
":",
"param",
"configuration",
":",
"Конфгурация",
"запроса",
":",
"param",
"output_file",
":",
"Место",
"куда",
"надо",
"скачать",
"файл",
":",
"return",
":"
] | python | train | 47.333333 |
pallets/werkzeug | examples/manage-plnt.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/examples/manage-plnt.py#L18-L25 | def make_app():
"""Helper function that creates a plnt app."""
from plnt import Plnt
database_uri = os.environ.get("PLNT_DATABASE_URI")
app = Plnt(database_uri or "sqlite:////tmp/plnt.db")
app.bind_to_context()
return app | [
"def",
"make_app",
"(",
")",
":",
"from",
"plnt",
"import",
"Plnt",
"database_uri",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PLNT_DATABASE_URI\"",
")",
"app",
"=",
"Plnt",
"(",
"database_uri",
"or",
"\"sqlite:////tmp/plnt.db\"",
")",
"app",
".",
"bind_... | Helper function that creates a plnt app. | [
"Helper",
"function",
"that",
"creates",
"a",
"plnt",
"app",
"."
] | python | train | 29.875 |
crdoconnor/commandlib | commandlib/command.py | https://github.com/crdoconnor/commandlib/blob/b630364fd7b0d189b388e22a7f43235d182e12e4/commandlib/command.py#L115-L129 | def with_env(self, **environment_variables):
"""
Return new Command object that will be run with additional
environment variables.
Specify environment variables as follows:
new_cmd = old_cmd.with_env(PYTHON_PATH=".", ENV_PORT="2022")
"""
new_env_vars = {
... | [
"def",
"with_env",
"(",
"self",
",",
"*",
"*",
"environment_variables",
")",
":",
"new_env_vars",
"=",
"{",
"str",
"(",
"var",
")",
":",
"str",
"(",
"val",
")",
"for",
"var",
",",
"val",
"in",
"environment_variables",
".",
"items",
"(",
")",
"}",
"ne... | Return new Command object that will be run with additional
environment variables.
Specify environment variables as follows:
new_cmd = old_cmd.with_env(PYTHON_PATH=".", ENV_PORT="2022") | [
"Return",
"new",
"Command",
"object",
"that",
"will",
"be",
"run",
"with",
"additional",
"environment",
"variables",
"."
] | python | train | 33.6 |
pantsbuild/pants | src/python/pants/java/nailgun_executor.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_executor.py#L286-L299 | def post_fork_child(self, fingerprint, jvm_options, classpath, stdout, stderr):
"""Post-fork() child callback for ProcessManager.daemon_spawn()."""
java = SubprocessExecutor(self._distribution)
subproc = java.spawn(classpath=classpath,
main='com.martiansoftware.nailgun.NGServer',
... | [
"def",
"post_fork_child",
"(",
"self",
",",
"fingerprint",
",",
"jvm_options",
",",
"classpath",
",",
"stdout",
",",
"stderr",
")",
":",
"java",
"=",
"SubprocessExecutor",
"(",
"self",
".",
"_distribution",
")",
"subproc",
"=",
"java",
".",
"spawn",
"(",
"... | Post-fork() child callback for ProcessManager.daemon_spawn(). | [
"Post",
"-",
"fork",
"()",
"child",
"callback",
"for",
"ProcessManager",
".",
"daemon_spawn",
"()",
"."
] | python | train | 46.928571 |
wesyoung/pyzyre | czmq/_czmq_ctypes.py | https://github.com/wesyoung/pyzyre/blob/22d4c757acefcfdb700d3802adaf30b402bb9eea/czmq/_czmq_ctypes.py#L3116-L3122 | def insert(self, key, item):
"""
Insert item into hash table with specified key and item.
If key is already present returns -1 and leaves existing item unchanged
Returns 0 on success.
"""
return lib.zhashx_insert(self._as_parameter_, key, item) | [
"def",
"insert",
"(",
"self",
",",
"key",
",",
"item",
")",
":",
"return",
"lib",
".",
"zhashx_insert",
"(",
"self",
".",
"_as_parameter_",
",",
"key",
",",
"item",
")"
] | Insert item into hash table with specified key and item.
If key is already present returns -1 and leaves existing item unchanged
Returns 0 on success. | [
"Insert",
"item",
"into",
"hash",
"table",
"with",
"specified",
"key",
"and",
"item",
".",
"If",
"key",
"is",
"already",
"present",
"returns",
"-",
"1",
"and",
"leaves",
"existing",
"item",
"unchanged",
"Returns",
"0",
"on",
"success",
"."
] | python | train | 38.571429 |
conchoecia/gloTK | gloTK/wrappers.py | https://github.com/conchoecia/gloTK/blob/58abee663fcfbbd09f4863c3ca3ae054e33184a8/gloTK/wrappers.py#L118-L127 | def check_path(self, path):
"""
turns path into an absolute path and checks that it exists, then
returns it as a string.
"""
path = os.path.abspath(path)
if os.path.exists(path):
return path
else:
utils.die("input file does not exists:\n {... | [
"def",
"check_path",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"path",
"else",
":",
"utils",
".",
"die",
"(",
"... | turns path into an absolute path and checks that it exists, then
returns it as a string. | [
"turns",
"path",
"into",
"an",
"absolute",
"path",
"and",
"checks",
"that",
"it",
"exists",
"then",
"returns",
"it",
"as",
"a",
"string",
"."
] | python | train | 32.7 |
cag/sphinxcontrib-soliditydomain | sphinxcontrib/soliditydomain/documenters.py | https://github.com/cag/sphinxcontrib-soliditydomain/blob/b004b6e43727771027b4065fab18fcb9ccb2c826/sphinxcontrib/soliditydomain/documenters.py#L141-L220 | def generate(self, more_content=None, all_members=False):
# type: (Any, str, bool, bool) -> None
"""Generate reST for the object given by *self.name*, and possibly for
its members.
If *more_content* is given, include that content.
If *all_members* is True, document all members.
... | [
"def",
"generate",
"(",
"self",
",",
"more_content",
"=",
"None",
",",
"all_members",
"=",
"False",
")",
":",
"# type: (Any, str, bool, bool) -> None",
"directive",
"=",
"getattr",
"(",
"self",
",",
"'directivetype'",
",",
"self",
".",
"objtype",
")",
"# parse c... | Generate reST for the object given by *self.name*, and possibly for
its members.
If *more_content* is given, include that content.
If *all_members* is True, document all members. | [
"Generate",
"reST",
"for",
"the",
"object",
"given",
"by",
"*",
"self",
".",
"name",
"*",
"and",
"possibly",
"for",
"its",
"members",
"."
] | python | train | 37.5125 |
daethnir/authprogs | setup.py | https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/setup.py#L102-L106 | def rm_docs(self):
"""Remove converted docs."""
for filename in self.created:
if os.path.exists(filename):
os.unlink(filename) | [
"def",
"rm_docs",
"(",
"self",
")",
":",
"for",
"filename",
"in",
"self",
".",
"created",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"os",
".",
"unlink",
"(",
"filename",
")"
] | Remove converted docs. | [
"Remove",
"converted",
"docs",
"."
] | python | train | 33.2 |
cbclab/MOT | mot/lib/cl_function.py | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_function.py#L155-L166 | def from_string(cls, cl_function, dependencies=()):
"""Parse the given CL function into a SimpleCLFunction object.
Args:
cl_function (str): the function we wish to turn into an object
dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends on
... | [
"def",
"from_string",
"(",
"cls",
",",
"cl_function",
",",
"dependencies",
"=",
"(",
")",
")",
":",
"return_type",
",",
"function_name",
",",
"parameter_list",
",",
"body",
"=",
"split_cl_function",
"(",
"cl_function",
")",
"return",
"SimpleCLFunction",
"(",
"... | Parse the given CL function into a SimpleCLFunction object.
Args:
cl_function (str): the function we wish to turn into an object
dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends on
Returns:
SimpleCLFunction: the CL data type ... | [
"Parse",
"the",
"given",
"CL",
"function",
"into",
"a",
"SimpleCLFunction",
"object",
"."
] | python | train | 51.083333 |
manns/pyspread | pyspread/src/actions/_main_window_actions.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/actions/_main_window_actions.py#L507-L553 | def copy_result(self, selection):
"""Returns result
If selection consists of one cell only and result is a bitmap then
the bitmap is returned.
Otherwise the method returns string representations of the result
for the given selection in a tab separated string.
"""
... | [
"def",
"copy_result",
"(",
"self",
",",
"selection",
")",
":",
"bbox",
"=",
"selection",
".",
"get_bbox",
"(",
")",
"if",
"not",
"bbox",
":",
"# There is no selection",
"bb_top",
",",
"bb_left",
"=",
"self",
".",
"grid",
".",
"actions",
".",
"cursor",
"[... | Returns result
If selection consists of one cell only and result is a bitmap then
the bitmap is returned.
Otherwise the method returns string representations of the result
for the given selection in a tab separated string. | [
"Returns",
"result"
] | python | train | 35.893617 |
StackStorm/pybind | pybind/nos/v7_2_0/interface/hundredgigabitethernet/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/interface/hundredgigabitethernet/__init__.py#L1314-L1337 | def _set_openflow_interface_cfg(self, v, load=False):
"""
Setter method for openflow_interface_cfg, mapped from YANG variable /interface/hundredgigabitethernet/openflow_interface_cfg (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_openflow_interface_cfg is co... | [
"def",
"_set_openflow_interface_cfg",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | Setter method for openflow_interface_cfg, mapped from YANG variable /interface/hundredgigabitethernet/openflow_interface_cfg (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_openflow_interface_cfg is considered as a private
method. Backends looking to populate thi... | [
"Setter",
"method",
"for",
"openflow_interface_cfg",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface",
"/",
"hundredgigabitethernet",
"/",
"openflow_interface_cfg",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":... | python | train | 89.083333 |
gwpy/gwpy | gwpy/signal/spectral/_registry.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/signal/spectral/_registry.py#L36-L70 | def register_method(func, name=None, deprecated=False):
"""Register a method of calculating an average spectrogram.
Parameters
----------
func : `callable`
function to execute
name : `str`, optional
name of the method, defaults to ``func.__name__``
deprecated : `bool`, optiona... | [
"def",
"register_method",
"(",
"func",
",",
"name",
"=",
"None",
",",
"deprecated",
"=",
"False",
")",
":",
"# warn about deprecated functions",
"if",
"deprecated",
":",
"func",
"=",
"deprecated_function",
"(",
"func",
",",
"\"the {0!r} PSD methods is deprecated, and ... | Register a method of calculating an average spectrogram.
Parameters
----------
func : `callable`
function to execute
name : `str`, optional
name of the method, defaults to ``func.__name__``
deprecated : `bool`, optional
whether this method is deprecated (`True`) or not (`F... | [
"Register",
"a",
"method",
"of",
"calculating",
"an",
"average",
"spectrogram",
"."
] | python | train | 27.857143 |
bastibe/SoundFile | soundfile.py | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1151-L1158 | def close(self):
"""Close the file. Can be called multiple times."""
if not self.closed:
# be sure to flush data to disk before closing the file
self.flush()
err = _snd.sf_close(self._file)
self._file = None
_error_check(err) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"closed",
":",
"# be sure to flush data to disk before closing the file",
"self",
".",
"flush",
"(",
")",
"err",
"=",
"_snd",
".",
"sf_close",
"(",
"self",
".",
"_file",
")",
"self",
".",
"_f... | Close the file. Can be called multiple times. | [
"Close",
"the",
"file",
".",
"Can",
"be",
"called",
"multiple",
"times",
"."
] | python | train | 36.875 |
vsoch/helpme | helpme/main/base/settings.py | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/settings.py#L232-L258 | def get_and_update_setting(self, name, default=None, user=True):
'''Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The user config file is used as a ca... | [
"def",
"get_and_update_setting",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
",",
"user",
"=",
"True",
")",
":",
"setting",
"=",
"self",
".",
"_get_setting",
"(",
"name",
",",
"user",
"=",
"user",
")",
"if",
"setting",
"is",
"None",
"and",
... | Look for a setting in the environment (first priority) and then
the settings file (second). If something is found, the settings
file is updated. The order of operations works as follows:
1. The user config file is used as a cache for the variable
2. the environment variable always takes pri... | [
"Look",
"for",
"a",
"setting",
"in",
"the",
"environment",
"(",
"first",
"priority",
")",
"and",
"then",
"the",
"settings",
"file",
"(",
"second",
")",
".",
"If",
"something",
"is",
"found",
"the",
"settings",
"file",
"is",
"updated",
".",
"The",
"order"... | python | train | 39.074074 |
theislab/scanpy | scanpy/neighbors/__init__.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/neighbors/__init__.py#L579-L661 | def compute_neighbors(
self,
n_neighbors: int = 30,
knn: bool = True,
n_pcs: Optional[int] = None,
use_rep: Optional[str] = None,
method: str = 'umap',
random_state: Optional[Union[RandomState, int]] = 0,
write_knn_indices: bool = False,
metric: st... | [
"def",
"compute_neighbors",
"(",
"self",
",",
"n_neighbors",
":",
"int",
"=",
"30",
",",
"knn",
":",
"bool",
"=",
"True",
",",
"n_pcs",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"use_rep",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",... | \
Compute distances and connectivities of neighbors.
Parameters
----------
n_neighbors
Use this number of nearest neighbors.
knn
Restrict result to `n_neighbors` nearest neighbors.
{n_pcs}
{use_rep}
Returns
-------
... | [
"\\",
"Compute",
"distances",
"and",
"connectivities",
"of",
"neighbors",
"."
] | python | train | 44.939759 |
tanghaibao/goatools | goatools/grouper/grprplt.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprplt.py#L125-L144 | def plot_grouped_gos(self, fout_img=None, exclude_hdrs=None, **kws_usr):
"""One Plot containing all user GOs (yellow or green) and header GO IDs(green or purple)."""
# kws_plt -> go2color go2bordercolor
kws_plt, kws_dag = self._get_kws_plt(self.grprobj.usrgos, **kws_usr)
pltgosusr = self... | [
"def",
"plot_grouped_gos",
"(",
"self",
",",
"fout_img",
"=",
"None",
",",
"exclude_hdrs",
"=",
"None",
",",
"*",
"*",
"kws_usr",
")",
":",
"# kws_plt -> go2color go2bordercolor",
"kws_plt",
",",
"kws_dag",
"=",
"self",
".",
"_get_kws_plt",
"(",
"self",
".",
... | One Plot containing all user GOs (yellow or green) and header GO IDs(green or purple). | [
"One",
"Plot",
"containing",
"all",
"user",
"GOs",
"(",
"yellow",
"or",
"green",
")",
"and",
"header",
"GO",
"IDs",
"(",
"green",
"or",
"purple",
")",
"."
] | python | train | 60.15 |
EconForge/dolo | dolo/numeric/discretization/quadrature.py | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/discretization/quadrature.py#L59-L122 | def gauss_hermite_nodes(orders, sigma, mu=None):
'''
Computes the weights and nodes for Gauss Hermite quadrature.
Parameters
----------
orders : int, list, array
The order of integration used in the quadrature routine
sigma : array-like
If one dimensional, the variance of the no... | [
"def",
"gauss_hermite_nodes",
"(",
"orders",
",",
"sigma",
",",
"mu",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"orders",
",",
"int",
")",
":",
"orders",
"=",
"[",
"orders",
"]",
"import",
"numpy",
"if",
"mu",
"is",
"None",
":",
"mu",
"=",
"n... | Computes the weights and nodes for Gauss Hermite quadrature.
Parameters
----------
orders : int, list, array
The order of integration used in the quadrature routine
sigma : array-like
If one dimensional, the variance of the normal distribution being
approximated. If multidimensi... | [
"Computes",
"the",
"weights",
"and",
"nodes",
"for",
"Gauss",
"Hermite",
"quadrature",
"."
] | python | train | 24.625 |
log2timeline/plaso | plaso/parsers/sqlite_plugins/firefox.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/sqlite_plugins/firefox.py#L467-L490 | def _ReverseHostname(self, hostname):
"""Reverses the hostname and strips the leading dot.
The hostname entry is reversed:
moc.elgoog.www.
Should be:
www.google.com
Args:
hostname (str): reversed hostname.
Returns:
str: hostname without a leading dot.
"""
if not ho... | [
"def",
"_ReverseHostname",
"(",
"self",
",",
"hostname",
")",
":",
"if",
"not",
"hostname",
":",
"return",
"''",
"if",
"len",
"(",
"hostname",
")",
"<=",
"1",
":",
"return",
"hostname",
"if",
"hostname",
"[",
"-",
"1",
"]",
"==",
"'.'",
":",
"return"... | Reverses the hostname and strips the leading dot.
The hostname entry is reversed:
moc.elgoog.www.
Should be:
www.google.com
Args:
hostname (str): reversed hostname.
Returns:
str: hostname without a leading dot. | [
"Reverses",
"the",
"hostname",
"and",
"strips",
"the",
"leading",
"dot",
"."
] | python | train | 19.25 |
assamite/creamas | creamas/mp.py | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/mp.py#L886-L915 | def spawn_container(addr, env_cls=Environment,
mgr_cls=EnvManager, set_seed=True, *args, **kwargs):
"""Spawn a new environment in a given address as a coroutine.
Arguments and keyword arguments are passed down to the created environment
at initialization time.
If `setproctitle <htt... | [
"def",
"spawn_container",
"(",
"addr",
",",
"env_cls",
"=",
"Environment",
",",
"mgr_cls",
"=",
"EnvManager",
",",
"set_seed",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Try setting the process name to easily recognize the spawned",
"# en... | Spawn a new environment in a given address as a coroutine.
Arguments and keyword arguments are passed down to the created environment
at initialization time.
If `setproctitle <https://pypi.python.org/pypi/setproctitle>`_ is
installed, this function renames the title of the process to start with
'c... | [
"Spawn",
"a",
"new",
"environment",
"in",
"a",
"given",
"address",
"as",
"a",
"coroutine",
"."
] | python | train | 36.8 |
KnowledgeLinks/rdfframework | rdfframework/utilities/codetimer.py | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/codetimer.py#L16-L24 | def log(self, timer_name, node):
''' logs a event in the timer '''
timestamp = time.time()
if hasattr(self, timer_name):
getattr(self, timer_name).append({
"node":node,
"time":timestamp})
else:
setattr(self, timer_name, [{"node":nod... | [
"def",
"log",
"(",
"self",
",",
"timer_name",
",",
"node",
")",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"if",
"hasattr",
"(",
"self",
",",
"timer_name",
")",
":",
"getattr",
"(",
"self",
",",
"timer_name",
")",
".",
"append",
"(",
"{"... | logs a event in the timer | [
"logs",
"a",
"event",
"in",
"the",
"timer"
] | python | train | 37.111111 |
apache/incubator-heron | heron/statemgrs/src/python/config.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/statemgrs/src/python/config.py#L45-L50 | def validate_state_locations(self):
"""
Names of all state locations must be unique.
"""
names = map(lambda loc: loc["name"], self.locations)
assert len(names) == len(set(names)), "Names of state locations must be unique" | [
"def",
"validate_state_locations",
"(",
"self",
")",
":",
"names",
"=",
"map",
"(",
"lambda",
"loc",
":",
"loc",
"[",
"\"name\"",
"]",
",",
"self",
".",
"locations",
")",
"assert",
"len",
"(",
"names",
")",
"==",
"len",
"(",
"set",
"(",
"names",
")",... | Names of all state locations must be unique. | [
"Names",
"of",
"all",
"state",
"locations",
"must",
"be",
"unique",
"."
] | python | valid | 39.333333 |
dustin/twitty-twister | twittytwister/streaming.py | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/streaming.py#L35-L48 | def lineReceived(self, line):
"""
Called when a line is received.
We expect a length in bytes or an empty line for keep-alive. If
we got a length, switch to raw mode to receive that amount of bytes.
"""
if line and line.isdigit():
self._expectedLength = int(l... | [
"def",
"lineReceived",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
"and",
"line",
".",
"isdigit",
"(",
")",
":",
"self",
".",
"_expectedLength",
"=",
"int",
"(",
"line",
")",
"self",
".",
"_rawBuffer",
"=",
"[",
"]",
"self",
".",
"_rawBufferLen... | Called when a line is received.
We expect a length in bytes or an empty line for keep-alive. If
we got a length, switch to raw mode to receive that amount of bytes. | [
"Called",
"when",
"a",
"line",
"is",
"received",
"."
] | python | train | 33.071429 |
aiortc/aiortc | aiortc/rtcrtpsender.py | https://github.com/aiortc/aiortc/blob/60ed036abf4575bd63985724b4493d569e6da29b/aiortc/rtcrtpsender.py#L140-L162 | async def send(self, parameters: RTCRtpSendParameters):
"""
Attempt to set the parameters controlling the sending of media.
:param: parameters: The :class:`RTCRtpParameters` for the sender.
"""
if not self.__started:
self.__cname = parameters.rtcp.cname
s... | [
"async",
"def",
"send",
"(",
"self",
",",
"parameters",
":",
"RTCRtpSendParameters",
")",
":",
"if",
"not",
"self",
".",
"__started",
":",
"self",
".",
"__cname",
"=",
"parameters",
".",
"rtcp",
".",
"cname",
"self",
".",
"__mid",
"=",
"parameters",
".",... | Attempt to set the parameters controlling the sending of media.
:param: parameters: The :class:`RTCRtpParameters` for the sender. | [
"Attempt",
"to",
"set",
"the",
"parameters",
"controlling",
"the",
"sending",
"of",
"media",
"."
] | python | train | 43.043478 |
hobson/pug-dj | pug/dj/db.py | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db.py#L651-L683 | def sum_in_date(x='date', y='net_sales', filter_dict=None, model='WikiItem', app=DEFAULT_APP, sort=True, limit=100000):
"""
Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts.
FIXME: Tests need models with a date fiel... | [
"def",
"sum_in_date",
"(",
"x",
"=",
"'date'",
",",
"y",
"=",
"'net_sales'",
",",
"filter_dict",
"=",
"None",
",",
"model",
"=",
"'WikiItem'",
",",
"app",
"=",
"DEFAULT_APP",
",",
"sort",
"=",
"True",
",",
"limit",
"=",
"100000",
")",
":",
"sort",
"=... | Count the number of records for each discrete (categorical) value of a field and return a dict of two lists, the field values and the counts.
FIXME: Tests need models with a date field:
Examples:
>> x, y = sum_in_date(y='net_sales', filter_dict={'model__startswith': 'LC60'}, model='Permission', limit=5, ... | [
"Count",
"the",
"number",
"of",
"records",
"for",
"each",
"discrete",
"(",
"categorical",
")",
"value",
"of",
"a",
"field",
"and",
"return",
"a",
"dict",
"of",
"two",
"lists",
"the",
"field",
"values",
"and",
"the",
"counts",
"."
] | python | train | 39.69697 |
gem/oq-engine | openquake/calculators/views.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L838-L864 | def view_dupl_sources(token, dstore):
"""
Show the sources with the same ID and the truly duplicated sources
"""
fields = ['source_id', 'code', 'gidx1', 'gidx2', 'num_ruptures']
dic = group_array(dstore['source_info'].value[fields], 'source_id')
sameid = []
dupl = []
for source_id, group... | [
"def",
"view_dupl_sources",
"(",
"token",
",",
"dstore",
")",
":",
"fields",
"=",
"[",
"'source_id'",
",",
"'code'",
",",
"'gidx1'",
",",
"'gidx2'",
",",
"'num_ruptures'",
"]",
"dic",
"=",
"group_array",
"(",
"dstore",
"[",
"'source_info'",
"]",
".",
"valu... | Show the sources with the same ID and the truly duplicated sources | [
"Show",
"the",
"sources",
"with",
"the",
"same",
"ID",
"and",
"the",
"truly",
"duplicated",
"sources"
] | python | train | 37.888889 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/sqlitedb.py#L181-L187 | def _defaults(self, keys=None):
"""create an empty record"""
d = {}
keys = self._keys if keys is None else keys
for key in keys:
d[key] = None
return d | [
"def",
"_defaults",
"(",
"self",
",",
"keys",
"=",
"None",
")",
":",
"d",
"=",
"{",
"}",
"keys",
"=",
"self",
".",
"_keys",
"if",
"keys",
"is",
"None",
"else",
"keys",
"for",
"key",
"in",
"keys",
":",
"d",
"[",
"key",
"]",
"=",
"None",
"return"... | create an empty record | [
"create",
"an",
"empty",
"record"
] | python | test | 28.142857 |
dailymuse/oz | oz/core/actions.py | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/core/actions.py#L36-L45 | def config_maker(project_name, path):
"""Creates a config file based on the project name"""
with open(skeleton_path("config.py"), "r") as config_source:
config_content = config_source.read()
config_content = config_content.replace("__PROJECT_NAME__", project_name)
with open(path, "w") as conf... | [
"def",
"config_maker",
"(",
"project_name",
",",
"path",
")",
":",
"with",
"open",
"(",
"skeleton_path",
"(",
"\"config.py\"",
")",
",",
"\"r\"",
")",
"as",
"config_source",
":",
"config_content",
"=",
"config_source",
".",
"read",
"(",
")",
"config_content",
... | Creates a config file based on the project name | [
"Creates",
"a",
"config",
"file",
"based",
"on",
"the",
"project",
"name"
] | python | train | 36.1 |
vatlab/SoS | src/sos/utils.py | https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/utils.py#L1476-L1495 | def tail_of_file(filename, n, ansi2html=False):
"""Reads a n lines from f with an offset of offset lines. """
avg_line_length = 74
to_read = n
with open(filename) as f:
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
... | [
"def",
"tail_of_file",
"(",
"filename",
",",
"n",
",",
"ansi2html",
"=",
"False",
")",
":",
"avg_line_length",
"=",
"74",
"to_read",
"=",
"n",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"while",
"1",
":",
"try",
":",
"f",
".",
"seek",
"(... | Reads a n lines from f with an offset of offset lines. | [
"Reads",
"a",
"n",
"lines",
"from",
"f",
"with",
"an",
"offset",
"of",
"offset",
"lines",
"."
] | python | train | 37.8 |
saltstack/salt | salt/states/azurearm_dns.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_dns.py#L300-L360 | def zone_absent(name, resource_group, connection_auth=None):
'''
.. versionadded:: Fluorine
Ensure a DNS zone does not exist in the resource group.
:param name:
Name of the DNS zone.
:param resource_group:
The resource group assigned to the DNS zone.
:param connection_auth:
... | [
"def",
"zone_absent",
"(",
"name",
",",
"resource_group",
",",
"connection_auth",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"... | .. versionadded:: Fluorine
Ensure a DNS zone does not exist in the resource group.
:param name:
Name of the DNS zone.
:param resource_group:
The resource group assigned to the DNS zone.
:param connection_auth:
A dict with subscription and authentication parameters to be used ... | [
"..",
"versionadded",
"::",
"Fluorine"
] | python | train | 26.131148 |
minio/minio-py | minio/xml_marshal.py | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/xml_marshal.py#L165-L199 | def _add_notification_config_to_xml(node, element_name, configs):
"""
Internal function that builds the XML sub-structure for a given
kind of notification configuration.
"""
for config in configs:
config_node = s3_xml.SubElement(node, element_name)
if 'Id' in config:
id... | [
"def",
"_add_notification_config_to_xml",
"(",
"node",
",",
"element_name",
",",
"configs",
")",
":",
"for",
"config",
"in",
"configs",
":",
"config_node",
"=",
"s3_xml",
".",
"SubElement",
"(",
"node",
",",
"element_name",
")",
"if",
"'Id'",
"in",
"config",
... | Internal function that builds the XML sub-structure for a given
kind of notification configuration. | [
"Internal",
"function",
"that",
"builds",
"the",
"XML",
"sub",
"-",
"structure",
"for",
"a",
"given",
"kind",
"of",
"notification",
"configuration",
"."
] | python | train | 38.057143 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/schema.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/schema.py#L595-L611 | def giant_text_sqltype(dialect: Dialect) -> str:
"""
Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVARCHAR(MA... | [
"def",
"giant_text_sqltype",
"(",
"dialect",
":",
"Dialect",
")",
"->",
"str",
":",
"if",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"SQLSERVER",
":",
"return",
"'NVARCHAR(MAX)'",
"elif",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"MYSQL"... | Returns the SQL column type used to make very large text columns for a
given dialect.
Args:
dialect: a SQLAlchemy :class:`Dialect`
Returns:
the SQL data type of "giant text", typically 'LONGTEXT' for MySQL
and 'NVARCHAR(MAX)' for SQL Server. | [
"Returns",
"the",
"SQL",
"column",
"type",
"used",
"to",
"make",
"very",
"large",
"text",
"columns",
"for",
"a",
"given",
"dialect",
"."
] | python | train | 33.235294 |
SeleniumHQ/selenium | py/selenium/webdriver/remote/switch_to.py | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/switch_to.py#L125-L141 | def window(self, window_name):
"""
Switches focus to the specified window.
:Args:
- window_name: The name or window handle of the window to switch to.
:Usage:
::
driver.switch_to.window('main')
"""
if self._driver.w3c:
s... | [
"def",
"window",
"(",
"self",
",",
"window_name",
")",
":",
"if",
"self",
".",
"_driver",
".",
"w3c",
":",
"self",
".",
"_w3c_window",
"(",
"window_name",
")",
"return",
"data",
"=",
"{",
"'name'",
":",
"window_name",
"}",
"self",
".",
"_driver",
".",
... | Switches focus to the specified window.
:Args:
- window_name: The name or window handle of the window to switch to.
:Usage:
::
driver.switch_to.window('main') | [
"Switches",
"focus",
"to",
"the",
"specified",
"window",
"."
] | python | train | 26.411765 |
google/grr | grr/server/grr_response_server/client_report_utils.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/client_report_utils.py#L196-L240 | def _FetchMostRecentGraphSeriesFromTheLegacyDB(
label,
report_type,
token = None
):
"""Fetches the latest graph-series for a client label from the legacy DB.
Args:
label: Client label to fetch data for.
report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for.
token: ACL token ... | [
"def",
"_FetchMostRecentGraphSeriesFromTheLegacyDB",
"(",
"label",
",",
"report_type",
",",
"token",
"=",
"None",
")",
":",
"try",
":",
"stats_for_label",
"=",
"aff4",
".",
"FACTORY",
".",
"Open",
"(",
"GetAFF4ClientReportsURN",
"(",
")",
".",
"Add",
"(",
"lab... | Fetches the latest graph-series for a client label from the legacy DB.
Args:
label: Client label to fetch data for.
report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for.
token: ACL token to use for reading from the DB.
Raises:
AFF4AttributeTypeError: If an unexpected report-data t... | [
"Fetches",
"the",
"latest",
"graph",
"-",
"series",
"for",
"a",
"client",
"label",
"from",
"the",
"legacy",
"DB",
"."
] | python | train | 32.4 |
markbaas/python-iresolve | iresolve.py | https://github.com/markbaas/python-iresolve/blob/ba91e37221e91265e4ac5dbc6e8f5cffa955a04f/iresolve.py#L37-L46 | def suppress_output(reverse=False):
"""
Suppress output
"""
if reverse:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
else:
sys.stdout = os.devnull
sys.stderr = os.devnull | [
"def",
"suppress_output",
"(",
"reverse",
"=",
"False",
")",
":",
"if",
"reverse",
":",
"sys",
".",
"stdout",
"=",
"sys",
".",
"__stdout__",
"sys",
".",
"stderr",
"=",
"sys",
".",
"__stderr__",
"else",
":",
"sys",
".",
"stdout",
"=",
"os",
".",
"devn... | Suppress output | [
"Suppress",
"output"
] | python | train | 22.4 |
saltstack/salt | salt/modules/chocolatey.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L614-L647 | def install_python(name, version=None, install_args=None, override_args=False):
'''
Instructs Chocolatey to install a package via Python's easy_install.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defa... | [
"def",
"install_python",
"(",
"name",
",",
"version",
"=",
"None",
",",
"install_args",
"=",
"None",
",",
"override_args",
"=",
"False",
")",
":",
"return",
"install",
"(",
"name",
",",
"version",
"=",
"version",
",",
"source",
"=",
"'python'",
",",
"ins... | Instructs Chocolatey to install a package via Python's easy_install.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
available.
install_args
A list of install argume... | [
"Instructs",
"Chocolatey",
"to",
"install",
"a",
"package",
"via",
"Python",
"s",
"easy_install",
"."
] | python | train | 35.882353 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.