repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
shexSpec/grammar | parsers/python/pyshexc/parser_impl/shex_shape_expression_parser.py | https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/shex_shape_expression_parser.py#L101-L109 | def visitShapeNot(self, ctx: ShExDocParser.ShapeNotContext):
""" shapeNot: negation? shapeAtom """
if ctx.negation():
self.expr = ShapeNot(id=self.label)
sn = ShexShapeExpressionParser(self.context)
sn.visit(ctx.shapeAtom())
self.expr.shapeExpr = sn.expr i... | [
"def",
"visitShapeNot",
"(",
"self",
",",
"ctx",
":",
"ShExDocParser",
".",
"ShapeNotContext",
")",
":",
"if",
"ctx",
".",
"negation",
"(",
")",
":",
"self",
".",
"expr",
"=",
"ShapeNot",
"(",
"id",
"=",
"self",
".",
"label",
")",
"sn",
"=",
"ShexSha... | shapeNot: negation? shapeAtom | [
"shapeNot",
":",
"negation?",
"shapeAtom"
] | python | train |
DeepHorizons/iarm | iarm/arm_instructions/conditional_branch.py | https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/conditional_branch.py#L260-L275 | def BVS(self, params):
"""
BVS label
Branch to the instruction at label if the V flag is set
"""
label = self.get_one_parameter(self.ONE_PARAMETER, params)
self.check_arguments(label_exists=(label,))
# BVS label
def BVS_func():
if self.is_V_... | [
"def",
"BVS",
"(",
"self",
",",
"params",
")",
":",
"label",
"=",
"self",
".",
"get_one_parameter",
"(",
"self",
".",
"ONE_PARAMETER",
",",
"params",
")",
"self",
".",
"check_arguments",
"(",
"label_exists",
"=",
"(",
"label",
",",
")",
")",
"# BVS label... | BVS label
Branch to the instruction at label if the V flag is set | [
"BVS",
"label"
] | python | train |
serge-sans-paille/pythran | docs/papers/sc2013/hyantes_core.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/docs/papers/sc2013/hyantes_core.py#L4-L14 | def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t):
pt = zeros((range_x, range_y, 3))
"omp parallel for private(i,j,k,tmp)"
for i in xrange(range_x):
for j in xrange(range_y):
pt[i,j,0], pt[i,j,1] = (xmin+step*i)*180/math.pi, (ymin+step*j)*180/math.pi
for k in... | [
"def",
"run",
"(",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
",",
"step",
",",
"range_",
",",
"range_x",
",",
"range_y",
",",
"t",
")",
":",
"pt",
"=",
"zeros",
"(",
"(",
"range_x",
",",
"range_y",
",",
"3",
")",
")",
"for",
"i",
"in",
"... | omp parallel for private(i,j,k,tmp) | [
"omp",
"parallel",
"for",
"private",
"(",
"i",
"j",
"k",
"tmp",
")"
] | python | train |
Spinmob/spinmob | _functions.py | https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_functions.py#L1405-L1415 | def submatrix(matrix,i1,i2,j1,j2):
"""
returns the submatrix defined by the index bounds i1-i2 and j1-j2
Endpoints included!
"""
new = []
for i in range(i1,i2+1):
new.append(matrix[i][j1:j2+1])
return _n.array(new) | [
"def",
"submatrix",
"(",
"matrix",
",",
"i1",
",",
"i2",
",",
"j1",
",",
"j2",
")",
":",
"new",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"i1",
",",
"i2",
"+",
"1",
")",
":",
"new",
".",
"append",
"(",
"matrix",
"[",
"i",
"]",
"[",
"... | returns the submatrix defined by the index bounds i1-i2 and j1-j2
Endpoints included! | [
"returns",
"the",
"submatrix",
"defined",
"by",
"the",
"index",
"bounds",
"i1",
"-",
"i2",
"and",
"j1",
"-",
"j2"
] | python | train |
pgmpy/pgmpy | pgmpy/readwrite/BIF.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/BIF.py#L176-L196 | def get_property(self):
"""
Returns the property of the variable
Example
-------------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIFReader("bif_test.bif")
>>> reader.get_property()
{'bowel-problem': ['position = (335, 99)'],
'dog-out'... | [
"def",
"get_property",
"(",
"self",
")",
":",
"variable_properties",
"=",
"{",
"}",
"for",
"block",
"in",
"self",
".",
"variable_block",
"(",
")",
":",
"name",
"=",
"self",
".",
"name_expr",
".",
"searchString",
"(",
"block",
")",
"[",
"0",
"]",
"[",
... | Returns the property of the variable
Example
-------------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIFReader("bif_test.bif")
>>> reader.get_property()
{'bowel-problem': ['position = (335, 99)'],
'dog-out': ['position = (300, 195)'],
'family... | [
"Returns",
"the",
"property",
"of",
"the",
"variable"
] | python | train |
RacingTadpole/django-singleton-admin | django_singleton_admin/admin.py | https://github.com/RacingTadpole/django-singleton-admin/blob/0a81454be11fdcbaf95ca5018667a8dff3f45bf7/django_singleton_admin/admin.py#L44-L55 | def add_view(self, *args, **kwargs):
"""
Redirect to the change view if the singleton instance exists.
"""
try:
singleton = self.model.objects.get()
except (self.model.DoesNotExist, self.model.MultipleObjectsReturned):
kwargs.setdefault("extra_context", {}... | [
"def",
"add_view",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"singleton",
"=",
"self",
".",
"model",
".",
"objects",
".",
"get",
"(",
")",
"except",
"(",
"self",
".",
"model",
".",
"DoesNotExist",
",",
"self",
... | Redirect to the change view if the singleton instance exists. | [
"Redirect",
"to",
"the",
"change",
"view",
"if",
"the",
"singleton",
"instance",
"exists",
"."
] | python | train |
secdev/scapy | scapy/layers/ipsec.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/ipsec.py#L341-L366 | def encrypt(self, sa, esp, key):
"""
Encrypt an ESP packet
@param sa: the SecurityAssociation associated with the ESP packet.
@param esp: an unencrypted _ESPPlain packet with valid padding
@param key: the secret key used for encryption
@return: a valid ESP packet... | [
"def",
"encrypt",
"(",
"self",
",",
"sa",
",",
"esp",
",",
"key",
")",
":",
"data",
"=",
"esp",
".",
"data_for_encryption",
"(",
")",
"if",
"self",
".",
"cipher",
":",
"mode_iv",
"=",
"self",
".",
"_format_mode_iv",
"(",
"algo",
"=",
"self",
",",
"... | Encrypt an ESP packet
@param sa: the SecurityAssociation associated with the ESP packet.
@param esp: an unencrypted _ESPPlain packet with valid padding
@param key: the secret key used for encryption
@return: a valid ESP packet encrypted with this algorithm | [
"Encrypt",
"an",
"ESP",
"packet"
] | python | train |
saltstack/salt | salt/modules/boto_elb.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L1076-L1092 | def _remove_tags(conn, load_balancer_names, tags):
'''
Delete metadata tags for the specified resource ids.
:type load_balancer_names: list
:param load_balancer_names: A list of load balancer names.
:type tags: list
:param tags: A list containing just tag names for the tags to be
... | [
"def",
"_remove_tags",
"(",
"conn",
",",
"load_balancer_names",
",",
"tags",
")",
":",
"params",
"=",
"{",
"}",
"conn",
".",
"build_list_params",
"(",
"params",
",",
"load_balancer_names",
",",
"'LoadBalancerNames.member.%d'",
")",
"conn",
".",
"build_list_params"... | Delete metadata tags for the specified resource ids.
:type load_balancer_names: list
:param load_balancer_names: A list of load balancer names.
:type tags: list
:param tags: A list containing just tag names for the tags to be
deleted. | [
"Delete",
"metadata",
"tags",
"for",
"the",
"specified",
"resource",
"ids",
"."
] | python | train |
TylerTemp/docpie | docpie/__init__.py | https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/__init__.py#L34-L133 | def docpie(doc, argv=None, help=True, version=None,
stdopt=True, attachopt=True, attachvalue=True,
helpstyle='python',
auto2dashes=True, name=None, case_sensitive=False,
optionsfirst=False, appearedonly=False, namedoptions=False,
extra=None):
"""
Parse `arg... | [
"def",
"docpie",
"(",
"doc",
",",
"argv",
"=",
"None",
",",
"help",
"=",
"True",
",",
"version",
"=",
"None",
",",
"stdopt",
"=",
"True",
",",
"attachopt",
"=",
"True",
",",
"attachvalue",
"=",
"True",
",",
"helpstyle",
"=",
"'python'",
",",
"auto2da... | Parse `argv` based on command-line interface described in `doc`.
`docpie` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, commands, which could be
[optional], (required), (mutually | exclusive) or repeat... | [
"Parse",
"argv",
"based",
"on",
"command",
"-",
"line",
"interface",
"described",
"in",
"doc",
"."
] | python | train |
Parquery/icontract | icontract/_represent.py | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L183-L245 | def inspect_decorator(lines: List[str], lineno: int, filename: str) -> DecoratorInspection:
"""
Parse the file in which the decorator is called and figure out the corresponding call AST node.
:param lines: lines of the source file corresponding to the decorator call
:param lineno: line index (starting ... | [
"def",
"inspect_decorator",
"(",
"lines",
":",
"List",
"[",
"str",
"]",
",",
"lineno",
":",
"int",
",",
"filename",
":",
"str",
")",
"->",
"DecoratorInspection",
":",
"if",
"lineno",
"<",
"0",
"or",
"lineno",
">=",
"len",
"(",
"lines",
")",
":",
"rai... | Parse the file in which the decorator is called and figure out the corresponding call AST node.
:param lines: lines of the source file corresponding to the decorator call
:param lineno: line index (starting with 0) of one of the lines in the decorator call
:param filename: name of the file where decorator ... | [
"Parse",
"the",
"file",
"in",
"which",
"the",
"decorator",
"is",
"called",
"and",
"figure",
"out",
"the",
"corresponding",
"call",
"AST",
"node",
"."
] | python | train |
saltstack/salt | salt/modules/nova.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nova.py#L554-L565 | def flavor_access_list(flavor_id, profile=None, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_list flavor_id=ID
'''
conn = _auth(profile, **kwargs)
return conn.flavor_access_list(flavor_id=flavor_id,... | [
"def",
"flavor_access_list",
"(",
"flavor_id",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
",",
"*",
"*",
"kwargs",
")",
"return",
"conn",
".",
"flavor_access_list",
"(",
"flavor_id",
"=",
"flavor... | Return a list of project IDs assigned to flavor ID
CLI Example:
.. code-block:: bash
salt '*' nova.flavor_access_list flavor_id=ID | [
"Return",
"a",
"list",
"of",
"project",
"IDs",
"assigned",
"to",
"flavor",
"ID"
] | python | train |
zyga/python-phablet | phablet.py | https://github.com/zyga/python-phablet/blob/c281045dfb8b55dd2888e1efe9631f72ffc77ac8/phablet.py#L215-L249 | def ssh_cmdline(self, cmd):
"""
Get argument list for meth:`subprocess.Popen()` to run ssh.
:param cmd:
a list of arguments to pass to ssh
:returns:
argument list to pass as the first argument to subprocess.Popen()
.. note::
you must call :me... | [
"def",
"ssh_cmdline",
"(",
"self",
",",
"cmd",
")",
":",
"if",
"not",
"isinstance",
"(",
"cmd",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"cmd needs to be a list\"",
")",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"item",
",",
"str",
")",
"f... | Get argument list for meth:`subprocess.Popen()` to run ssh.
:param cmd:
a list of arguments to pass to ssh
:returns:
argument list to pass as the first argument to subprocess.Popen()
.. note::
you must call :meth:`connect()` at least once
before ... | [
"Get",
"argument",
"list",
"for",
"meth",
":",
"subprocess",
".",
"Popen",
"()",
"to",
"run",
"ssh",
"."
] | python | train |
bids-standard/pybids | bids/layout/layout.py | https://github.com/bids-standard/pybids/blob/30d924ce770622bda0e390d613a8da42a2a20c32/bids/layout/layout.py#L1080-L1136 | def search(self, files=None, defined_fields=None, **kwargs):
"""Search files in the layout by metadata fields.
Args:
files (list): Optional list of names of files to search. If None,
all files in the layout are scanned.
defined_fields (list): Optional list of nam... | [
"def",
"search",
"(",
"self",
",",
"files",
"=",
"None",
",",
"defined_fields",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"defined_fields",
"is",
"None",
":",
"defined_fields",
"=",
"[",
"]",
"all_keys",
"=",
"set",
"(",
"defined_fields",
"... | Search files in the layout by metadata fields.
Args:
files (list): Optional list of names of files to search. If None,
all files in the layout are scanned.
defined_fields (list): Optional list of names of fields that must
be defined in the JSON sidecar in... | [
"Search",
"files",
"in",
"the",
"layout",
"by",
"metadata",
"fields",
"."
] | python | train |
tanghaibao/jcvi | jcvi/apps/restriction.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/restriction.py#L72-L104 | def extract_ends(rec, sites, flank, fw, maxfragsize=800):
"""
Extraction of ends of fragments above certain size.
"""
nsites = len(sites)
size = len(rec)
for i, s in enumerate(sites):
newid = "{0}:{1}".format(rec.name, s)
recs = []
if i == 0 or s - sites[i - 1] <= maxfra... | [
"def",
"extract_ends",
"(",
"rec",
",",
"sites",
",",
"flank",
",",
"fw",
",",
"maxfragsize",
"=",
"800",
")",
":",
"nsites",
"=",
"len",
"(",
"sites",
")",
"size",
"=",
"len",
"(",
"rec",
")",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"sites... | Extraction of ends of fragments above certain size. | [
"Extraction",
"of",
"ends",
"of",
"fragments",
"above",
"certain",
"size",
"."
] | python | train |
IdentityPython/SATOSA | src/satosa/backends/saml2.py | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/saml2.py#L240-L259 | def disco_response(self, context):
"""
Endpoint for the discovery server response
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response
"""
info = context.request
state = cont... | [
"def",
"disco_response",
"(",
"self",
",",
"context",
")",
":",
"info",
"=",
"context",
".",
"request",
"state",
"=",
"context",
".",
"state",
"try",
":",
"entity_id",
"=",
"info",
"[",
"\"entityID\"",
"]",
"except",
"KeyError",
"as",
"err",
":",
"satosa... | Endpoint for the discovery server response
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response | [
"Endpoint",
"for",
"the",
"discovery",
"server",
"response"
] | python | train |
Microsoft/botbuilder-python | libraries/botframework-connector/botframework/connector/auth/jwt_token_validation.py | https://github.com/Microsoft/botbuilder-python/blob/274663dd91c811bae6ac4488915ba5880771b0a7/libraries/botframework-connector/botframework/connector/auth/jwt_token_validation.py#L12-L39 | async def authenticate_request(activity: Activity, auth_header: str, credentials: CredentialProvider) -> ClaimsIdentity:
"""Authenticates the request and sets the service url in the set of trusted urls.
:param activity: The incoming Activity from the Bot Framework or the Emulator
:type ... | [
"async",
"def",
"authenticate_request",
"(",
"activity",
":",
"Activity",
",",
"auth_header",
":",
"str",
",",
"credentials",
":",
"CredentialProvider",
")",
"->",
"ClaimsIdentity",
":",
"if",
"not",
"auth_header",
":",
"# No auth header was sent. We might be on the ano... | Authenticates the request and sets the service url in the set of trusted urls.
:param activity: The incoming Activity from the Bot Framework or the Emulator
:type activity: ~botframework.connector.models.Activity
:param auth_header: The Bearer token included as part of the request
... | [
"Authenticates",
"the",
"request",
"and",
"sets",
"the",
"service",
"url",
"in",
"the",
"set",
"of",
"trusted",
"urls",
".",
":",
"param",
"activity",
":",
"The",
"incoming",
"Activity",
"from",
"the",
"Bot",
"Framework",
"or",
"the",
"Emulator",
":",
"typ... | python | test |
carpedm20/fbchat | fbchat/_client.py | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2000-L2020 | def createPlan(self, plan, thread_id=None):
"""
Sets a plan
:param plan: Plan to set
:param thread_id: User/Group ID to send plan to. See :ref:`intro_threads`
:type plan: models.Plan
:raises: FBchatException if request failed
"""
thread_id, thread_type = ... | [
"def",
"createPlan",
"(",
"self",
",",
"plan",
",",
"thread_id",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"data",
"=",
"{",
"\"event_type\"",
":",
"\"EVENT\"",
",",
"\"eve... | Sets a plan
:param plan: Plan to set
:param thread_id: User/Group ID to send plan to. See :ref:`intro_threads`
:type plan: models.Plan
:raises: FBchatException if request failed | [
"Sets",
"a",
"plan"
] | python | train |
seung-lab/cloud-volume | cloudvolume/lib.py | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/lib.py#L792-L877 | def save_images(image, directory=None, axis='z', channel=None, global_norm=True, image_format='PNG'):
"""
Serialize a 3D or 4D array into a series of PNGs for visualization.
image: A 3D or 4D numpy array. Supported dtypes: integer, float, boolean
axis: 'x', 'y', 'z'
channel: None, 0, 1, 2, etc, which channel... | [
"def",
"save_images",
"(",
"image",
",",
"directory",
"=",
"None",
",",
"axis",
"=",
"'z'",
",",
"channel",
"=",
"None",
",",
"global_norm",
"=",
"True",
",",
"image_format",
"=",
"'PNG'",
")",
":",
"if",
"directory",
"is",
"None",
":",
"directory",
"=... | Serialize a 3D or 4D array into a series of PNGs for visualization.
image: A 3D or 4D numpy array. Supported dtypes: integer, float, boolean
axis: 'x', 'y', 'z'
channel: None, 0, 1, 2, etc, which channel to serialize. Does all by default.
directory: override the default output directory
global_norm: Normaliz... | [
"Serialize",
"a",
"3D",
"or",
"4D",
"array",
"into",
"a",
"series",
"of",
"PNGs",
"for",
"visualization",
"."
] | python | train |
SmokinCaterpillar/pypet | pypet/trajectory.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/trajectory.py#L2327-L2401 | def _merge_links(self, other_trajectory, used_runs, allowed_translations, ignore_data):
""" Merges all links"""
linked_items = other_trajectory._linked_by
run_name_dummys = set([f(-1) for f in other_trajectory._wildcard_functions.values()])
if len(linked_items) > 0:
self._log... | [
"def",
"_merge_links",
"(",
"self",
",",
"other_trajectory",
",",
"used_runs",
",",
"allowed_translations",
",",
"ignore_data",
")",
":",
"linked_items",
"=",
"other_trajectory",
".",
"_linked_by",
"run_name_dummys",
"=",
"set",
"(",
"[",
"f",
"(",
"-",
"1",
"... | Merges all links | [
"Merges",
"all",
"links"
] | python | test |
mitodl/edx-api-client | edx_api/enrollments/__init__.py | https://github.com/mitodl/edx-api-client/blob/083fd23a48b3ef0d39602fc3e7e53ef02f4ad6d6/edx_api/enrollments/__init__.py#L121-L141 | def create_audit_student_enrollment(self, course_id):
"""
Creates an audit enrollment for the user in a given course
Args:
course_id (str): an edX course id
Returns:
Enrollment: object representing the student enrollment in the provided course
"""
... | [
"def",
"create_audit_student_enrollment",
"(",
"self",
",",
"course_id",
")",
":",
"audit_enrollment",
"=",
"{",
"\"mode\"",
":",
"\"audit\"",
",",
"\"course_details\"",
":",
"{",
"\"course_id\"",
":",
"course_id",
"}",
"}",
"# the request is done in behalf of the curre... | Creates an audit enrollment for the user in a given course
Args:
course_id (str): an edX course id
Returns:
Enrollment: object representing the student enrollment in the provided course | [
"Creates",
"an",
"audit",
"enrollment",
"for",
"the",
"user",
"in",
"a",
"given",
"course"
] | python | train |
ambitioninc/newrelic-api | newrelic_api/alert_conditions_infra.py | https://github.com/ambitioninc/newrelic-api/blob/07b4430aa6ae61e4704e2928a6e7a24c76f0f424/newrelic_api/alert_conditions_infra.py#L71-L106 | def show(self, alert_condition_infra_id):
"""
This API endpoint returns an alert condition for infrastucture, identified by its
ID.
:type alert_condition_infra_id: int
:param alert_condition_infra_id: Alert Condition Infra ID
:rtype: dict
:return: The JSON respo... | [
"def",
"show",
"(",
"self",
",",
"alert_condition_infra_id",
")",
":",
"return",
"self",
".",
"_get",
"(",
"url",
"=",
"'{0}alerts/conditions/{1}'",
".",
"format",
"(",
"self",
".",
"URL",
",",
"alert_condition_infra_id",
")",
",",
"headers",
"=",
"self",
".... | This API endpoint returns an alert condition for infrastucture, identified by its
ID.
:type alert_condition_infra_id: int
:param alert_condition_infra_id: Alert Condition Infra ID
:rtype: dict
:return: The JSON response of the API
::
{
"dat... | [
"This",
"API",
"endpoint",
"returns",
"an",
"alert",
"condition",
"for",
"infrastucture",
"identified",
"by",
"its",
"ID",
"."
] | python | train |
uber/tchannel-python | tchannel/peer_heap.py | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/peer_heap.py#L136-L147 | def remove_peer(self, peer):
"""Remove the peer from the heap.
Return: removed peer if peer exists. If peer's index is out of range,
raise IndexError.
"""
if peer.index < 0 or peer.index >= self.size():
raise IndexError('Peer index is out of range')
assert p... | [
"def",
"remove_peer",
"(",
"self",
",",
"peer",
")",
":",
"if",
"peer",
".",
"index",
"<",
"0",
"or",
"peer",
".",
"index",
">=",
"self",
".",
"size",
"(",
")",
":",
"raise",
"IndexError",
"(",
"'Peer index is out of range'",
")",
"assert",
"peer",
"is... | Remove the peer from the heap.
Return: removed peer if peer exists. If peer's index is out of range,
raise IndexError. | [
"Remove",
"the",
"peer",
"from",
"the",
"heap",
"."
] | python | train |
ev3dev/ev3dev-lang-python | ev3dev2/motor.py | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L644-L653 | def ramp_down_sp(self):
"""
Writing sets the ramp down setpoint. Reading returns the current value. Units
are in milliseconds and must be positive. When set to a non-zero value, the
motor speed will decrease from 0 to 100% of `max_speed` over the span of this
setpoint. The actual... | [
"def",
"ramp_down_sp",
"(",
"self",
")",
":",
"self",
".",
"_ramp_down_sp",
",",
"value",
"=",
"self",
".",
"get_attr_int",
"(",
"self",
".",
"_ramp_down_sp",
",",
"'ramp_down_sp'",
")",
"return",
"value"
] | Writing sets the ramp down setpoint. Reading returns the current value. Units
are in milliseconds and must be positive. When set to a non-zero value, the
motor speed will decrease from 0 to 100% of `max_speed` over the span of this
setpoint. The actual ramp time is the ratio of the difference be... | [
"Writing",
"sets",
"the",
"ramp",
"down",
"setpoint",
".",
"Reading",
"returns",
"the",
"current",
"value",
".",
"Units",
"are",
"in",
"milliseconds",
"and",
"must",
"be",
"positive",
".",
"When",
"set",
"to",
"a",
"non",
"-",
"zero",
"value",
"the",
"mo... | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_wp.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_wp.py#L248-L267 | def set_home_location(self):
'''set home location from last map click'''
try:
latlon = self.module('map').click_position
except Exception:
print("No map available")
return
lat = float(latlon[0])
lon = float(latlon[1])
if self.wploader.c... | [
"def",
"set_home_location",
"(",
"self",
")",
":",
"try",
":",
"latlon",
"=",
"self",
".",
"module",
"(",
"'map'",
")",
".",
"click_position",
"except",
"Exception",
":",
"print",
"(",
"\"No map available\"",
")",
"return",
"lat",
"=",
"float",
"(",
"latlo... | set home location from last map click | [
"set",
"home",
"location",
"from",
"last",
"map",
"click"
] | python | train |
openstack/pyghmi | pyghmi/ipmi/oem/lenovo/inventory.py | https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/oem/lenovo/inventory.py#L105-L147 | def parse_inventory_category_entry(raw, fields):
"""Parses one entry in an inventory category.
:param raw: the raw data to the entry. May contain more than one entry,
only one entry will be read in that case.
:param fields: an iterable of EntryField objects to be used for parsing the
... | [
"def",
"parse_inventory_category_entry",
"(",
"raw",
",",
"fields",
")",
":",
"r",
"=",
"raw",
"obj",
"=",
"{",
"}",
"bytes_read",
"=",
"0",
"discard",
"=",
"False",
"for",
"field",
"in",
"fields",
":",
"value",
"=",
"struct",
".",
"unpack_from",
"(",
... | Parses one entry in an inventory category.
:param raw: the raw data to the entry. May contain more than one entry,
only one entry will be read in that case.
:param fields: an iterable of EntryField objects to be used for parsing the
entry.
:returns: dict -- a tuple with ... | [
"Parses",
"one",
"entry",
"in",
"an",
"inventory",
"category",
"."
] | python | train |
Microsoft/malmo | Malmo/samples/Python_examples/human_action.py | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/human_action.py#L205-L222 | def update(self):
'''Called at regular intervals to poll the mouse position to send continuous commands.'''
if self.action_space == 'continuous': # mouse movement only used for continuous action space
if self.world_state and self.world_state.is_mission_running:
if self.mouse_... | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"action_space",
"==",
"'continuous'",
":",
"# mouse movement only used for continuous action space",
"if",
"self",
".",
"world_state",
"and",
"self",
".",
"world_state",
".",
"is_mission_running",
":",
"if",... | Called at regular intervals to poll the mouse position to send continuous commands. | [
"Called",
"at",
"regular",
"intervals",
"to",
"poll",
"the",
"mouse",
"position",
"to",
"send",
"continuous",
"commands",
"."
] | python | train |
bioidiap/gridtk | gridtk/models.py | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/models.py#L127-L156 | def queue(self, new_job_id = None, new_job_name = None, queue_name = None):
"""Sets the status of this job to 'queued' or 'waiting'."""
# update the job id (i.e., when the job is executed in the grid)
if new_job_id is not None:
self.id = new_job_id
if new_job_name is not None:
self.name = n... | [
"def",
"queue",
"(",
"self",
",",
"new_job_id",
"=",
"None",
",",
"new_job_name",
"=",
"None",
",",
"queue_name",
"=",
"None",
")",
":",
"# update the job id (i.e., when the job is executed in the grid)",
"if",
"new_job_id",
"is",
"not",
"None",
":",
"self",
".",
... | Sets the status of this job to 'queued' or 'waiting'. | [
"Sets",
"the",
"status",
"of",
"this",
"job",
"to",
"queued",
"or",
"waiting",
"."
] | python | train |
totalgood/pugnlp | src/pugnlp/util.py | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L189-L238 | def sort_strings(strings, sort_order=None, reverse=False, case_sensitive=False, sort_order_first=True):
"""Sort a list of strings according to the provided sorted list of string prefixes
TODO:
- Provide an option to use `.startswith()` rather than a fixed prefix length (will be much slower)
Argume... | [
"def",
"sort_strings",
"(",
"strings",
",",
"sort_order",
"=",
"None",
",",
"reverse",
"=",
"False",
",",
"case_sensitive",
"=",
"False",
",",
"sort_order_first",
"=",
"True",
")",
":",
"if",
"not",
"case_sensitive",
":",
"sort_order",
"=",
"tuple",
"(",
"... | Sort a list of strings according to the provided sorted list of string prefixes
TODO:
- Provide an option to use `.startswith()` rather than a fixed prefix length (will be much slower)
Arguments:
sort_order_first (bool): Whether strings in sort_order should always preceed "unknown" strings
... | [
"Sort",
"a",
"list",
"of",
"strings",
"according",
"to",
"the",
"provided",
"sorted",
"list",
"of",
"string",
"prefixes"
] | python | train |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L23267-L23302 | def get_properties(self, names):
"""Returns values for a group of properties in one call.
The names of the properties to get are specified using the @a names
argument which is a list of comma-separated property names or
an empty string if all properties are to be returned.
... | [
"def",
"get_properties",
"(",
"self",
",",
"names",
")",
":",
"if",
"not",
"isinstance",
"(",
"names",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"names can only be an instance of type basestring\"",
")",
"(",
"return_values",
",",
"return_names",
"... | Returns values for a group of properties in one call.
The names of the properties to get are specified using the @a names
argument which is a list of comma-separated property names or
an empty string if all properties are to be returned.
Currently the value of this argument is i... | [
"Returns",
"values",
"for",
"a",
"group",
"of",
"properties",
"in",
"one",
"call",
".",
"The",
"names",
"of",
"the",
"properties",
"to",
"get",
"are",
"specified",
"using",
"the",
"@a",
"names",
"argument",
"which",
"is",
"a",
"list",
"of",
"comma",
"-",... | python | train |
numenta/htmresearch | projects/speech_commands/analyze_nonzero.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/speech_commands/analyze_nonzero.py#L194-L214 | def run(pool, expName, name, args):
"""
Runs :func:`analyzeWeightPruning` in parallel and save the results
:param pool: multiprocessing pool
:param expName: Experiment name
:param name: File/Plot name (i.e. 'weight_prunning')
:param args: Argument list to be passed to :func:`analyzeWeightPruning`
:return... | [
"def",
"run",
"(",
"pool",
",",
"expName",
",",
"name",
",",
"args",
")",
":",
"tables",
"=",
"pool",
".",
"map",
"(",
"analyzeWeightPruning",
",",
"args",
")",
"merged",
"=",
"pd",
".",
"concat",
"(",
"tables",
",",
"axis",
"=",
"1",
")",
".",
"... | Runs :func:`analyzeWeightPruning` in parallel and save the results
:param pool: multiprocessing pool
:param expName: Experiment name
:param name: File/Plot name (i.e. 'weight_prunning')
:param args: Argument list to be passed to :func:`analyzeWeightPruning`
:return: panda dataframe with all the results | [
"Runs",
":",
"func",
":",
"analyzeWeightPruning",
"in",
"parallel",
"and",
"save",
"the",
"results"
] | python | train |
noahbenson/pimms | pimms/calculation.py | https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/calculation.py#L104-L114 | def set_meta(self, meta_data):
'''
node.set_meta(meta) yields a calculation node identical to the given node except that its
meta_data attribute has been set to the given dictionary meta. If meta is not persistent,
it is cast to a persistent dictionary first.
'''
if not (... | [
"def",
"set_meta",
"(",
"self",
",",
"meta_data",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"meta_data",
",",
"ps",
".",
"PMap",
")",
"or",
"isinstance",
"(",
"meta_data",
",",
"IMap",
")",
")",
":",
"meta_data",
"=",
"ps",
".",
"pmap",
"(",
"... | node.set_meta(meta) yields a calculation node identical to the given node except that its
meta_data attribute has been set to the given dictionary meta. If meta is not persistent,
it is cast to a persistent dictionary first. | [
"node",
".",
"set_meta",
"(",
"meta",
")",
"yields",
"a",
"calculation",
"node",
"identical",
"to",
"the",
"given",
"node",
"except",
"that",
"its",
"meta_data",
"attribute",
"has",
"been",
"set",
"to",
"the",
"given",
"dictionary",
"meta",
".",
"If",
"met... | python | train |
bcbio/bcbio-nextgen | bcbio/variation/vcfutils.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfutils.py#L680-L690 | def cyvcf_add_filter(rec, name):
"""Add a FILTER value to a cyvcf2 record
"""
if rec.FILTER:
filters = rec.FILTER.split(";")
else:
filters = []
if name not in filters:
filters.append(name)
rec.FILTER = filters
return rec | [
"def",
"cyvcf_add_filter",
"(",
"rec",
",",
"name",
")",
":",
"if",
"rec",
".",
"FILTER",
":",
"filters",
"=",
"rec",
".",
"FILTER",
".",
"split",
"(",
"\";\"",
")",
"else",
":",
"filters",
"=",
"[",
"]",
"if",
"name",
"not",
"in",
"filters",
":",
... | Add a FILTER value to a cyvcf2 record | [
"Add",
"a",
"FILTER",
"value",
"to",
"a",
"cyvcf2",
"record"
] | python | train |
HPENetworking/PYHPEIMC | pyhpeimc/plat/perf.py | https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/perf.py#L101-L130 | def delete_perf_task(task_name, auth, url):
"""
Function takes a str of the target task_name to be deleted and retrieves task_id using
the get_perf_task function. Once the task_id has been successfully retrieved it is
populated into the task_id variable and an DELETE call is made against the HPE IMC RES... | [
"def",
"delete_perf_task",
"(",
"task_name",
",",
"auth",
",",
"url",
")",
":",
"task_id",
"=",
"get_perf_task",
"(",
"task_name",
",",
"auth",
",",
"url",
")",
"if",
"isinstance",
"(",
"task_id",
",",
"str",
")",
":",
"print",
"(",
"\"Perf task doesn't ex... | Function takes a str of the target task_name to be deleted and retrieves task_id using
the get_perf_task function. Once the task_id has been successfully retrieved it is
populated into the task_id variable and an DELETE call is made against the HPE IMC REST
interface to delete the target task.
:param ta... | [
"Function",
"takes",
"a",
"str",
"of",
"the",
"target",
"task_name",
"to",
"be",
"deleted",
"and",
"retrieves",
"task_id",
"using",
"the",
"get_perf_task",
"function",
".",
"Once",
"the",
"task_id",
"has",
"been",
"successfully",
"retrieved",
"it",
"is",
"popu... | python | train |
c0ntrol-x/p4rr0t007 | p4rr0t007/lib/core.py | https://github.com/c0ntrol-x/p4rr0t007/blob/6fe88ec1231a778b9f1d13bc61332581715d646e/p4rr0t007/lib/core.py#L89-L99 | def lpad(s, N, char='\0'):
"""pads a string to the left with null-bytes or any other given character.
..note:: This is used by the :py:func:`xor` function.
:param s: the string
:param N: an integer of how much padding should be done
:returns: the original bytes
"""
assert isinstance(char, ... | [
"def",
"lpad",
"(",
"s",
",",
"N",
",",
"char",
"=",
"'\\0'",
")",
":",
"assert",
"isinstance",
"(",
"char",
",",
"bytes",
")",
"and",
"len",
"(",
"char",
")",
"==",
"1",
",",
"'char should be a string with length 1'",
"return",
"s",
".",
"rjust",
"(",... | pads a string to the left with null-bytes or any other given character.
..note:: This is used by the :py:func:`xor` function.
:param s: the string
:param N: an integer of how much padding should be done
:returns: the original bytes | [
"pads",
"a",
"string",
"to",
"the",
"left",
"with",
"null",
"-",
"bytes",
"or",
"any",
"other",
"given",
"character",
"."
] | python | train |
roboogle/gtkmvc3 | gtkmvco/gtkmvc3/adapters/basic.py | https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L369-L382 | def _write_widget(self, val):
"""Writes value into the widget. If specified, user setter
is invoked."""
self._itsme = True
try:
setter = self._wid_info[self._wid][1]
wtype = self._wid_info[self._wid][2]
if setter:
if wtype is not None:
... | [
"def",
"_write_widget",
"(",
"self",
",",
"val",
")",
":",
"self",
".",
"_itsme",
"=",
"True",
"try",
":",
"setter",
"=",
"self",
".",
"_wid_info",
"[",
"self",
".",
"_wid",
"]",
"[",
"1",
"]",
"wtype",
"=",
"self",
".",
"_wid_info",
"[",
"self",
... | Writes value into the widget. If specified, user setter
is invoked. | [
"Writes",
"value",
"into",
"the",
"widget",
".",
"If",
"specified",
"user",
"setter",
"is",
"invoked",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/distlib/_backport/tarfile.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/tarfile.py#L1016-L1027 | def create_ustar_header(self, info, encoding, errors):
"""Return the object as a ustar header block.
"""
info["magic"] = POSIX_MAGIC
if len(info["linkname"]) > LENGTH_LINK:
raise ValueError("linkname is too long")
if len(info["name"]) > LENGTH_NAME:
info... | [
"def",
"create_ustar_header",
"(",
"self",
",",
"info",
",",
"encoding",
",",
"errors",
")",
":",
"info",
"[",
"\"magic\"",
"]",
"=",
"POSIX_MAGIC",
"if",
"len",
"(",
"info",
"[",
"\"linkname\"",
"]",
")",
">",
"LENGTH_LINK",
":",
"raise",
"ValueError",
... | Return the object as a ustar header block. | [
"Return",
"the",
"object",
"as",
"a",
"ustar",
"header",
"block",
"."
] | python | train |
twisted/mantissa | xmantissa/webnav.py | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webnav.py#L251-L310 | def applicationNavigation(ctx, translator, navigation):
"""
Horizontal, primary-only navigation view.
For the navigation element currently being viewed, copies of the
I{selected-app-tab} and I{selected-tab-contents} patterns will be
loaded from the tag. For all other navigation elements, copies of... | [
"def",
"applicationNavigation",
"(",
"ctx",
",",
"translator",
",",
"navigation",
")",
":",
"setTabURLs",
"(",
"navigation",
",",
"translator",
")",
"selectedTab",
"=",
"getSelectedTab",
"(",
"navigation",
",",
"url",
".",
"URL",
".",
"fromContext",
"(",
"ctx"... | Horizontal, primary-only navigation view.
For the navigation element currently being viewed, copies of the
I{selected-app-tab} and I{selected-tab-contents} patterns will be
loaded from the tag. For all other navigation elements, copies of the
I{app-tab} and I{tab-contents} patterns will be loaded.
... | [
"Horizontal",
"primary",
"-",
"only",
"navigation",
"view",
"."
] | python | train |
linkhub-sdk/popbill.py | popbill/kakaoService.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/kakaoService.py#L289-L351 | def sendFMS_same(self, CorpNum, PlusFriendID, Sender, Content, AltContent, AltSendType, SndDT, FilePath, ImageURL,
KakaoMessages, KakaoButtons, AdsYN=False, UserID=None, RequestNum=None):
"""
친구톡 이미지 대량 전송
:param CorpNum: 팝빌회원 사업자번호
:param PlusFriendID: 플러스친구 아이디
... | [
"def",
"sendFMS_same",
"(",
"self",
",",
"CorpNum",
",",
"PlusFriendID",
",",
"Sender",
",",
"Content",
",",
"AltContent",
",",
"AltSendType",
",",
"SndDT",
",",
"FilePath",
",",
"ImageURL",
",",
"KakaoMessages",
",",
"KakaoButtons",
",",
"AdsYN",
"=",
"Fals... | 친구톡 이미지 대량 전송
:param CorpNum: 팝빌회원 사업자번호
:param PlusFriendID: 플러스친구 아이디
:param Sender: 발신번호
:param Content: [동보] 친구톡 내용
:param AltContent: [동보] 대체문자 내용
:param AltSendType: 대체문자 유형 [공백-미전송, C-알림톡내용, A-대체문자내용]
:param SndDT: 예약일시 [작성형식 : yyyyMMddHHmmss]
:para... | [
"친구톡",
"이미지",
"대량",
"전송",
":",
"param",
"CorpNum",
":",
"팝빌회원",
"사업자번호",
":",
"param",
"PlusFriendID",
":",
"플러스친구",
"아이디",
":",
"param",
"Sender",
":",
"발신번호",
":",
"param",
"Content",
":",
"[",
"동보",
"]",
"친구톡",
"내용",
":",
"param",
"AltContent",
":... | python | train |
PmagPy/PmagPy | programs/thellier_gui.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/thellier_gui.py#L2188-L2199 | def write_preferences_file(self):
"""
Write json preferences file to (platform specific) user data directory,
or PmagPy directory if appdirs module is missing.
"""
user_data_dir = find_pmag_dir.find_user_data_dir("thellier_gui")
if not os.path.exists(user_data_dir):
... | [
"def",
"write_preferences_file",
"(",
"self",
")",
":",
"user_data_dir",
"=",
"find_pmag_dir",
".",
"find_user_data_dir",
"(",
"\"thellier_gui\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"user_data_dir",
")",
":",
"find_pmag_dir",
".",
"make_use... | Write json preferences file to (platform specific) user data directory,
or PmagPy directory if appdirs module is missing. | [
"Write",
"json",
"preferences",
"file",
"to",
"(",
"platform",
"specific",
")",
"user",
"data",
"directory",
"or",
"PmagPy",
"directory",
"if",
"appdirs",
"module",
"is",
"missing",
"."
] | python | train |
openvax/datacache | datacache/database.py | https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database.py#L48-L53 | def table_names(self):
"""Returns names of all tables in the database"""
query = "SELECT name FROM sqlite_master WHERE type='table'"
cursor = self.connection.execute(query)
results = cursor.fetchall()
return [result_tuple[0] for result_tuple in results] | [
"def",
"table_names",
"(",
"self",
")",
":",
"query",
"=",
"\"SELECT name FROM sqlite_master WHERE type='table'\"",
"cursor",
"=",
"self",
".",
"connection",
".",
"execute",
"(",
"query",
")",
"results",
"=",
"cursor",
".",
"fetchall",
"(",
")",
"return",
"[",
... | Returns names of all tables in the database | [
"Returns",
"names",
"of",
"all",
"tables",
"in",
"the",
"database"
] | python | train |
totalgood/pugnlp | src/pugnlp/util.py | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2522-L2549 | def unlistify(n, depth=1, typ=list, get=None):
"""Return the desired element in a list ignoring the rest.
>>> unlistify([1,2,3])
1
>>> unlistify([1,[4, 5, 6],3], get=1)
[4, 5, 6]
>>> unlistify([1,[4, 5, 6],3], depth=2, get=1)
5
>>> unlistify([1,(4, 5, 6),3], depth=2, get=1)
(4, 5, 6... | [
"def",
"unlistify",
"(",
"n",
",",
"depth",
"=",
"1",
",",
"typ",
"=",
"list",
",",
"get",
"=",
"None",
")",
":",
"i",
"=",
"0",
"if",
"depth",
"is",
"None",
":",
"depth",
"=",
"1",
"index_desired",
"=",
"get",
"or",
"0",
"while",
"i",
"<",
"... | Return the desired element in a list ignoring the rest.
>>> unlistify([1,2,3])
1
>>> unlistify([1,[4, 5, 6],3], get=1)
[4, 5, 6]
>>> unlistify([1,[4, 5, 6],3], depth=2, get=1)
5
>>> unlistify([1,(4, 5, 6),3], depth=2, get=1)
(4, 5, 6)
>>> unlistify([1,2,(4, 5, 6)], depth=2, get=2)
... | [
"Return",
"the",
"desired",
"element",
"in",
"a",
"list",
"ignoring",
"the",
"rest",
"."
] | python | train |
xray7224/PyPump | pypump/models/feed.py | https://github.com/xray7224/PyPump/blob/f921f691c39fe021f4fd124b6bc91718c9e49b4a/pypump/models/feed.py#L456-L463 | def major(self):
""" Major inbox feed, contains major activities such as notes and images. """
url = self._subfeed("major")
if "major" in self.url or "minor" in self.url:
return self
if self._major is None:
self._major = self.__class__(url, pypump=self._pump)
... | [
"def",
"major",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_subfeed",
"(",
"\"major\"",
")",
"if",
"\"major\"",
"in",
"self",
".",
"url",
"or",
"\"minor\"",
"in",
"self",
".",
"url",
":",
"return",
"self",
"if",
"self",
".",
"_major",
"is",
"... | Major inbox feed, contains major activities such as notes and images. | [
"Major",
"inbox",
"feed",
"contains",
"major",
"activities",
"such",
"as",
"notes",
"and",
"images",
"."
] | python | train |
oscarbranson/latools | latools/filtering/filt_obj.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/filtering/filt_obj.py#L174-L189 | def clear(self):
"""
Clear all filters.
"""
self.components = {}
self.info = {}
self.params = {}
self.switches = {}
self.keys = {}
self.index = {}
self.sets = {}
self.maxset = -1
self.n = 0
for a in self.analytes:
... | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"components",
"=",
"{",
"}",
"self",
".",
"info",
"=",
"{",
"}",
"self",
".",
"params",
"=",
"{",
"}",
"self",
".",
"switches",
"=",
"{",
"}",
"self",
".",
"keys",
"=",
"{",
"}",
"self",
"."... | Clear all filters. | [
"Clear",
"all",
"filters",
"."
] | python | test |
nkavaldj/myhdl_lib | myhdl_lib/simulation/_DUTer.py | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/simulation/_DUTer.py#L66-L98 | def _getCosimulation(self, func, **kwargs):
''' Returns a co-simulation instance of func.
Uses the _simulator specified by self._simulator.
Enables traces if self._trace is True
func - MyHDL function to be simulated
kwargs - dict of func interface assign... | [
"def",
"_getCosimulation",
"(",
"self",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"vals",
"=",
"{",
"}",
"vals",
"[",
"'topname'",
"]",
"=",
"func",
".",
"func_name",
"vals",
"[",
"'unitname'",
"]",
"=",
"func",
".",
"func_name",
".",
"lower",
... | Returns a co-simulation instance of func.
Uses the _simulator specified by self._simulator.
Enables traces if self._trace is True
func - MyHDL function to be simulated
kwargs - dict of func interface assignments: for signals and parameters | [
"Returns",
"a",
"co",
"-",
"simulation",
"instance",
"of",
"func",
".",
"Uses",
"the",
"_simulator",
"specified",
"by",
"self",
".",
"_simulator",
".",
"Enables",
"traces",
"if",
"self",
".",
"_trace",
"is",
"True",
"func",
"-",
"MyHDL",
"function",
"to",
... | python | train |
couchbase/couchbase-python-client | couchbase/bucketmanager.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L414-L428 | def n1ql_index_create_primary(self, defer=False, ignore_exists=False):
"""
Create the primary index on the bucket.
Equivalent to::
n1ql_index_create('', primary=True, **kwargs)
:param bool defer:
:param bool ignore_exists:
.. seealso:: :meth:`create_index`... | [
"def",
"n1ql_index_create_primary",
"(",
"self",
",",
"defer",
"=",
"False",
",",
"ignore_exists",
"=",
"False",
")",
":",
"return",
"self",
".",
"n1ql_index_create",
"(",
"''",
",",
"defer",
"=",
"defer",
",",
"primary",
"=",
"True",
",",
"ignore_exists",
... | Create the primary index on the bucket.
Equivalent to::
n1ql_index_create('', primary=True, **kwargs)
:param bool defer:
:param bool ignore_exists:
.. seealso:: :meth:`create_index` | [
"Create",
"the",
"primary",
"index",
"on",
"the",
"bucket",
"."
] | python | train |
log2timeline/dfvfs | dfvfs/vfs/vshadow_file_system.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/vshadow_file_system.py#L76-L93 | def FileEntryExistsByPathSpec(self, path_spec):
"""Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): path specification.
Returns:
bool: True if the file entry exists.
"""
store_index = vshadow.VShadowPathSpecGetStoreIndex(path_spec)
# The virt... | [
"def",
"FileEntryExistsByPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"store_index",
"=",
"vshadow",
".",
"VShadowPathSpecGetStoreIndex",
"(",
"path_spec",
")",
"# The virtual root file has not corresponding store index but",
"# should have a location.",
"if",
"store_ind... | Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): path specification.
Returns:
bool: True if the file entry exists. | [
"Determines",
"if",
"a",
"file",
"entry",
"for",
"a",
"path",
"specification",
"exists",
"."
] | python | train |
hyperledger/indy-sdk | vcx/wrappers/python3/vcx/api/connection.py | https://github.com/hyperledger/indy-sdk/blob/55240dc170308d7883c48f03f308130a6d077be6/vcx/wrappers/python3/vcx/api/connection.py#L254-L278 | async def invite_details(self, abbreviated: bool) -> dict:
"""
Get the invite details that were sent or can be sent to the endpoint.
:param abbreviated: abbreviate invite details or not
Example:
phone_number = '8019119191'
connection = await Connection.create('foobar123'... | [
"async",
"def",
"invite_details",
"(",
"self",
",",
"abbreviated",
":",
"bool",
")",
"->",
"dict",
":",
"if",
"not",
"hasattr",
"(",
"Connection",
".",
"invite_details",
",",
"\"cb\"",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"vcx_connection_i... | Get the invite details that were sent or can be sent to the endpoint.
:param abbreviated: abbreviate invite details or not
Example:
phone_number = '8019119191'
connection = await Connection.create('foobar123')
invite_details = await connection.connect(phone_number)
inivt... | [
"Get",
"the",
"invite",
"details",
"that",
"were",
"sent",
"or",
"can",
"be",
"sent",
"to",
"the",
"endpoint",
"."
] | python | train |
AlecAivazis/graphql-over-kafka | nautilus/auth/primitives/passwordHash.py | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/auth/primitives/passwordHash.py#L59-L63 | def coerce(cls, key, value):
"""Ensure that loaded values are PasswordHashes."""
if isinstance(value, PasswordHash):
return value
return super(PasswordHash, cls).coerce(key, value) | [
"def",
"coerce",
"(",
"cls",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"PasswordHash",
")",
":",
"return",
"value",
"return",
"super",
"(",
"PasswordHash",
",",
"cls",
")",
".",
"coerce",
"(",
"key",
",",
"value",
")"... | Ensure that loaded values are PasswordHashes. | [
"Ensure",
"that",
"loaded",
"values",
"are",
"PasswordHashes",
"."
] | python | train |
tcalmant/ipopo | pelix/ipopo/handlers/requires.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L369-L384 | def on_service_arrival(self, svc_ref):
"""
Called when a service has been registered in the framework
:param svc_ref: A service reference
"""
with self._lock:
if self._value is None:
# Inject the service
self.reference = svc_ref
... | [
"def",
"on_service_arrival",
"(",
"self",
",",
"svc_ref",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_value",
"is",
"None",
":",
"# Inject the service",
"self",
".",
"reference",
"=",
"svc_ref",
"self",
".",
"_value",
"=",
"self",
"... | Called when a service has been registered in the framework
:param svc_ref: A service reference | [
"Called",
"when",
"a",
"service",
"has",
"been",
"registered",
"in",
"the",
"framework"
] | python | train |
aliyun/aliyun-log-python-sdk | aliyun/log/logclient.py | https://github.com/aliyun/aliyun-log-python-sdk/blob/ac383db0a16abf1e5ef7df36074374184b43516e/aliyun/log/logclient.py#L639-L666 | def get_cursor(self, project_name, logstore_name, shard_id, start_time):
""" Get cursor from log service for batch pull logs
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
... | [
"def",
"get_cursor",
"(",
"self",
",",
"project_name",
",",
"logstore_name",
",",
"shard_id",
",",
"start_time",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
"params",
"=",
"{",
"'type'",
":",
"'cursor'",
",",
"'from'",
":... | Get cursor from log service for batch pull logs
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the logstore name
:type shard_id: int
... | [
"Get",
"cursor",
"from",
"log",
"service",
"for",
"batch",
"pull",
"logs",
"Unsuccessful",
"opertaion",
"will",
"cause",
"an",
"LogException",
".",
":",
"type",
"project_name",
":",
"string",
":",
"param",
"project_name",
":",
"the",
"Project",
"name",
":",
... | python | train |
ArabellaTech/ydcommon | ydcommon/fab.py | https://github.com/ArabellaTech/ydcommon/blob/4aa105e7b33f379e8f09111497c0e427b189c36c/ydcommon/fab.py#L324-L342 | def copy_s3_bucket(src_bucket_name, src_bucket_secret_key, src_bucket_access_key,
dst_bucket_name, dst_bucket_secret_key, dst_bucket_access_key):
""" Copy S3 bucket directory with CMS data between environments. Operations are done on server. """
with cd(env.remote_path):
tmp_dir = "s3... | [
"def",
"copy_s3_bucket",
"(",
"src_bucket_name",
",",
"src_bucket_secret_key",
",",
"src_bucket_access_key",
",",
"dst_bucket_name",
",",
"dst_bucket_secret_key",
",",
"dst_bucket_access_key",
")",
":",
"with",
"cd",
"(",
"env",
".",
"remote_path",
")",
":",
"tmp_dir"... | Copy S3 bucket directory with CMS data between environments. Operations are done on server. | [
"Copy",
"S3",
"bucket",
"directory",
"with",
"CMS",
"data",
"between",
"environments",
".",
"Operations",
"are",
"done",
"on",
"server",
"."
] | python | train |
pyca/pyopenssl | src/OpenSSL/SSL.py | https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/SSL.py#L1343-L1354 | def set_options(self, options):
"""
Add options. Options set before are not cleared!
This method should be used with the :const:`OP_*` constants.
:param options: The options to add.
:return: The new option bitmask.
"""
if not isinstance(options, integer_types):
... | [
"def",
"set_options",
"(",
"self",
",",
"options",
")",
":",
"if",
"not",
"isinstance",
"(",
"options",
",",
"integer_types",
")",
":",
"raise",
"TypeError",
"(",
"\"options must be an integer\"",
")",
"return",
"_lib",
".",
"SSL_CTX_set_options",
"(",
"self",
... | Add options. Options set before are not cleared!
This method should be used with the :const:`OP_*` constants.
:param options: The options to add.
:return: The new option bitmask. | [
"Add",
"options",
".",
"Options",
"set",
"before",
"are",
"not",
"cleared!",
"This",
"method",
"should",
"be",
"used",
"with",
"the",
":",
"const",
":",
"OP_",
"*",
"constants",
"."
] | python | test |
timstaley/voevent-parse | src/voeventparse/voevent.py | https://github.com/timstaley/voevent-parse/blob/58fc1eb3af5eca23d9e819c727204950615402a7/src/voeventparse/voevent.py#L255-L306 | def add_where_when(voevent, coords, obs_time, observatory_location,
allow_tz_naive_datetime=False):
"""
Add details of an observation to the WhereWhen section.
We
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
coords(:class:`.Position2D`): Sky co-ordi... | [
"def",
"add_where_when",
"(",
"voevent",
",",
"coords",
",",
"obs_time",
",",
"observatory_location",
",",
"allow_tz_naive_datetime",
"=",
"False",
")",
":",
"# .. todo:: Implement TimeError using datetime.timedelta",
"if",
"obs_time",
".",
"tzinfo",
"is",
"not",
"None"... | Add details of an observation to the WhereWhen section.
We
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
coords(:class:`.Position2D`): Sky co-ordinates of event.
obs_time(datetime.datetime): Nominal DateTime of the observation. Must
either be timezone-aware... | [
"Add",
"details",
"of",
"an",
"observation",
"to",
"the",
"WhereWhen",
"section",
"."
] | python | train |
Cadair/jupyter_environment_kernels | environment_kernels/activate_helper.py | https://github.com/Cadair/jupyter_environment_kernels/blob/3da304550b511bda7d5d39280379b5ca39bb31bc/environment_kernels/activate_helper.py#L85-L105 | def source_cmd(args, stdin=None):
"""Simple cmd.exe-specific wrapper around source-foreign.
returns a dict to be used as a new environment
"""
args = list(args)
fpath = locate_binary(args[0])
args[0] = fpath if fpath else args[0]
if not os.path.isfile(args[0]):
raise RuntimeError("C... | [
"def",
"source_cmd",
"(",
"args",
",",
"stdin",
"=",
"None",
")",
":",
"args",
"=",
"list",
"(",
"args",
")",
"fpath",
"=",
"locate_binary",
"(",
"args",
"[",
"0",
"]",
")",
"args",
"[",
"0",
"]",
"=",
"fpath",
"if",
"fpath",
"else",
"args",
"[",... | Simple cmd.exe-specific wrapper around source-foreign.
returns a dict to be used as a new environment | [
"Simple",
"cmd",
".",
"exe",
"-",
"specific",
"wrapper",
"around",
"source",
"-",
"foreign",
"."
] | python | train |
glormph/msstitch | src/app/lookups/sqlite/proteingroups.py | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/lookups/sqlite/proteingroups.py#L79-L85 | def get_proteins_for_peptide(self, psm_id):
"""Returns list of proteins for a passed psm_id"""
protsql = self.get_sql_select(['protein_acc'], 'protein_psm')
protsql = '{0} WHERE psm_id=?'.format(protsql)
cursor = self.get_cursor()
proteins = cursor.execute(protsql, psm_id).fetcha... | [
"def",
"get_proteins_for_peptide",
"(",
"self",
",",
"psm_id",
")",
":",
"protsql",
"=",
"self",
".",
"get_sql_select",
"(",
"[",
"'protein_acc'",
"]",
",",
"'protein_psm'",
")",
"protsql",
"=",
"'{0} WHERE psm_id=?'",
".",
"format",
"(",
"protsql",
")",
"curs... | Returns list of proteins for a passed psm_id | [
"Returns",
"list",
"of",
"proteins",
"for",
"a",
"passed",
"psm_id"
] | python | train |
dpkp/kafka-python | kafka/client_async.py | https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/client_async.py#L418-L435 | def close(self, node_id=None):
"""Close one or all broker connections.
Arguments:
node_id (int, optional): the id of the node to close
"""
with self._lock:
if node_id is None:
self._close()
conns = list(self._conns.values())
... | [
"def",
"close",
"(",
"self",
",",
"node_id",
"=",
"None",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"node_id",
"is",
"None",
":",
"self",
".",
"_close",
"(",
")",
"conns",
"=",
"list",
"(",
"self",
".",
"_conns",
".",
"values",
"(",
")",... | Close one or all broker connections.
Arguments:
node_id (int, optional): the id of the node to close | [
"Close",
"one",
"or",
"all",
"broker",
"connections",
"."
] | python | train |
doconix/django-mako-plus | django_mako_plus/template/adapter.py | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/template/adapter.py#L39-L43 | def name(self):
'''Returns the name of this template (if created from a file) or "string" if not'''
if self.mako_template.filename:
return os.path.basename(self.mako_template.filename)
return 'string' | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"mako_template",
".",
"filename",
":",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"mako_template",
".",
"filename",
")",
"return",
"'string'"
] | Returns the name of this template (if created from a file) or "string" if not | [
"Returns",
"the",
"name",
"of",
"this",
"template",
"(",
"if",
"created",
"from",
"a",
"file",
")",
"or",
"string",
"if",
"not"
] | python | train |
CivicSpleen/ambry | ambry/identity.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/identity.py#L852-L878 | def base62_decode(cls, string):
"""Decode a Base X encoded string into the number.
Arguments:
- `string`: The encoded string
- `alphabet`: The alphabet to use for encoding
Stolen from: http://stackoverflow.com/a/1119769/1144479
"""
alphabet = "0123456789abcdefg... | [
"def",
"base62_decode",
"(",
"cls",
",",
"string",
")",
":",
"alphabet",
"=",
"\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"base",
"=",
"len",
"(",
"alphabet",
")",
"strlen",
"=",
"len",
"(",
"string",
")",
"num",
"=",
"0",
"idx",
"=",
... | Decode a Base X encoded string into the number.
Arguments:
- `string`: The encoded string
- `alphabet`: The alphabet to use for encoding
Stolen from: http://stackoverflow.com/a/1119769/1144479 | [
"Decode",
"a",
"Base",
"X",
"encoded",
"string",
"into",
"the",
"number",
"."
] | python | train |
duniter/duniter-python-api | duniterpy/grammars/output.py | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/grammars/output.py#L109-L117 | def compose(self, parser: Any, grammar: Any = None, attr_of: str = None):
"""
Return the CSV(time) expression as string format
:param parser: Parser instance
:param grammar: Grammar
:param attr_of: Attribute of...
"""
return "CSV({0})".format(self.time) | [
"def",
"compose",
"(",
"self",
",",
"parser",
":",
"Any",
",",
"grammar",
":",
"Any",
"=",
"None",
",",
"attr_of",
":",
"str",
"=",
"None",
")",
":",
"return",
"\"CSV({0})\"",
".",
"format",
"(",
"self",
".",
"time",
")"
] | Return the CSV(time) expression as string format
:param parser: Parser instance
:param grammar: Grammar
:param attr_of: Attribute of... | [
"Return",
"the",
"CSV",
"(",
"time",
")",
"expression",
"as",
"string",
"format"
] | python | train |
msoulier/tftpy | tftpy/TftpPacketTypes.py | https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketTypes.py#L410-L429 | def decode(self):
"Decode self.buffer, populating instance variables and return self."
buflen = len(self.buffer)
tftpassert(buflen >= 4, "malformed ERR packet, too short")
log.debug("Decoding ERR packet, length %s bytes", buflen)
if buflen == 4:
log.debug("Allowing th... | [
"def",
"decode",
"(",
"self",
")",
":",
"buflen",
"=",
"len",
"(",
"self",
".",
"buffer",
")",
"tftpassert",
"(",
"buflen",
">=",
"4",
",",
"\"malformed ERR packet, too short\"",
")",
"log",
".",
"debug",
"(",
"\"Decoding ERR packet, length %s bytes\"",
",",
"... | Decode self.buffer, populating instance variables and return self. | [
"Decode",
"self",
".",
"buffer",
"populating",
"instance",
"variables",
"and",
"return",
"self",
"."
] | python | train |
PyPSA/PyPSA | pypsa/pf.py | https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/pypsa/pf.py#L393-L411 | def network_lpf(network, snapshots=None, skip_pre=False):
"""
Linear power flow for generic network.
Parameters
----------
snapshots : list-like|single snapshot
A subset or an elements of network.snapshots on which to run
the power flow, defaults to network.snapshots
skip_pre: b... | [
"def",
"network_lpf",
"(",
"network",
",",
"snapshots",
"=",
"None",
",",
"skip_pre",
"=",
"False",
")",
":",
"_network_prepare_and_run_pf",
"(",
"network",
",",
"snapshots",
",",
"skip_pre",
",",
"linear",
"=",
"True",
")"
] | Linear power flow for generic network.
Parameters
----------
snapshots : list-like|single snapshot
A subset or an elements of network.snapshots on which to run
the power flow, defaults to network.snapshots
skip_pre: bool, default False
Skip the preliminary steps of computing top... | [
"Linear",
"power",
"flow",
"for",
"generic",
"network",
"."
] | python | train |
couchbase/couchbase-python-client | couchbase/asynchronous/rowsbase.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/asynchronous/rowsbase.py#L66-L80 | def _callback(self, mres):
"""
This is invoked as the row callback.
If 'rows' is true, then we are a row callback, otherwise
the request has ended and it's time to collect the other data
"""
try:
rows = self._process_payload(self.raw.rows)
if rows:... | [
"def",
"_callback",
"(",
"self",
",",
"mres",
")",
":",
"try",
":",
"rows",
"=",
"self",
".",
"_process_payload",
"(",
"self",
".",
"raw",
".",
"rows",
")",
"if",
"rows",
":",
"self",
".",
"on_rows",
"(",
"rows",
")",
"if",
"self",
".",
"raw",
".... | This is invoked as the row callback.
If 'rows' is true, then we are a row callback, otherwise
the request has ended and it's time to collect the other data | [
"This",
"is",
"invoked",
"as",
"the",
"row",
"callback",
".",
"If",
"rows",
"is",
"true",
"then",
"we",
"are",
"a",
"row",
"callback",
"otherwise",
"the",
"request",
"has",
"ended",
"and",
"it",
"s",
"time",
"to",
"collect",
"the",
"other",
"data"
] | python | train |
prompt-toolkit/ptpython | ptpython/python_input.py | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/python_input.py#L330-L337 | def install_code_colorscheme(self, name, style_dict):
"""
Install a new code color scheme.
"""
assert isinstance(name, six.text_type)
assert isinstance(style_dict, dict)
self.code_styles[name] = style_dict | [
"def",
"install_code_colorscheme",
"(",
"self",
",",
"name",
",",
"style_dict",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"six",
".",
"text_type",
")",
"assert",
"isinstance",
"(",
"style_dict",
",",
"dict",
")",
"self",
".",
"code_styles",
"[",
... | Install a new code color scheme. | [
"Install",
"a",
"new",
"code",
"color",
"scheme",
"."
] | python | train |
lepture/flask-oauthlib | flask_oauthlib/provider/oauth1.py | https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L860-L877 | def save_request_token(self, token, request):
"""Save request token to database.
A grantsetter is required, which accepts a token and request
parameters::
def grantsetter(token, request):
grant = Grant(
token=token['oauth_token'],
... | [
"def",
"save_request_token",
"(",
"self",
",",
"token",
",",
"request",
")",
":",
"log",
".",
"debug",
"(",
"'Save request token %r'",
",",
"token",
")",
"self",
".",
"_grantsetter",
"(",
"token",
",",
"request",
")"
] | Save request token to database.
A grantsetter is required, which accepts a token and request
parameters::
def grantsetter(token, request):
grant = Grant(
token=token['oauth_token'],
secret=token['oauth_token_secret'],
... | [
"Save",
"request",
"token",
"to",
"database",
"."
] | python | test |
mdorn/pyinstapaper | pyinstapaper/instapaper.py | https://github.com/mdorn/pyinstapaper/blob/94f5f61ccd07079ba3967f788c555aea1a81cca5/pyinstapaper/instapaper.py#L191-L204 | def _simple_action(self, action=None):
'''Issue a request for an API method whose only param is the obj ID.
:param str action: The name of the action for the resource
:returns: Response from the API
:rtype: dict
'''
if not action:
raise Exception('No simple a... | [
"def",
"_simple_action",
"(",
"self",
",",
"action",
"=",
"None",
")",
":",
"if",
"not",
"action",
":",
"raise",
"Exception",
"(",
"'No simple action defined'",
")",
"path",
"=",
"\"/\"",
".",
"join",
"(",
"[",
"self",
".",
"RESOURCE",
",",
"action",
"]"... | Issue a request for an API method whose only param is the obj ID.
:param str action: The name of the action for the resource
:returns: Response from the API
:rtype: dict | [
"Issue",
"a",
"request",
"for",
"an",
"API",
"method",
"whose",
"only",
"param",
"is",
"the",
"obj",
"ID",
"."
] | python | train |
google/grr | grr/core/grr_response_core/lib/interpolation.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/interpolation.py#L56-L91 | def Substitute(self, pattern):
"""Formats given pattern with this substitution environment.
A pattern can contain placeholders for variables (`%%foo%%`) and scopes
(`%%bar.baz%%`) that are replaced with concrete values in this substiution
environment (specified in the constructor).
Args:
pat... | [
"def",
"Substitute",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"isinstance",
"(",
"pattern",
",",
"bytes",
")",
":",
"substs",
"=",
"[",
"re",
".",
"escape",
"(",
"subst",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
"for",
"subst",
"in",
"self",
... | Formats given pattern with this substitution environment.
A pattern can contain placeholders for variables (`%%foo%%`) and scopes
(`%%bar.baz%%`) that are replaced with concrete values in this substiution
environment (specified in the constructor).
Args:
pattern: A pattern with placeholders to s... | [
"Formats",
"given",
"pattern",
"with",
"this",
"substitution",
"environment",
"."
] | python | train |
markchil/gptools | gptools/kernel/core.py | https://github.com/markchil/gptools/blob/225db52bfe6baef1516529ad22177aa2cf7b71e4/gptools/kernel/core.py#L236-L256 | def set_hyperparams(self, new_params):
"""Sets the free hyperparameters to the new parameter values in new_params.
Parameters
----------
new_params : :py:class:`Array` or other Array-like, (len(:py:attr:`self.free_params`),)
New parameter values, ordered as dictated ... | [
"def",
"set_hyperparams",
"(",
"self",
",",
"new_params",
")",
":",
"new_params",
"=",
"scipy",
".",
"asarray",
"(",
"new_params",
",",
"dtype",
"=",
"float",
")",
"if",
"len",
"(",
"new_params",
")",
"==",
"len",
"(",
"self",
".",
"free_params",
")",
... | Sets the free hyperparameters to the new parameter values in new_params.
Parameters
----------
new_params : :py:class:`Array` or other Array-like, (len(:py:attr:`self.free_params`),)
New parameter values, ordered as dictated by the docstring for the
class. | [
"Sets",
"the",
"free",
"hyperparameters",
"to",
"the",
"new",
"parameter",
"values",
"in",
"new_params",
".",
"Parameters",
"----------",
"new_params",
":",
":",
"py",
":",
"class",
":",
"Array",
"or",
"other",
"Array",
"-",
"like",
"(",
"len",
"(",
":",
... | python | train |
wummel/linkchecker | linkcheck/checker/fileurl.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/checker/fileurl.py#L112-L138 | def build_base_url(self):
"""The URL is normed according to the platform:
- the base URL is made an absolute file:// URL
- under Windows platform the drive specifier is normed
"""
if self.base_url is None:
return
base_url = self.base_url
if not (self... | [
"def",
"build_base_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"base_url",
"is",
"None",
":",
"return",
"base_url",
"=",
"self",
".",
"base_url",
"if",
"not",
"(",
"self",
".",
"parent_url",
"or",
"self",
".",
"base_ref",
"or",
"base_url",
".",
"st... | The URL is normed according to the platform:
- the base URL is made an absolute file:// URL
- under Windows platform the drive specifier is normed | [
"The",
"URL",
"is",
"normed",
"according",
"to",
"the",
"platform",
":",
"-",
"the",
"base",
"URL",
"is",
"made",
"an",
"absolute",
"file",
":",
"//",
"URL",
"-",
"under",
"Windows",
"platform",
"the",
"drive",
"specifier",
"is",
"normed"
] | python | train |
selectel/timecard | timecard/timecard.py | https://github.com/selectel/timecard/blob/cfbd14356511c8d7817750c22acf3164ff0030de/timecard/timecard.py#L556-L592 | def write_line(self, fix=True):
"""
Output line containing values to console and csv file.
Only committed values are written to css file.
:param bool fix: to commit measurement values
"""
cells = []
csv_values = []
for m in self.values():
... | [
"def",
"write_line",
"(",
"self",
",",
"fix",
"=",
"True",
")",
":",
"cells",
"=",
"[",
"]",
"csv_values",
"=",
"[",
"]",
"for",
"m",
"in",
"self",
".",
"values",
"(",
")",
":",
"cells",
".",
"append",
"(",
"m",
".",
"render_value",
"(",
"fix",
... | Output line containing values to console and csv file.
Only committed values are written to css file.
:param bool fix: to commit measurement values | [
"Output",
"line",
"containing",
"values",
"to",
"console",
"and",
"csv",
"file",
".",
"Only",
"committed",
"values",
"are",
"written",
"to",
"css",
"file",
".",
":",
"param",
"bool",
"fix",
":",
"to",
"commit",
"measurement",
"values"
] | python | train |
jldantas/libmft | libmft/api.py | https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/api.py#L641-L654 | def _add_data_attribute(self, data_attr):
"""Add a data attribute to the datastream structure.
Data attributes require processing before they can be interpreted as
datastream. This function grants that it is adding the attribute to
the correct datastream or creating a new datastream if ... | [
"def",
"_add_data_attribute",
"(",
"self",
",",
"data_attr",
")",
":",
"attr_name",
"=",
"data_attr",
".",
"header",
".",
"attr_name",
"stream",
"=",
"self",
".",
"_find_datastream",
"(",
"attr_name",
")",
"if",
"stream",
"is",
"None",
":",
"stream",
"=",
... | Add a data attribute to the datastream structure.
Data attributes require processing before they can be interpreted as
datastream. This function grants that it is adding the attribute to
the correct datastream or creating a new datastream if necessary. | [
"Add",
"a",
"data",
"attribute",
"to",
"the",
"datastream",
"structure",
"."
] | python | train |
chrismattmann/tika-python | tika/tika.py | https://github.com/chrismattmann/tika-python/blob/ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a/tika/tika.py#L285-L300 | def parse(option, urlOrPaths, serverEndpoint=ServerEndpoint, verbose=Verbose, tikaServerJar=TikaServerJar,
responseMimeType='application/json',
services={'meta': '/meta', 'text': '/tika', 'all': '/rmeta'}, rawResponse=False):
'''
Parse the objects and return extracted metadata and/or text i... | [
"def",
"parse",
"(",
"option",
",",
"urlOrPaths",
",",
"serverEndpoint",
"=",
"ServerEndpoint",
",",
"verbose",
"=",
"Verbose",
",",
"tikaServerJar",
"=",
"TikaServerJar",
",",
"responseMimeType",
"=",
"'application/json'",
",",
"services",
"=",
"{",
"'meta'",
"... | Parse the objects and return extracted metadata and/or text in JSON format.
:param option:
:param urlOrPaths:
:param serverEndpoint:
:param verbose:
:param tikaServerJar:
:param responseMimeType:
:param services:
:return: | [
"Parse",
"the",
"objects",
"and",
"return",
"extracted",
"metadata",
"and",
"/",
"or",
"text",
"in",
"JSON",
"format",
".",
":",
"param",
"option",
":",
":",
"param",
"urlOrPaths",
":",
":",
"param",
"serverEndpoint",
":",
":",
"param",
"verbose",
":",
"... | python | train |
HazyResearch/metal | metal/analysis.py | https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L25-L29 | def _conflicted_data_points(L):
"""Returns an indicator vector where ith element = 1 if x_i is labeled by
at least two LFs that give it disagreeing labels."""
m = sparse.diags(np.ravel(L.max(axis=1).todense()))
return np.ravel(np.max(m @ (L != 0) != L, axis=1).astype(int).todense()) | [
"def",
"_conflicted_data_points",
"(",
"L",
")",
":",
"m",
"=",
"sparse",
".",
"diags",
"(",
"np",
".",
"ravel",
"(",
"L",
".",
"max",
"(",
"axis",
"=",
"1",
")",
".",
"todense",
"(",
")",
")",
")",
"return",
"np",
".",
"ravel",
"(",
"np",
".",... | Returns an indicator vector where ith element = 1 if x_i is labeled by
at least two LFs that give it disagreeing labels. | [
"Returns",
"an",
"indicator",
"vector",
"where",
"ith",
"element",
"=",
"1",
"if",
"x_i",
"is",
"labeled",
"by",
"at",
"least",
"two",
"LFs",
"that",
"give",
"it",
"disagreeing",
"labels",
"."
] | python | train |
taskcluster/taskcluster-client.py | taskcluster/queue.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/queue.py#L188-L212 | def scheduleTask(self, *args, **kwargs):
"""
Schedule Defined Task
scheduleTask will schedule a task to be executed, even if it has
unresolved dependencies. A task would otherwise only be scheduled if
its dependencies were resolved.
This is useful if you have defined a ... | [
"def",
"scheduleTask",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"scheduleTask\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Schedule Defined Task
scheduleTask will schedule a task to be executed, even if it has
unresolved dependencies. A task would otherwise only be scheduled if
its dependencies were resolved.
This is useful if you have defined a task that depends on itself or on
some other task tha... | [
"Schedule",
"Defined",
"Task"
] | python | train |
elliterate/capybara.py | capybara/selector/selector.py | https://github.com/elliterate/capybara.py/blob/0c6ae449cc37e4445ec3cd6af95674533beedc6c/capybara/selector/selector.py#L57-L62 | def expression_filters(self):
""" Dict[str, ExpressionFilter]: Returns the expression filters for this selector. """
return {
name: filter for name, filter in iter(self.filters.items())
if isinstance(filter, ExpressionFilter)} | [
"def",
"expression_filters",
"(",
"self",
")",
":",
"return",
"{",
"name",
":",
"filter",
"for",
"name",
",",
"filter",
"in",
"iter",
"(",
"self",
".",
"filters",
".",
"items",
"(",
")",
")",
"if",
"isinstance",
"(",
"filter",
",",
"ExpressionFilter",
... | Dict[str, ExpressionFilter]: Returns the expression filters for this selector. | [
"Dict",
"[",
"str",
"ExpressionFilter",
"]",
":",
"Returns",
"the",
"expression",
"filters",
"for",
"this",
"selector",
"."
] | python | test |
jacebrowning/comparable | comparable/tools.py | https://github.com/jacebrowning/comparable/blob/48455e613650e22412d31109681368fcc479298d/comparable/tools.py#L68-L76 | def sort(base, items):
"""Get a sorted list of items ranked in descending similarity.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: list of items sorted by similarity to the base
"""
return sorted(items, key=base.similarity, re... | [
"def",
"sort",
"(",
"base",
",",
"items",
")",
":",
"return",
"sorted",
"(",
"items",
",",
"key",
"=",
"base",
".",
"similarity",
",",
"reverse",
"=",
"True",
")"
] | Get a sorted list of items ranked in descending similarity.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: list of items sorted by similarity to the base | [
"Get",
"a",
"sorted",
"list",
"of",
"items",
"ranked",
"in",
"descending",
"similarity",
"."
] | python | train |
arne-cl/discoursegraphs | src/discoursegraphs/readwrite/brat.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/brat.py#L41-L101 | def brat_output(docgraph, layer=None, show_relations=True):
"""
converts a document graph with pointing chains into a string representation
of a brat *.ann file.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph which might contain pointing chains (e.g. coreferenc... | [
"def",
"brat_output",
"(",
"docgraph",
",",
"layer",
"=",
"None",
",",
"show_relations",
"=",
"True",
")",
":",
"# we can't rely on the .ns attribute of a merged graph",
"if",
"layer",
":",
"namespace",
"=",
"dg",
".",
"layer2namespace",
"(",
"layer",
")",
"else",... | converts a document graph with pointing chains into a string representation
of a brat *.ann file.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph which might contain pointing chains (e.g. coreference links)
layer : str or None
the name of the layer that cont... | [
"converts",
"a",
"document",
"graph",
"with",
"pointing",
"chains",
"into",
"a",
"string",
"representation",
"of",
"a",
"brat",
"*",
".",
"ann",
"file",
"."
] | python | train |
m32/endesive | endesive/pdf/fpdf/fpdf.py | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L890-L955 | def write(self, h, txt='', link=''):
"Output text in flowing mode"
txt = self.normalize_text(txt)
cw=self.current_font['cw']
w=self.w-self.r_margin-self.x
wmax=(w-2*self.c_margin)*1000.0/self.font_size
s=txt.replace("\r",'')
nb=len(s)
sep=-1
i=0
... | [
"def",
"write",
"(",
"self",
",",
"h",
",",
"txt",
"=",
"''",
",",
"link",
"=",
"''",
")",
":",
"txt",
"=",
"self",
".",
"normalize_text",
"(",
"txt",
")",
"cw",
"=",
"self",
".",
"current_font",
"[",
"'cw'",
"]",
"w",
"=",
"self",
".",
"w",
... | Output text in flowing mode | [
"Output",
"text",
"in",
"flowing",
"mode"
] | python | train |
ReFirmLabs/binwalk | src/binwalk/plugins/unpfs.py | https://github.com/ReFirmLabs/binwalk/blob/a0c5315fd2bae167e5c3d8469ce95d5defc743c2/src/binwalk/plugins/unpfs.py#L33-L40 | def _get_fname_len(self, bufflen=128):
"""Returns the number of bytes designated for the filename."""
buff = self.meta.peek(bufflen)
strlen = buff.find('\0')
for i, b in enumerate(buff[strlen:]):
if b != '\0':
return strlen+i
return bufflen | [
"def",
"_get_fname_len",
"(",
"self",
",",
"bufflen",
"=",
"128",
")",
":",
"buff",
"=",
"self",
".",
"meta",
".",
"peek",
"(",
"bufflen",
")",
"strlen",
"=",
"buff",
".",
"find",
"(",
"'\\0'",
")",
"for",
"i",
",",
"b",
"in",
"enumerate",
"(",
"... | Returns the number of bytes designated for the filename. | [
"Returns",
"the",
"number",
"of",
"bytes",
"designated",
"for",
"the",
"filename",
"."
] | python | train |
Stewori/pytypes | pytypes/util.py | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/util.py#L551-L568 | def getmodule(code):
"""More robust variant of inspect.getmodule.
E.g. has less issues on Jython.
"""
try:
md = inspect.getmodule(code, code.co_filename)
except AttributeError:
return inspect.getmodule(code)
if md is None:
# Jython-specific:
# This is currently ju... | [
"def",
"getmodule",
"(",
"code",
")",
":",
"try",
":",
"md",
"=",
"inspect",
".",
"getmodule",
"(",
"code",
",",
"code",
".",
"co_filename",
")",
"except",
"AttributeError",
":",
"return",
"inspect",
".",
"getmodule",
"(",
"code",
")",
"if",
"md",
"is"... | More robust variant of inspect.getmodule.
E.g. has less issues on Jython. | [
"More",
"robust",
"variant",
"of",
"inspect",
".",
"getmodule",
".",
"E",
".",
"g",
".",
"has",
"less",
"issues",
"on",
"Jython",
"."
] | python | train |
totalgood/nlpia | src/nlpia/regexes.py | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/regexes.py#L127-L135 | def to_tsv():
""" Save all regular expressions to a tsv file so they can be more easily copy/pasted in Sublime """
with open(os.path.join(DATA_PATH, 'regexes.tsv'), mode='wt') as fout:
vars = copy.copy(tuple(globals().items()))
for k, v in vars:
if k.lower().startswith('cre_'):
... | [
"def",
"to_tsv",
"(",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"DATA_PATH",
",",
"'regexes.tsv'",
")",
",",
"mode",
"=",
"'wt'",
")",
"as",
"fout",
":",
"vars",
"=",
"copy",
".",
"copy",
"(",
"tuple",
"(",
"globals",
"(... | Save all regular expressions to a tsv file so they can be more easily copy/pasted in Sublime | [
"Save",
"all",
"regular",
"expressions",
"to",
"a",
"tsv",
"file",
"so",
"they",
"can",
"be",
"more",
"easily",
"copy",
"/",
"pasted",
"in",
"Sublime"
] | python | train |
docker/docker-py | docker/api/exec_api.py | https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/api/exec_api.py#L9-L80 | def exec_create(self, container, cmd, stdout=True, stderr=True,
stdin=False, tty=False, privileged=False, user='',
environment=None, workdir=None, detach_keys=None):
"""
Sets up an exec instance in a running container.
Args:
container (str): T... | [
"def",
"exec_create",
"(",
"self",
",",
"container",
",",
"cmd",
",",
"stdout",
"=",
"True",
",",
"stderr",
"=",
"True",
",",
"stdin",
"=",
"False",
",",
"tty",
"=",
"False",
",",
"privileged",
"=",
"False",
",",
"user",
"=",
"''",
",",
"environment"... | Sets up an exec instance in a running container.
Args:
container (str): Target container where exec instance will be
created
cmd (str or list): Command to be executed
stdout (bool): Attach to stdout. Default: ``True``
stderr (bool): Attach to stde... | [
"Sets",
"up",
"an",
"exec",
"instance",
"in",
"a",
"running",
"container",
"."
] | python | train |
google/grr | grr/server/grr_response_server/bigquery.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/bigquery.py#L167-L220 | def InsertData(self, table_id, fd, schema, job_id):
"""Insert data into a bigquery table.
If the table specified doesn't exist, it will be created with the specified
schema.
Args:
table_id: string table id
fd: open file descriptor containing the newline separated JSON
schema: BigQuer... | [
"def",
"InsertData",
"(",
"self",
",",
"table_id",
",",
"fd",
",",
"schema",
",",
"job_id",
")",
":",
"configuration",
"=",
"{",
"\"schema\"",
":",
"{",
"\"fields\"",
":",
"schema",
"}",
",",
"\"destinationTable\"",
":",
"{",
"\"projectId\"",
":",
"self",
... | Insert data into a bigquery table.
If the table specified doesn't exist, it will be created with the specified
schema.
Args:
table_id: string table id
fd: open file descriptor containing the newline separated JSON
schema: BigQuery schema dict
job_id: string job id
Returns:
... | [
"Insert",
"data",
"into",
"a",
"bigquery",
"table",
"."
] | python | train |
apache/incubator-heron | heron/tools/tracker/src/python/tracker.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L182-L186 | def getTopologiesForStateLocation(self, name):
"""
Returns all the topologies for a given state manager.
"""
return filter(lambda t: t.state_manager_name == name, self.topologies) | [
"def",
"getTopologiesForStateLocation",
"(",
"self",
",",
"name",
")",
":",
"return",
"filter",
"(",
"lambda",
"t",
":",
"t",
".",
"state_manager_name",
"==",
"name",
",",
"self",
".",
"topologies",
")"
] | Returns all the topologies for a given state manager. | [
"Returns",
"all",
"the",
"topologies",
"for",
"a",
"given",
"state",
"manager",
"."
] | python | valid |
g2p/bedup | bedup/dedup.py | https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/dedup.py#L120-L186 | def find_inodes_in_use(fds):
"""
Find which of these inodes are in use, and give their open modes.
Does not count the passed fds as an use of the inode they point to,
but if the current process has the same inodes open with different
file descriptors these will be listed.
Looks at /proc/*/fd a... | [
"def",
"find_inodes_in_use",
"(",
"fds",
")",
":",
"self_pid",
"=",
"os",
".",
"getpid",
"(",
")",
"id_fd_assoc",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"fd",
"in",
"fds",
":",
"st",
"=",
"os",
".",
"fstat",
"(",
"fd",
")",
... | Find which of these inodes are in use, and give their open modes.
Does not count the passed fds as an use of the inode they point to,
but if the current process has the same inodes open with different
file descriptors these will be listed.
Looks at /proc/*/fd and /proc/*/map_files (Linux 3.3).
Con... | [
"Find",
"which",
"of",
"these",
"inodes",
"are",
"in",
"use",
"and",
"give",
"their",
"open",
"modes",
"."
] | python | train |
fdb/aufmachen | aufmachen/BeautifulSoup.py | https://github.com/fdb/aufmachen/blob/f2986a0cf087ac53969f82b84d872e3f1c6986f4/aufmachen/BeautifulSoup.py#L778-L793 | def decompose(self):
"""Recursively destroys the contents of this tree."""
self.extract()
if len(self.contents) == 0:
return
current = self.contents[0]
while current is not None:
next = current.next
if isinstance(current, Tag):
... | [
"def",
"decompose",
"(",
"self",
")",
":",
"self",
".",
"extract",
"(",
")",
"if",
"len",
"(",
"self",
".",
"contents",
")",
"==",
"0",
":",
"return",
"current",
"=",
"self",
".",
"contents",
"[",
"0",
"]",
"while",
"current",
"is",
"not",
"None",
... | Recursively destroys the contents of this tree. | [
"Recursively",
"destroys",
"the",
"contents",
"of",
"this",
"tree",
"."
] | python | train |
raymondEhlers/pachyderm | pachyderm/yaml.py | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/yaml.py#L156-L181 | def enum_to_yaml(cls: Type[T_EnumToYAML], representer: Representer, data: T_EnumToYAML) -> ruamel.yaml.nodes.ScalarNode:
""" Encodes YAML representation.
This is a mixin method for writing enum values to YAML. It needs to be added to the enum
as a classmethod. See the module docstring for further informati... | [
"def",
"enum_to_yaml",
"(",
"cls",
":",
"Type",
"[",
"T_EnumToYAML",
"]",
",",
"representer",
":",
"Representer",
",",
"data",
":",
"T_EnumToYAML",
")",
"->",
"ruamel",
".",
"yaml",
".",
"nodes",
".",
"ScalarNode",
":",
"return",
"representer",
".",
"repre... | Encodes YAML representation.
This is a mixin method for writing enum values to YAML. It needs to be added to the enum
as a classmethod. See the module docstring for further information on this approach and how
to implement it.
This method writes whatever is used in the string representation of the YAM... | [
"Encodes",
"YAML",
"representation",
"."
] | python | train |
CityOfZion/neo-python | neo/Core/State/UnspentCoinState.py | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/UnspentCoinState.py#L43-L52 | def Size(self):
"""
Get the total size in bytes of the object.
Returns:
int: size.
"""
# Items should be an array of type CoinState, not of ints!
corrected_items = list(map(lambda i: CoinState(i), self.Items))
return super(UnspentCoinState, self).Size... | [
"def",
"Size",
"(",
"self",
")",
":",
"# Items should be an array of type CoinState, not of ints!",
"corrected_items",
"=",
"list",
"(",
"map",
"(",
"lambda",
"i",
":",
"CoinState",
"(",
"i",
")",
",",
"self",
".",
"Items",
")",
")",
"return",
"super",
"(",
... | Get the total size in bytes of the object.
Returns:
int: size. | [
"Get",
"the",
"total",
"size",
"in",
"bytes",
"of",
"the",
"object",
"."
] | python | train |
QInfer/python-qinfer | src/qinfer/domains.py | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L493-L503 | def n_members(self):
"""
Returns the number of members in the domain if it
`is_finite`, otherwise, returns `np.inf`.
:type: ``int`` or ``np.inf``
"""
if self.is_finite:
return int(self.max - self.min + 1)
else:
return np.inf | [
"def",
"n_members",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_finite",
":",
"return",
"int",
"(",
"self",
".",
"max",
"-",
"self",
".",
"min",
"+",
"1",
")",
"else",
":",
"return",
"np",
".",
"inf"
] | Returns the number of members in the domain if it
`is_finite`, otherwise, returns `np.inf`.
:type: ``int`` or ``np.inf`` | [
"Returns",
"the",
"number",
"of",
"members",
"in",
"the",
"domain",
"if",
"it",
"is_finite",
"otherwise",
"returns",
"np",
".",
"inf",
"."
] | python | train |
inasafe/inasafe | safe/report/processors/default.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/processors/default.py#L716-L781 | def atlas_renderer(layout, coverage_layer, output_path, file_format):
"""Extract composition using atlas generation.
:param layout: QGIS Print Layout object used for producing the report.
:type layout: qgis.core.QgsPrintLayout
:param coverage_layer: Coverage Layer used for atlas map.
:type coverag... | [
"def",
"atlas_renderer",
"(",
"layout",
",",
"coverage_layer",
",",
"output_path",
",",
"file_format",
")",
":",
"# set the composer map to be atlas driven",
"composer_map",
"=",
"layout_item",
"(",
"layout",
",",
"'impact-map'",
",",
"QgsLayoutItemMap",
")",
"composer_... | Extract composition using atlas generation.
:param layout: QGIS Print Layout object used for producing the report.
:type layout: qgis.core.QgsPrintLayout
:param coverage_layer: Coverage Layer used for atlas map.
:type coverage_layer: QgsMapLayer
:param output_path: The output path of the product.... | [
"Extract",
"composition",
"using",
"atlas",
"generation",
"."
] | python | train |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L133-L160 | def store(self, name, value, atype, new_name=None, multiplier=None, allowed_values=None):
''' store a config value in a dictionary, these values are used to populate a trasnfer spec
validation -- check type, check allowed values and rename if required '''
if value is not None:
_b... | [
"def",
"store",
"(",
"self",
",",
"name",
",",
"value",
",",
"atype",
",",
"new_name",
"=",
"None",
",",
"multiplier",
"=",
"None",
",",
"allowed_values",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"_bad_type",
"=",
"(",
"not",
... | store a config value in a dictionary, these values are used to populate a trasnfer spec
validation -- check type, check allowed values and rename if required | [
"store",
"a",
"config",
"value",
"in",
"a",
"dictionary",
"these",
"values",
"are",
"used",
"to",
"populate",
"a",
"trasnfer",
"spec",
"validation",
"--",
"check",
"type",
"check",
"allowed",
"values",
"and",
"rename",
"if",
"required"
] | python | train |
dwavesystems/penaltymodel | penaltymodel_core/penaltymodel/core/classes/specification.py | https://github.com/dwavesystems/penaltymodel/blob/b9d343233aea8df0f59cea45a07f12d0b3b8d9b3/penaltymodel_core/penaltymodel/core/classes/specification.py#L210-L237 | def _check_ising_quadratic_ranges(quad_ranges, graph):
"""check correctness/populate defaults for ising_quadratic_ranges."""
if quad_ranges is None:
quad_ranges = {}
# first just populate the top level so we can rely on the structure
for u in graph:
if u not in q... | [
"def",
"_check_ising_quadratic_ranges",
"(",
"quad_ranges",
",",
"graph",
")",
":",
"if",
"quad_ranges",
"is",
"None",
":",
"quad_ranges",
"=",
"{",
"}",
"# first just populate the top level so we can rely on the structure",
"for",
"u",
"in",
"graph",
":",
"if",
"u",
... | check correctness/populate defaults for ising_quadratic_ranges. | [
"check",
"correctness",
"/",
"populate",
"defaults",
"for",
"ising_quadratic_ranges",
"."
] | python | train |
orbingol/NURBS-Python | geomdl/helpers.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L115-L137 | def find_multiplicity(knot, knot_vector, **kwargs):
""" Finds knot multiplicity over the knot vector.
Keyword Arguments:
* ``tol``: tolerance (delta) value for equality checking
:param knot: knot or parameter, :math:`u`
:type knot: float
:param knot_vector: knot vector, :math:`U`
:type... | [
"def",
"find_multiplicity",
"(",
"knot",
",",
"knot_vector",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get tolerance value",
"tol",
"=",
"kwargs",
".",
"get",
"(",
"'tol'",
",",
"10e-8",
")",
"mult",
"=",
"0",
"# initial multiplicity",
"for",
"kv",
"in",
"knot... | Finds knot multiplicity over the knot vector.
Keyword Arguments:
* ``tol``: tolerance (delta) value for equality checking
:param knot: knot or parameter, :math:`u`
:type knot: float
:param knot_vector: knot vector, :math:`U`
:type knot_vector: list, tuple
:return: knot multiplicity, :m... | [
"Finds",
"knot",
"multiplicity",
"over",
"the",
"knot",
"vector",
"."
] | python | train |
chriso/gauged | gauged/drivers/mysql.py | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/mysql.py#L299-L307 | def get_namespace_statistics(self, namespace, start_offset, end_offset):
"""Get namespace statistics for the period between start_offset and
end_offset (inclusive)"""
cursor = self.cursor
cursor.execute('SELECT SUM(data_points), SUM(byte_count) '
'FROM gauged_stati... | [
"def",
"get_namespace_statistics",
"(",
"self",
",",
"namespace",
",",
"start_offset",
",",
"end_offset",
")",
":",
"cursor",
"=",
"self",
".",
"cursor",
"cursor",
".",
"execute",
"(",
"'SELECT SUM(data_points), SUM(byte_count) '",
"'FROM gauged_statistics WHERE namespace... | Get namespace statistics for the period between start_offset and
end_offset (inclusive) | [
"Get",
"namespace",
"statistics",
"for",
"the",
"period",
"between",
"start_offset",
"and",
"end_offset",
"(",
"inclusive",
")"
] | python | train |
TeamHG-Memex/eli5 | eli5/sklearn/explain_weights.py | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_weights.py#L329-L377 | def explain_decision_tree(estimator,
vec=None,
top=_TOP,
target_names=None,
targets=None, # ignored
feature_names=None,
feature_re=None,
... | [
"def",
"explain_decision_tree",
"(",
"estimator",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"_TOP",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"# ignored",
"feature_names",
"=",
"None",
",",
"feature_re",
"=",
"None",
",",
"feature... | Return an explanation of a decision tree.
See :func:`eli5.explain_weights` for description of
``top``, ``target_names``, ``feature_names``,
``feature_re`` and ``feature_filter`` parameters.
``targets`` parameter is ignored.
``vec`` is a vectorizer instance used to transform
raw features to th... | [
"Return",
"an",
"explanation",
"of",
"a",
"decision",
"tree",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/common_video.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_video.py#L128-L156 | def scheduled_sample_count(ground_truth_x,
generated_x,
batch_size,
scheduled_sample_var):
"""Sample batch with specified mix of groundtruth and generated data points.
Args:
ground_truth_x: tensor of ground-truth data points.
... | [
"def",
"scheduled_sample_count",
"(",
"ground_truth_x",
",",
"generated_x",
",",
"batch_size",
",",
"scheduled_sample_var",
")",
":",
"num_ground_truth",
"=",
"scheduled_sample_var",
"idx",
"=",
"tf",
".",
"random_shuffle",
"(",
"tf",
".",
"range",
"(",
"batch_size"... | Sample batch with specified mix of groundtruth and generated data points.
Args:
ground_truth_x: tensor of ground-truth data points.
generated_x: tensor of generated data points.
batch_size: batch size
scheduled_sample_var: number of ground-truth examples to include in batch.
Returns:
New batch ... | [
"Sample",
"batch",
"with",
"specified",
"mix",
"of",
"groundtruth",
"and",
"generated",
"data",
"points",
"."
] | python | train |
mikedh/trimesh | trimesh/path/path.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/path.py#L651-L663 | def discrete(self):
"""
A sequence of connected vertices in space, corresponding to
self.paths.
Returns
---------
discrete : (len(self.paths),)
A sequence of (m*, dimension) float
"""
discrete = np.array([self.discretize_path(i)
... | [
"def",
"discrete",
"(",
"self",
")",
":",
"discrete",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"discretize_path",
"(",
"i",
")",
"for",
"i",
"in",
"self",
".",
"paths",
"]",
")",
"return",
"discrete"
] | A sequence of connected vertices in space, corresponding to
self.paths.
Returns
---------
discrete : (len(self.paths),)
A sequence of (m*, dimension) float | [
"A",
"sequence",
"of",
"connected",
"vertices",
"in",
"space",
"corresponding",
"to",
"self",
".",
"paths",
"."
] | python | train |
amzn/ion-python | amazon/ion/reader_text.py | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L482-L493 | def set_annotation(self):
"""Appends the context's ``pending_symbol`` to its ``annotations`` sequence."""
assert self.pending_symbol is not None
assert not self.value
annotations = (_as_symbol(self.pending_symbol, is_symbol_value=False),) # pending_symbol becomes an annotation
s... | [
"def",
"set_annotation",
"(",
"self",
")",
":",
"assert",
"self",
".",
"pending_symbol",
"is",
"not",
"None",
"assert",
"not",
"self",
".",
"value",
"annotations",
"=",
"(",
"_as_symbol",
"(",
"self",
".",
"pending_symbol",
",",
"is_symbol_value",
"=",
"Fals... | Appends the context's ``pending_symbol`` to its ``annotations`` sequence. | [
"Appends",
"the",
"context",
"s",
"pending_symbol",
"to",
"its",
"annotations",
"sequence",
"."
] | python | train |
timdiels/pytil | pytil/path.py | https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/path.py#L91-L146 | def chmod(path, mode, operator='=', recursive=False):
'''
Change file mode bits.
When recursively chmodding a directory, executable bits in ``mode`` are
ignored when applying to a regular file. E.g. ``chmod(path, mode=0o777,
recursive=True)`` would apply ``mode=0o666`` to regular files.
Symlin... | [
"def",
"chmod",
"(",
"path",
",",
"mode",
",",
"operator",
"=",
"'='",
",",
"recursive",
"=",
"False",
")",
":",
"if",
"mode",
">",
"0o777",
"and",
"operator",
"!=",
"'='",
":",
"raise",
"ValueError",
"(",
"'Special bits (i.e. >0o777) only supported when using... | Change file mode bits.
When recursively chmodding a directory, executable bits in ``mode`` are
ignored when applying to a regular file. E.g. ``chmod(path, mode=0o777,
recursive=True)`` would apply ``mode=0o666`` to regular files.
Symlinks are ignored.
Parameters
----------
path : ~pathlib... | [
"Change",
"file",
"mode",
"bits",
"."
] | python | train |
jobovy/galpy | galpy/df/streamdf.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamdf.py#L3077-L3090 | def sample_t(self,n):
"""
NAME:
sample_t
PURPOSE:
generate a stripping time (time since stripping); simple implementation could be replaced by more complicated distributions in sub-classes of streamdf
INPUT:
n - number of points to return
OUTPUT:... | [
"def",
"sample_t",
"(",
"self",
",",
"n",
")",
":",
"return",
"numpy",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"n",
")",
"*",
"self",
".",
"_tdisrupt"
] | NAME:
sample_t
PURPOSE:
generate a stripping time (time since stripping); simple implementation could be replaced by more complicated distributions in sub-classes of streamdf
INPUT:
n - number of points to return
OUTPUT:
array of n stripping times
... | [
"NAME",
":",
"sample_t",
"PURPOSE",
":",
"generate",
"a",
"stripping",
"time",
"(",
"time",
"since",
"stripping",
")",
";",
"simple",
"implementation",
"could",
"be",
"replaced",
"by",
"more",
"complicated",
"distributions",
"in",
"sub",
"-",
"classes",
"of",
... | python | train |
Clinical-Genomics/scout | scout/server/blueprints/variants/controllers.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/server/blueprints/variants/controllers.py#L864-L871 | def callers(variant_obj, category='snv'):
"""Return info about callers."""
calls = set()
for caller in CALLERS[category]:
if variant_obj.get(caller['id']):
calls.add((caller['name'], variant_obj[caller['id']]))
return list(calls) | [
"def",
"callers",
"(",
"variant_obj",
",",
"category",
"=",
"'snv'",
")",
":",
"calls",
"=",
"set",
"(",
")",
"for",
"caller",
"in",
"CALLERS",
"[",
"category",
"]",
":",
"if",
"variant_obj",
".",
"get",
"(",
"caller",
"[",
"'id'",
"]",
")",
":",
"... | Return info about callers. | [
"Return",
"info",
"about",
"callers",
"."
] | python | test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.