repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
quantum5/2048 | _2048/manager.py | https://github.com/quantum5/2048/blob/93ada2e3026eaf154e1bbee943d0500c9253e66f/_2048/manager.py#L88-L91 | def new_game(self):
"""Creates a new game of 2048."""
self.game = self.game_class(self, self.screen)
self.save() | [
"def",
"new_game",
"(",
"self",
")",
":",
"self",
".",
"game",
"=",
"self",
".",
"game_class",
"(",
"self",
",",
"self",
".",
"screen",
")",
"self",
".",
"save",
"(",
")"
] | Creates a new game of 2048. | [
"Creates",
"a",
"new",
"game",
"of",
"2048",
"."
] | python | train | 33.25 |
Esri/ArcREST | src/arcrest/common/geometry.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/geometry.py#L130-L134 | def asArcPyObject(self):
""" returns the Point as an ESRI arcpy.Point object """
if arcpyFound == False:
raise Exception("ArcPy is required to use this function")
return arcpy.AsShape(self.asDictionary, True) | [
"def",
"asArcPyObject",
"(",
"self",
")",
":",
"if",
"arcpyFound",
"==",
"False",
":",
"raise",
"Exception",
"(",
"\"ArcPy is required to use this function\"",
")",
"return",
"arcpy",
".",
"AsShape",
"(",
"self",
".",
"asDictionary",
",",
"True",
")"
] | returns the Point as an ESRI arcpy.Point object | [
"returns",
"the",
"Point",
"as",
"an",
"ESRI",
"arcpy",
".",
"Point",
"object"
] | python | train | 48 |
globocom/GloboNetworkAPI-client-python | networkapiclient/ApiNetworkIPv6.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiNetworkIPv6.py#L35-L44 | def get_by_id(self, id_networkv6):
"""Get IPv6 network
:param id_networkv4: ID for NetworkIPv6
:return: IPv6 Network
"""
uri = 'api/networkv4/%s/' % id_networkv6
return super(ApiNetworkIPv6, self).get(uri) | [
"def",
"get_by_id",
"(",
"self",
",",
"id_networkv6",
")",
":",
"uri",
"=",
"'api/networkv4/%s/'",
"%",
"id_networkv6",
"return",
"super",
"(",
"ApiNetworkIPv6",
",",
"self",
")",
".",
"get",
"(",
"uri",
")"
] | Get IPv6 network
:param id_networkv4: ID for NetworkIPv6
:return: IPv6 Network | [
"Get",
"IPv6",
"network"
] | python | train | 24.7 |
pypa/pipenv | pipenv/vendor/jinja2/environment.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/environment.py#L1108-L1115 | def get_corresponding_lineno(self, lineno):
"""Return the source line number of a line number in the
generated bytecode as they are not in sync.
"""
for template_line, code_line in reversed(self.debug_info):
if code_line <= lineno:
return template_line
... | [
"def",
"get_corresponding_lineno",
"(",
"self",
",",
"lineno",
")",
":",
"for",
"template_line",
",",
"code_line",
"in",
"reversed",
"(",
"self",
".",
"debug_info",
")",
":",
"if",
"code_line",
"<=",
"lineno",
":",
"return",
"template_line",
"return",
"1"
] | Return the source line number of a line number in the
generated bytecode as they are not in sync. | [
"Return",
"the",
"source",
"line",
"number",
"of",
"a",
"line",
"number",
"in",
"the",
"generated",
"bytecode",
"as",
"they",
"are",
"not",
"in",
"sync",
"."
] | python | train | 40.25 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py#L686-L698 | def rover_yaw_rate(VFR_HUD, SERVO_OUTPUT_RAW):
'''return yaw rate in degrees/second given steering_angle and speed'''
max_wheel_turn=35
speed = VFR_HUD.groundspeed
# assume 1100 to 1900 PWM on steering
steering_angle = max_wheel_turn * (SERVO_OUTPUT_RAW.servo1_raw - 1500) / 400.0
if abs(steering... | [
"def",
"rover_yaw_rate",
"(",
"VFR_HUD",
",",
"SERVO_OUTPUT_RAW",
")",
":",
"max_wheel_turn",
"=",
"35",
"speed",
"=",
"VFR_HUD",
".",
"groundspeed",
"# assume 1100 to 1900 PWM on steering",
"steering_angle",
"=",
"max_wheel_turn",
"*",
"(",
"SERVO_OUTPUT_RAW",
".",
"... | return yaw rate in degrees/second given steering_angle and speed | [
"return",
"yaw",
"rate",
"in",
"degrees",
"/",
"second",
"given",
"steering_angle",
"and",
"speed"
] | python | train | 36.846154 |
PythonCharmers/python-future | src/future/backports/http/cookiejar.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1778-L1788 | def load(self, filename=None, ignore_discard=False, ignore_expires=False):
"""Load cookies from a file."""
if filename is None:
if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename)
try:
... | [
"def",
"load",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"ignore_discard",
"=",
"False",
",",
"ignore_expires",
"=",
"False",
")",
":",
"if",
"filename",
"is",
"None",
":",
"if",
"self",
".",
"filename",
"is",
"not",
"None",
":",
"filename",
"=",... | Load cookies from a file. | [
"Load",
"cookies",
"from",
"a",
"file",
"."
] | python | train | 37.545455 |
numenta/nupic | src/nupic/swarming/exp_generator/experiment_generator.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L272-L296 | def _indentLines(str, indentLevels = 1, indentFirstLine=True):
""" Indent all lines in the given string
str: input string
indentLevels: number of levels of indentation to apply
indentFirstLine: if False, the 1st line will not be indented
Returns: The result string with all lines indented
"""... | [
"def",
"_indentLines",
"(",
"str",
",",
"indentLevels",
"=",
"1",
",",
"indentFirstLine",
"=",
"True",
")",
":",
"indent",
"=",
"_ONE_INDENT",
"*",
"indentLevels",
"lines",
"=",
"str",
".",
"splitlines",
"(",
"True",
")",
"result",
"=",
"''",
"if",
"len"... | Indent all lines in the given string
str: input string
indentLevels: number of levels of indentation to apply
indentFirstLine: if False, the 1st line will not be indented
Returns: The result string with all lines indented | [
"Indent",
"all",
"lines",
"in",
"the",
"given",
"string"
] | python | valid | 22.44 |
pkgw/pwkit | pwkit/synphot.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/synphot.py#L474-L482 | def register_halfmaxes(self, telescope, band, lower, upper):
"""Register precomputed half-max points."""
if (telescope, band) in self._halfmaxes:
raise AlreadyDefinedError('half-max points for %s/%s already '
'defined', telescope, band)
self._no... | [
"def",
"register_halfmaxes",
"(",
"self",
",",
"telescope",
",",
"band",
",",
"lower",
",",
"upper",
")",
":",
"if",
"(",
"telescope",
",",
"band",
")",
"in",
"self",
".",
"_halfmaxes",
":",
"raise",
"AlreadyDefinedError",
"(",
"'half-max points for %s/%s alre... | Register precomputed half-max points. | [
"Register",
"precomputed",
"half",
"-",
"max",
"points",
"."
] | python | train | 45.333333 |
bloomreach/s4cmd | s4cmd.py | https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L927-L949 | def cp_files(self, source, target, delete_source=False):
'''Copy files
This function can handle multiple files if source S3 URL has wildcard
characters. It also handles recursive mode by copying all files and
keep the directory structure.
'''
pool = ThreadPool(ThreadUtil, self.opt)
... | [
"def",
"cp_files",
"(",
"self",
",",
"source",
",",
"target",
",",
"delete_source",
"=",
"False",
")",
":",
"pool",
"=",
"ThreadPool",
"(",
"ThreadUtil",
",",
"self",
".",
"opt",
")",
"source",
"=",
"self",
".",
"source_expand",
"(",
"source",
")",
"if... | Copy files
This function can handle multiple files if source S3 URL has wildcard
characters. It also handles recursive mode by copying all files and
keep the directory structure. | [
"Copy",
"files",
"This",
"function",
"can",
"handle",
"multiple",
"files",
"if",
"source",
"S3",
"URL",
"has",
"wildcard",
"characters",
".",
"It",
"also",
"handles",
"recursive",
"mode",
"by",
"copying",
"all",
"files",
"and",
"keep",
"the",
"directory",
"s... | python | test | 39.565217 |
hammerlab/cohorts | cohorts/cohort.py | https://github.com/hammerlab/cohorts/blob/278b05e609e6c4d4a77c57d49446460be53ea33e/cohorts/cohort.py#L1171-L1193 | def plot_roc_curve(self, on, bootstrap_samples=100, ax=None, **kwargs):
"""Plot an ROC curve for benefit and a given variable
Parameters
----------
on : str or function or list or dict
See `cohort.load.as_dataframe`
bootstrap_samples : int, optional
Numbe... | [
"def",
"plot_roc_curve",
"(",
"self",
",",
"on",
",",
"bootstrap_samples",
"=",
"100",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"plot_col",
",",
"df",
"=",
"self",
".",
"as_dataframe",
"(",
"on",
",",
"return_cols",
"=",
"True",
","... | Plot an ROC curve for benefit and a given variable
Parameters
----------
on : str or function or list or dict
See `cohort.load.as_dataframe`
bootstrap_samples : int, optional
Number of boostrap samples to use to compute the AUC
ax : Axes, default None
... | [
"Plot",
"an",
"ROC",
"curve",
"for",
"benefit",
"and",
"a",
"given",
"variable"
] | python | train | 39.956522 |
Clarify/clarify_python | clarify_python/clarify.py | https://github.com/Clarify/clarify_python/blob/1a00a5e39f77af9ad7f2e08480a3ab14e7d72aeb/clarify_python/clarify.py#L829-L848 | def _get_headers(self):
"""Get all the headers we're going to need:
1. Authorization
2. Content-Type
3. User-agent
Note that the User-agent string contains the library name, the
libary version, and the python version. This will help us track
what people are usin... | [
"def",
"_get_headers",
"(",
"self",
")",
":",
"user_agent",
"=",
"__api_lib_name__",
"+",
"'/'",
"+",
"__version__",
"+",
"'/'",
"+",
"PYTHON_VERSION",
"headers",
"=",
"{",
"'User-Agent'",
":",
"user_agent",
",",
"'Content-Type'",
":",
"'application/x-www-form-url... | Get all the headers we're going to need:
1. Authorization
2. Content-Type
3. User-agent
Note that the User-agent string contains the library name, the
libary version, and the python version. This will help us track
what people are using, and where we should concentrate ... | [
"Get",
"all",
"the",
"headers",
"we",
"re",
"going",
"to",
"need",
":"
] | python | train | 34.45 |
yohell/python-tui | tui/__init__.py | https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/__init__.py#L681-L703 | def parsestr(self, argsstr, usedname, location):
"""Parse a string lexically and store the result.
ARGS:
argsstr <str>:
The string to parse.
usedname <str>:
The string used by the user to invoke the option.
location <str>:
A user friendly sring... | [
"def",
"parsestr",
"(",
"self",
",",
"argsstr",
",",
"usedname",
",",
"location",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"format",
".",
"parsestr",
"(",
"argsstr",
")",
"except",
"formats",
".",
"BadNumberOfArguments",
",",
"e",
":",
"raise",
... | Parse a string lexically and store the result.
ARGS:
argsstr <str>:
The string to parse.
usedname <str>:
The string used by the user to invoke the option.
location <str>:
A user friendly sring describing where the parser got this
data from. | [
"Parse",
"a",
"string",
"lexically",
"and",
"store",
"the",
"result",
".",
"ARGS",
":",
"argsstr",
"<str",
">",
":",
"The",
"string",
"to",
"parse",
".",
"usedname",
"<str",
">",
":",
"The",
"string",
"used",
"by",
"the",
"user",
"to",
"invoke",
"the",... | python | valid | 34.73913 |
LonamiWebs/Telethon | telethon/tl/core/gzippacked.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/core/gzippacked.py#L14-L25 | def gzip_if_smaller(content_related, data):
"""Calls bytes(request), and based on a certain threshold,
optionally gzips the resulting data. If the gzipped data is
smaller than the original byte array, this is returned instead.
Note that this only applies to content related requ... | [
"def",
"gzip_if_smaller",
"(",
"content_related",
",",
"data",
")",
":",
"if",
"content_related",
"and",
"len",
"(",
"data",
")",
">",
"512",
":",
"gzipped",
"=",
"bytes",
"(",
"GzipPacked",
"(",
"data",
")",
")",
"return",
"gzipped",
"if",
"len",
"(",
... | Calls bytes(request), and based on a certain threshold,
optionally gzips the resulting data. If the gzipped data is
smaller than the original byte array, this is returned instead.
Note that this only applies to content related requests. | [
"Calls",
"bytes",
"(",
"request",
")",
"and",
"based",
"on",
"a",
"certain",
"threshold",
"optionally",
"gzips",
"the",
"resulting",
"data",
".",
"If",
"the",
"gzipped",
"data",
"is",
"smaller",
"than",
"the",
"original",
"byte",
"array",
"this",
"is",
"re... | python | train | 43.583333 |
cackharot/suds-py3 | suds/wsdl.py | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/wsdl.py#L664-L675 | def resolveport(self, definitions):
"""
Resolve port_type reference.
@param definitions: A definitions object.
@type definitions: L{Definitions}
"""
ref = qualify(self.type, self.root, definitions.tns)
port_type = definitions.port_types.get(ref)
if port_ty... | [
"def",
"resolveport",
"(",
"self",
",",
"definitions",
")",
":",
"ref",
"=",
"qualify",
"(",
"self",
".",
"type",
",",
"self",
".",
"root",
",",
"definitions",
".",
"tns",
")",
"port_type",
"=",
"definitions",
".",
"port_types",
".",
"get",
"(",
"ref",... | Resolve port_type reference.
@param definitions: A definitions object.
@type definitions: L{Definitions} | [
"Resolve",
"port_type",
"reference",
"."
] | python | train | 36.333333 |
PBR/MQ2 | MQ2/mapchart.py | https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/mapchart.py#L40-L99 | def _extrac_qtl(peak, block, headers):
""" Given a row containing the peak of the QTL and all the rows of
the linkage group of the said QTL (splitted per trait), determine
the QTL interval and find the start and stop marker of the said
interval.
The interval is a LOD 2 interval.
The approach is ... | [
"def",
"_extrac_qtl",
"(",
"peak",
",",
"block",
",",
"headers",
")",
":",
"qtls",
"=",
"[",
"]",
"if",
"not",
"peak",
":",
"return",
"qtls",
"threshold",
"=",
"2",
"for",
"trait",
"in",
"peak",
":",
"blockcnt",
"=",
"headers",
".",
"index",
"(",
"... | Given a row containing the peak of the QTL and all the rows of
the linkage group of the said QTL (splitted per trait), determine
the QTL interval and find the start and stop marker of the said
interval.
The interval is a LOD 2 interval.
The approach is conservative in the way it takes the first and ... | [
"Given",
"a",
"row",
"containing",
"the",
"peak",
"of",
"the",
"QTL",
"and",
"all",
"the",
"rows",
"of",
"the",
"linkage",
"group",
"of",
"the",
"said",
"QTL",
"(",
"splitted",
"per",
"trait",
")",
"determine",
"the",
"QTL",
"interval",
"and",
"find",
... | python | train | 34.75 |
gem/oq-engine | openquake/hazardlib/mfd/multi_mfd.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/multi_mfd.py#L121-L130 | def get_min_max_mag(self):
"""
:returns: minumum and maximum magnitudes from the underlying MFDs
"""
m1s, m2s = [], []
for mfd in self:
m1, m2 = mfd.get_min_max_mag()
m1s.append(m1)
m2s.append(m2)
return min(m1s), max(m2s) | [
"def",
"get_min_max_mag",
"(",
"self",
")",
":",
"m1s",
",",
"m2s",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"mfd",
"in",
"self",
":",
"m1",
",",
"m2",
"=",
"mfd",
".",
"get_min_max_mag",
"(",
")",
"m1s",
".",
"append",
"(",
"m1",
")",
"m2s",
".",
... | :returns: minumum and maximum magnitudes from the underlying MFDs | [
":",
"returns",
":",
"minumum",
"and",
"maximum",
"magnitudes",
"from",
"the",
"underlying",
"MFDs"
] | python | train | 29.7 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/io.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L349-L354 | def show(self):
"""write my output to sys.stdout/err as appropriate"""
sys.stdout.write(self.stdout)
sys.stderr.write(self.stderr)
sys.stdout.flush()
sys.stderr.flush() | [
"def",
"show",
"(",
"self",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"stdout",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"self",
".",
"stderr",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
... | write my output to sys.stdout/err as appropriate | [
"write",
"my",
"output",
"to",
"sys",
".",
"stdout",
"/",
"err",
"as",
"appropriate"
] | python | test | 33.833333 |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L2359-L2386 | def upload_complete(self, path, url, quiet):
""" function to complete an upload to retrieve a path from a url
Parameters
==========
path: the path for the upload that is read in
url: the url to send the POST to
quiet: suppress verbose output (default ... | [
"def",
"upload_complete",
"(",
"self",
",",
"path",
",",
"url",
",",
"quiet",
")",
":",
"file_size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"path",
")",
"try",
":",
"with",
"tqdm",
"(",
"total",
"=",
"file_size",
",",
"unit",
"=",
"'B'",
",",... | function to complete an upload to retrieve a path from a url
Parameters
==========
path: the path for the upload that is read in
url: the url to send the POST to
quiet: suppress verbose output (default is False) | [
"function",
"to",
"complete",
"an",
"upload",
"to",
"retrieve",
"a",
"path",
"from",
"a",
"url",
"Parameters",
"==========",
"path",
":",
"the",
"path",
"for",
"the",
"upload",
"that",
"is",
"read",
"in",
"url",
":",
"the",
"url",
"to",
"send",
"the",
... | python | train | 43.607143 |
yjzhang/uncurl_python | uncurl/dimensionality_reduction.py | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/dimensionality_reduction.py#L9-L28 | def diffusion_mds(means, weights, d, diffusion_rounds=10):
"""
Dimensionality reduction using MDS, while running diffusion on W.
Args:
means (array): genes x clusters
weights (array): clusters x cells
d (int): desired dimensionality
Returns:
W_reduced (array): array of ... | [
"def",
"diffusion_mds",
"(",
"means",
",",
"weights",
",",
"d",
",",
"diffusion_rounds",
"=",
"10",
")",
":",
"for",
"i",
"in",
"range",
"(",
"diffusion_rounds",
")",
":",
"weights",
"=",
"weights",
"*",
"weights",
"weights",
"=",
"weights",
"/",
"weight... | Dimensionality reduction using MDS, while running diffusion on W.
Args:
means (array): genes x clusters
weights (array): clusters x cells
d (int): desired dimensionality
Returns:
W_reduced (array): array of shape (d, cells) | [
"Dimensionality",
"reduction",
"using",
"MDS",
"while",
"running",
"diffusion",
"on",
"W",
"."
] | python | train | 28.5 |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L14341-L14424 | def unregister(self, cleanup_mode):
"""Unregisters a machine previously registered with
:py:func:`IVirtualBox.register_machine` and optionally do additional
cleanup before the machine is unregistered.
This method does not delete any files. It only changes the machine configurat... | [
"def",
"unregister",
"(",
"self",
",",
"cleanup_mode",
")",
":",
"if",
"not",
"isinstance",
"(",
"cleanup_mode",
",",
"CleanupMode",
")",
":",
"raise",
"TypeError",
"(",
"\"cleanup_mode can only be an instance of type CleanupMode\"",
")",
"media",
"=",
"self",
".",
... | Unregisters a machine previously registered with
:py:func:`IVirtualBox.register_machine` and optionally do additional
cleanup before the machine is unregistered.
This method does not delete any files. It only changes the machine configuration and
the list of registered machines... | [
"Unregisters",
"a",
"machine",
"previously",
"registered",
"with",
":",
"py",
":",
"func",
":",
"IVirtualBox",
".",
"register_machine",
"and",
"optionally",
"do",
"additional",
"cleanup",
"before",
"the",
"machine",
"is",
"unregistered",
".",
"This",
"method",
"... | python | train | 60.654762 |
pycontribs/jira | jira/client.py | https://github.com/pycontribs/jira/blob/397db5d78441ed6a680a9b7db4c62030ade1fd8a/jira/client.py#L3738-L3745 | def removed_issues(self, board_id, sprint_id):
"""Return the completed issues for the sprint."""
r_json = self._get_json('rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s' % (board_id, sprint_id),
base=self.AGILE_BASE_URL)
issues = [Issue(self._options, self._... | [
"def",
"removed_issues",
"(",
"self",
",",
"board_id",
",",
"sprint_id",
")",
":",
"r_json",
"=",
"self",
".",
"_get_json",
"(",
"'rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s'",
"%",
"(",
"board_id",
",",
"sprint_id",
")",
",",
"base",
"=",
"self",
".",... | Return the completed issues for the sprint. | [
"Return",
"the",
"completed",
"issues",
"for",
"the",
"sprint",
"."
] | python | train | 54.75 |
weld-project/weld | python/grizzly/grizzly/groupbyweld.py | https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/grizzly/grizzly/groupbyweld.py#L236-L255 | def get_column(self, column_name, column_type, index, verbose=True):
"""Summary
Args:
column_name (TYPE): Description
column_type (TYPE): Description
index (TYPE): Description
Returns:
TYPE: Description
"""
return LazyOpResult(
... | [
"def",
"get_column",
"(",
"self",
",",
"column_name",
",",
"column_type",
",",
"index",
",",
"verbose",
"=",
"True",
")",
":",
"return",
"LazyOpResult",
"(",
"grizzly_impl",
".",
"get_column",
"(",
"self",
".",
"expr",
",",
"self",
".",
"weld_type",
",",
... | Summary
Args:
column_name (TYPE): Description
column_type (TYPE): Description
index (TYPE): Description
Returns:
TYPE: Description | [
"Summary"
] | python | train | 24 |
googlefonts/ufo2ft | Lib/ufo2ft/util.py | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/util.py#L277-L369 | def calcCodePageRanges(unicodes):
""" Given a set of Unicode codepoints (integers), calculate the
corresponding OS/2 CodePage range bits.
This is a direct translation of FontForge implementation:
https://github.com/fontforge/fontforge/blob/7b2c074/fontforge/tottf.c#L3158
"""
codepageRanges = set... | [
"def",
"calcCodePageRanges",
"(",
"unicodes",
")",
":",
"codepageRanges",
"=",
"set",
"(",
")",
"chars",
"=",
"[",
"unichr",
"(",
"u",
")",
"for",
"u",
"in",
"unicodes",
"]",
"hasAscii",
"=",
"set",
"(",
"range",
"(",
"0x20",
",",
"0x7E",
")",
")",
... | Given a set of Unicode codepoints (integers), calculate the
corresponding OS/2 CodePage range bits.
This is a direct translation of FontForge implementation:
https://github.com/fontforge/fontforge/blob/7b2c074/fontforge/tottf.c#L3158 | [
"Given",
"a",
"set",
"of",
"Unicode",
"codepoints",
"(",
"integers",
")",
"calculate",
"the",
"corresponding",
"OS",
"/",
"2",
"CodePage",
"range",
"bits",
".",
"This",
"is",
"a",
"direct",
"translation",
"of",
"FontForge",
"implementation",
":",
"https",
":... | python | train | 43.11828 |
gplepage/gvar | src/gvar/__init__.py | https://github.com/gplepage/gvar/blob/d6671697319eb6280de3793c9a1c2b616c6f2ae0/src/gvar/__init__.py#L209-L320 | def chi2(g1, g2=None, svdcut=1e-12, nocorr=False):
""" Compute chi**2 of ``g1-g2``.
``chi**2`` is a measure of whether the multi-dimensional
Gaussian distributions ``g1`` and ``g2`` (dictionaries or arrays)
agree with each other --- that is, do their means agree
within errors for corresponding elem... | [
"def",
"chi2",
"(",
"g1",
",",
"g2",
"=",
"None",
",",
"svdcut",
"=",
"1e-12",
",",
"nocorr",
"=",
"False",
")",
":",
"# customized class for answer",
"class",
"ans",
"(",
"float",
")",
":",
"def",
"__new__",
"(",
"cls",
",",
"chi2",
",",
"dof",
",",... | Compute chi**2 of ``g1-g2``.
``chi**2`` is a measure of whether the multi-dimensional
Gaussian distributions ``g1`` and ``g2`` (dictionaries or arrays)
agree with each other --- that is, do their means agree
within errors for corresponding elements. The probability is high
if ``chi2(g1,g2)/chi2.dof... | [
"Compute",
"chi",
"**",
"2",
"of",
"g1",
"-",
"g2",
"."
] | python | train | 38.160714 |
SpriteLink/NIPAP | pynipap/pynipap.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/pynipap/pynipap.py#L548-L581 | def smart_search(cls, query_string, search_options=None, extra_query = None):
""" Perform a smart VRF search.
Maps to the function
:py:func:`nipap.backend.Nipap.smart_search_vrf` in the backend.
Please see the documentation for the backend function for
informatio... | [
"def",
"smart_search",
"(",
"cls",
",",
"query_string",
",",
"search_options",
"=",
"None",
",",
"extra_query",
"=",
"None",
")",
":",
"if",
"search_options",
"is",
"None",
":",
"search_options",
"=",
"{",
"}",
"xmlrpc",
"=",
"XMLRPCConnection",
"(",
")",
... | Perform a smart VRF search.
Maps to the function
:py:func:`nipap.backend.Nipap.smart_search_vrf` in the backend.
Please see the documentation for the backend function for
information regarding input arguments and return values. | [
"Perform",
"a",
"smart",
"VRF",
"search",
"."
] | python | train | 39.029412 |
allenai/allennlp | allennlp/training/tensorboard_writer.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/tensorboard_writer.py#L133-L139 | def log_histograms(self, model: Model, histogram_parameters: Set[str]) -> None:
"""
Send histograms of parameters to tensorboard.
"""
for name, param in model.named_parameters():
if name in histogram_parameters:
self.add_train_histogram("parameter_histogram/" ... | [
"def",
"log_histograms",
"(",
"self",
",",
"model",
":",
"Model",
",",
"histogram_parameters",
":",
"Set",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"name",
",",
"param",
"in",
"model",
".",
"named_parameters",
"(",
")",
":",
"if",
"name",
"in",
... | Send histograms of parameters to tensorboard. | [
"Send",
"histograms",
"of",
"parameters",
"to",
"tensorboard",
"."
] | python | train | 46.857143 |
ubernostrum/django-flashpolicies | flashpolicies/policies.py | https://github.com/ubernostrum/django-flashpolicies/blob/fb04693504186dde859cce97bad6e83d2b380dc6/flashpolicies/policies.py#L200-L213 | def _add_header_domains_xml(self, document):
"""
Generates the XML elements for allowed header domains.
"""
for domain, attrs in self.header_domains.items():
header_element = document.createElement(
'allow-http-request-headers-from'
)
... | [
"def",
"_add_header_domains_xml",
"(",
"self",
",",
"document",
")",
":",
"for",
"domain",
",",
"attrs",
"in",
"self",
".",
"header_domains",
".",
"items",
"(",
")",
":",
"header_element",
"=",
"document",
".",
"createElement",
"(",
"'allow-http-request-headers-... | Generates the XML elements for allowed header domains. | [
"Generates",
"the",
"XML",
"elements",
"for",
"allowed",
"header",
"domains",
"."
] | python | train | 42.5 |
myint/autoflake | autoflake.py | https://github.com/myint/autoflake/blob/68fea68646922b920d55975f9f2adaeafd84df4f/autoflake.py#L564-L574 | def filter_useless_pass(source):
"""Yield code with useless "pass" lines removed."""
try:
marked_lines = frozenset(useless_pass_line_numbers(source))
except (SyntaxError, tokenize.TokenError):
marked_lines = frozenset()
sio = io.StringIO(source)
for line_number, line in enumerate(si... | [
"def",
"filter_useless_pass",
"(",
"source",
")",
":",
"try",
":",
"marked_lines",
"=",
"frozenset",
"(",
"useless_pass_line_numbers",
"(",
"source",
")",
")",
"except",
"(",
"SyntaxError",
",",
"tokenize",
".",
"TokenError",
")",
":",
"marked_lines",
"=",
"fr... | Yield code with useless "pass" lines removed. | [
"Yield",
"code",
"with",
"useless",
"pass",
"lines",
"removed",
"."
] | python | test | 36.454545 |
etcher-be/emiz | emiz/avwx/metar.py | https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/metar.py#L23-L28 | def parse(station: str, txt: str) -> (MetarData, Units): # type: ignore
"""
Returns MetarData and Units dataclasses with parsed data and their associated units
"""
core.valid_station(station)
return parse_na(txt) if core.uses_na_format(station[:2]) else parse_in(txt) | [
"def",
"parse",
"(",
"station",
":",
"str",
",",
"txt",
":",
"str",
")",
"->",
"(",
"MetarData",
",",
"Units",
")",
":",
"# type: ignore",
"core",
".",
"valid_station",
"(",
"station",
")",
"return",
"parse_na",
"(",
"txt",
")",
"if",
"core",
".",
"u... | Returns MetarData and Units dataclasses with parsed data and their associated units | [
"Returns",
"MetarData",
"and",
"Units",
"dataclasses",
"with",
"parsed",
"data",
"and",
"their",
"associated",
"units"
] | python | train | 47.166667 |
mk-fg/txboxdotnet | txboxdotnet/api_v2.py | https://github.com/mk-fg/txboxdotnet/blob/4a3e48fbe1388c5e2a17e808aaaf6b2460e61f48/txboxdotnet/api_v2.py#L213-L219 | def listdir(self, folder_id='0', offset=None, limit=None, fields=None):
'Get Box object, representing list of objects in a folder.'
if fields is not None\
and not isinstance(fields, types.StringTypes): fields = ','.join(fields)
return self(
join('folders', folder_id, 'items'),
dict(offset=offset, limit=l... | [
"def",
"listdir",
"(",
"self",
",",
"folder_id",
"=",
"'0'",
",",
"offset",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"fields",
"=",
"None",
")",
":",
"if",
"fields",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"fields",
",",
"types",
... | Get Box object, representing list of objects in a folder. | [
"Get",
"Box",
"object",
"representing",
"list",
"of",
"objects",
"in",
"a",
"folder",
"."
] | python | train | 48 |
PGower/PyCanvas | pycanvas/apis/submissions.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/submissions.py#L387-L416 | def get_single_submission_courses(self, user_id, course_id, assignment_id, include=None):
"""
Get a single submission.
Get a single submission, based on user id.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID""... | [
"def",
"get_single_submission_courses",
"(",
"self",
",",
"user_id",
",",
"course_id",
",",
"assignment_id",
",",
"include",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\... | Get a single submission.
Get a single submission, based on user id. | [
"Get",
"a",
"single",
"submission",
".",
"Get",
"a",
"single",
"submission",
"based",
"on",
"user",
"id",
"."
] | python | train | 40.7 |
proycon/clam | clam/common/data.py | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1524-L1545 | def json(self):
"""Produce a JSON representation for the web interface"""
d = { 'id': self.id, 'format': self.formatclass.__name__,'label': self.label, 'mimetype': self.formatclass.mimetype, 'schema': self.formatclass.schema }
if self.unique:
d['unique'] = True
if self.filen... | [
"def",
"json",
"(",
"self",
")",
":",
"d",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'format'",
":",
"self",
".",
"formatclass",
".",
"__name__",
",",
"'label'",
":",
"self",
".",
"label",
",",
"'mimetype'",
":",
"self",
".",
"formatclass",
"... | Produce a JSON representation for the web interface | [
"Produce",
"a",
"JSON",
"representation",
"for",
"the",
"web",
"interface"
] | python | train | 49.590909 |
licenses/lice | lice/core.py | https://github.com/licenses/lice/blob/71635c2544d5edf9e93af4141467763916a86624/lice/core.py#L93-L100 | def clean_path(p):
""" Clean a path by expanding user and environment variables and
ensuring absolute path.
"""
p = os.path.expanduser(p)
p = os.path.expandvars(p)
p = os.path.abspath(p)
return p | [
"def",
"clean_path",
"(",
"p",
")",
":",
"p",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"p",
")",
"p",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"p",
")",
"p",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"p",
")",
"return",
"p"
] | Clean a path by expanding user and environment variables and
ensuring absolute path. | [
"Clean",
"a",
"path",
"by",
"expanding",
"user",
"and",
"environment",
"variables",
"and",
"ensuring",
"absolute",
"path",
"."
] | python | train | 27.5 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L670-L705 | def move(self, x = None, y = None, width = None, height = None,
bRepaint = True):
"""
Moves and/or resizes the window.
@note: This is request is performed syncronously.
@type x: int
@param x: (Optional) New horizontal... | [
"def",
"move",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"bRepaint",
"=",
"True",
")",
":",
"if",
"None",
"in",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
")",... | Moves and/or resizes the window.
@note: This is request is performed syncronously.
@type x: int
@param x: (Optional) New horizontal coordinate.
@type y: int
@param y: (Optional) New vertical coordinate.
@type width: int
@param width: (Optional) Desired wind... | [
"Moves",
"and",
"/",
"or",
"resizes",
"the",
"window",
"."
] | python | train | 33 |
Neurosim-lab/netpyne | netpyne/support/filter.py | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/filter.py#L45-L86 | def bandpass(data, freqmin, freqmax, df, corners=4, zerophase=True):
"""
Butterworth-Bandpass Filter.
Filter data from ``freqmin`` to ``freqmax`` using ``corners``
corners.
The filter uses :func:`scipy.signal.iirfilter` (for design)
and :func:`scipy.signal.sosfilt` (for applying the filter).
... | [
"def",
"bandpass",
"(",
"data",
",",
"freqmin",
",",
"freqmax",
",",
"df",
",",
"corners",
"=",
"4",
",",
"zerophase",
"=",
"True",
")",
":",
"fe",
"=",
"0.5",
"*",
"df",
"low",
"=",
"freqmin",
"/",
"fe",
"high",
"=",
"freqmax",
"/",
"fe",
"# rai... | Butterworth-Bandpass Filter.
Filter data from ``freqmin`` to ``freqmax`` using ``corners``
corners.
The filter uses :func:`scipy.signal.iirfilter` (for design)
and :func:`scipy.signal.sosfilt` (for applying the filter).
:type data: numpy.ndarray
:param data: Data to filter.
:param freqmin:... | [
"Butterworth",
"-",
"Bandpass",
"Filter",
"."
] | python | train | 37.952381 |
LogicalDash/LiSE | LiSE/LiSE/engine.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/engine.py#L1460-L1474 | def alias(self, v, stat='dummy'):
"""Return a representation of a value suitable for use in historical queries.
It will behave much as if you assigned the value to some entity and then used its
``historical`` method to get a reference to the set of its past values, which
happens to cont... | [
"def",
"alias",
"(",
"self",
",",
"v",
",",
"stat",
"=",
"'dummy'",
")",
":",
"from",
".",
"util",
"import",
"EntityStatAccessor",
"r",
"=",
"DummyEntity",
"(",
"self",
")",
"r",
"[",
"stat",
"]",
"=",
"v",
"return",
"EntityStatAccessor",
"(",
"r",
"... | Return a representation of a value suitable for use in historical queries.
It will behave much as if you assigned the value to some entity and then used its
``historical`` method to get a reference to the set of its past values, which
happens to contain only the value you've provided here, ``v`... | [
"Return",
"a",
"representation",
"of",
"a",
"value",
"suitable",
"for",
"use",
"in",
"historical",
"queries",
"."
] | python | train | 42 |
ewels/MultiQC | multiqc/modules/flash/flash.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/flash/flash.py#L217-L231 | def freqpoly_plot(data):
"""make freqpoly plot of merged read lengths"""
rel_data = OrderedDict()
for key, val in data.items():
tot = sum(val.values(), 0)
rel_data[key] = {k: v / tot for k, v in val.items()}
fplotconfig = {
'data_labels': [
... | [
"def",
"freqpoly_plot",
"(",
"data",
")",
":",
"rel_data",
"=",
"OrderedDict",
"(",
")",
"for",
"key",
",",
"val",
"in",
"data",
".",
"items",
"(",
")",
":",
"tot",
"=",
"sum",
"(",
"val",
".",
"values",
"(",
")",
",",
"0",
")",
"rel_data",
"[",
... | make freqpoly plot of merged read lengths | [
"make",
"freqpoly",
"plot",
"of",
"merged",
"read",
"lengths"
] | python | train | 49.933333 |
quodlibet/mutagen | mutagen/id3/_tags.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_tags.py#L491-L499 | def _restore(self, value):
"""Restores the state copied with _copy()"""
items, subs = value
self.clear()
for key, value in items:
self[key] = value
if key in subs:
value.sub_frames._restore(subs[key]) | [
"def",
"_restore",
"(",
"self",
",",
"value",
")",
":",
"items",
",",
"subs",
"=",
"value",
"self",
".",
"clear",
"(",
")",
"for",
"key",
",",
"value",
"in",
"items",
":",
"self",
"[",
"key",
"]",
"=",
"value",
"if",
"key",
"in",
"subs",
":",
"... | Restores the state copied with _copy() | [
"Restores",
"the",
"state",
"copied",
"with",
"_copy",
"()"
] | python | train | 29.444444 |
davenquinn/Attitude | attitude/stereonet.py | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L7-L11 | def quaternion(vector, angle):
"""
Unit quaternion for a vector and an angle
"""
return N.cos(angle/2)+vector*N.sin(angle/2) | [
"def",
"quaternion",
"(",
"vector",
",",
"angle",
")",
":",
"return",
"N",
".",
"cos",
"(",
"angle",
"/",
"2",
")",
"+",
"vector",
"*",
"N",
".",
"sin",
"(",
"angle",
"/",
"2",
")"
] | Unit quaternion for a vector and an angle | [
"Unit",
"quaternion",
"for",
"a",
"vector",
"and",
"an",
"angle"
] | python | train | 27.2 |
angr/angr | angr/calling_conventions.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/calling_conventions.py#L522-L629 | def setup_callsite(self, state, ret_addr, args, stack_base=None, alloc_base=None, grow_like_stack=True):
"""
This function performs the actions of the caller getting ready to jump into a function.
:param state: The SimState to operate on
:param ret_addr: The address to ... | [
"def",
"setup_callsite",
"(",
"self",
",",
"state",
",",
"ret_addr",
",",
"args",
",",
"stack_base",
"=",
"None",
",",
"alloc_base",
"=",
"None",
",",
"grow_like_stack",
"=",
"True",
")",
":",
"# STEP 0: clerical work",
"if",
"isinstance",
"(",
"self",
",",
... | This function performs the actions of the caller getting ready to jump into a function.
:param state: The SimState to operate on
:param ret_addr: The address to return to when the called function finishes
:param args: The list of arguments that that the called functi... | [
"This",
"function",
"performs",
"the",
"actions",
"of",
"the",
"caller",
"getting",
"ready",
"to",
"jump",
"into",
"a",
"function",
"."
] | python | train | 49.444444 |
hydpy-dev/hydpy | hydpy/auxs/statstools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/statstools.py#L140-L170 | def nse(sim=None, obs=None, node=None, skip_nan=False):
"""Calculate the efficiency criteria after Nash & Sutcliffe.
If the simulated values predict the observed values as well
as the average observed value (regarding the the mean square
error), the NSE value is zero:
>>> from hydpy import nse
... | [
"def",
"nse",
"(",
"sim",
"=",
"None",
",",
"obs",
"=",
"None",
",",
"node",
"=",
"None",
",",
"skip_nan",
"=",
"False",
")",
":",
"sim",
",",
"obs",
"=",
"prepare_arrays",
"(",
"sim",
",",
"obs",
",",
"node",
",",
"skip_nan",
")",
"return",
"1."... | Calculate the efficiency criteria after Nash & Sutcliffe.
If the simulated values predict the observed values as well
as the average observed value (regarding the the mean square
error), the NSE value is zero:
>>> from hydpy import nse
>>> nse(sim=[2.0, 2.0, 2.0], obs=[1.0, 2.0, 3.0])
0.0
... | [
"Calculate",
"the",
"efficiency",
"criteria",
"after",
"Nash",
"&",
"Sutcliffe",
"."
] | python | train | 31.967742 |
globocom/GloboNetworkAPI-client-python | networkapiclient/Ip.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ip.py#L616-L663 | def save_ipv6(self, ip6, id_equip, descricao, id_net):
"""
Save an IP6 and associate with equipment
:param ip6: An IP6 available to save in format xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx.
:param id_equip: Equipment identifier. Integer value and greater than zero.
:param descrica... | [
"def",
"save_ipv6",
"(",
"self",
",",
"ip6",
",",
"id_equip",
",",
"descricao",
",",
"id_net",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_net",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Network identifier is invalid or was not informed.'",
")",
... | Save an IP6 and associate with equipment
:param ip6: An IP6 available to save in format xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx.
:param id_equip: Equipment identifier. Integer value and greater than zero.
:param descricao: IPv6 description.
:param id_net: Network identifier. Integer val... | [
"Save",
"an",
"IP6",
"and",
"associate",
"with",
"equipment"
] | python | train | 33.5625 |
LudovicRousseau/PyKCS11 | PyKCS11/__init__.py | https://github.com/LudovicRousseau/PyKCS11/blob/76ccd8741af2ea193aaf1ca29dfedfa412c134fe/PyKCS11/__init__.py#L975-L985 | def digestSession(self, mecha=MechanismSHA1):
"""
C_DigestInit/C_DigestUpdate/C_DigestKey/C_DigestFinal
:param mecha: the digesting mechanism to be used
(use `MechanismSHA1` for `CKM_SHA_1`)
:type mecha: :class:`Mechanism`
:return: A :class:`DigestSession` object
... | [
"def",
"digestSession",
"(",
"self",
",",
"mecha",
"=",
"MechanismSHA1",
")",
":",
"return",
"DigestSession",
"(",
"self",
".",
"lib",
",",
"self",
".",
"session",
",",
"mecha",
")"
] | C_DigestInit/C_DigestUpdate/C_DigestKey/C_DigestFinal
:param mecha: the digesting mechanism to be used
(use `MechanismSHA1` for `CKM_SHA_1`)
:type mecha: :class:`Mechanism`
:return: A :class:`DigestSession` object
:rtype: DigestSession | [
"C_DigestInit",
"/",
"C_DigestUpdate",
"/",
"C_DigestKey",
"/",
"C_DigestFinal"
] | python | test | 36.909091 |
fboender/ansible-cmdb | lib/mako/runtime.py | https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/mako/runtime.py#L103-L109 | def _push_writer(self):
"""push a capturing buffer onto this Context and return
the new writer function."""
buf = util.FastEncodingBuffer()
self._buffer_stack.append(buf)
return buf.write | [
"def",
"_push_writer",
"(",
"self",
")",
":",
"buf",
"=",
"util",
".",
"FastEncodingBuffer",
"(",
")",
"self",
".",
"_buffer_stack",
".",
"append",
"(",
"buf",
")",
"return",
"buf",
".",
"write"
] | push a capturing buffer onto this Context and return
the new writer function. | [
"push",
"a",
"capturing",
"buffer",
"onto",
"this",
"Context",
"and",
"return",
"the",
"new",
"writer",
"function",
"."
] | python | train | 31.714286 |
Fortran-FOSS-Programmers/ford | ford/sourceform.py | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/sourceform.py#L998-L1034 | def prune(self):
"""
Remove anything which shouldn't be displayed.
"""
def to_include(obj):
inc = obj.permission in self.display
if self.settings['hide_undoc'].lower() == 'true' and not obj.doc:
inc = False
return inc
if self.o... | [
"def",
"prune",
"(",
"self",
")",
":",
"def",
"to_include",
"(",
"obj",
")",
":",
"inc",
"=",
"obj",
".",
"permission",
"in",
"self",
".",
"display",
"if",
"self",
".",
"settings",
"[",
"'hide_undoc'",
"]",
".",
"lower",
"(",
")",
"==",
"'true'",
"... | Remove anything which shouldn't be displayed. | [
"Remove",
"anything",
"which",
"shouldn",
"t",
"be",
"displayed",
"."
] | python | train | 50 |
ecmwf/cfgrib | cfgrib/dataset.py | https://github.com/ecmwf/cfgrib/blob/d6d533f49c1eebf78f2f16ed0671c666de08c666/cfgrib/dataset.py#L502-L508 | def open_file(path, grib_errors='warn', **kwargs):
"""Open a GRIB file as a ``cfgrib.Dataset``."""
if 'mode' in kwargs:
warnings.warn("the `mode` keyword argument is ignored and deprecated", FutureWarning)
kwargs.pop('mode')
stream = messages.FileStream(path, message_class=cfmessage.CfMessag... | [
"def",
"open_file",
"(",
"path",
",",
"grib_errors",
"=",
"'warn'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mode'",
"in",
"kwargs",
":",
"warnings",
".",
"warn",
"(",
"\"the `mode` keyword argument is ignored and deprecated\"",
",",
"FutureWarning",
")",
"kwa... | Open a GRIB file as a ``cfgrib.Dataset``. | [
"Open",
"a",
"GRIB",
"file",
"as",
"a",
"cfgrib",
".",
"Dataset",
"."
] | python | train | 57.142857 |
NatLibFi/Skosify | skosify/skosify.py | https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/skosify.py#L184-L206 | def initialize_concept_scheme(rdf, cs, label, language, set_modified):
"""Initialize a concept scheme: Optionally add a label if the concept
scheme doesn't have a label, and optionally add a dct:modified
timestamp."""
# check whether the concept scheme is unlabeled, and label it if possible
labels ... | [
"def",
"initialize_concept_scheme",
"(",
"rdf",
",",
"cs",
",",
"label",
",",
"language",
",",
"set_modified",
")",
":",
"# check whether the concept scheme is unlabeled, and label it if possible",
"labels",
"=",
"list",
"(",
"rdf",
".",
"objects",
"(",
"cs",
",",
"... | Initialize a concept scheme: Optionally add a label if the concept
scheme doesn't have a label, and optionally add a dct:modified
timestamp. | [
"Initialize",
"a",
"concept",
"scheme",
":",
"Optionally",
"add",
"a",
"label",
"if",
"the",
"concept",
"scheme",
"doesn",
"t",
"have",
"a",
"label",
"and",
"optionally",
"add",
"a",
"dct",
":",
"modified",
"timestamp",
"."
] | python | train | 44.478261 |
DataDog/integrations-core | vsphere/datadog_checks/vsphere/vsphere.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/vsphere/datadog_checks/vsphere/vsphere.py#L573-L608 | def _cache_morlist_raw(self, instance):
"""
Fill the Mor objects queue that will be asynchronously processed later.
Resolve the vCenter `rootFolder` and initiate hosts and virtual machines
discovery.
"""
i_key = self._instance_key(instance)
self.log.debug("Caching... | [
"def",
"_cache_morlist_raw",
"(",
"self",
",",
"instance",
")",
":",
"i_key",
"=",
"self",
".",
"_instance_key",
"(",
"instance",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"Caching the morlist for vcenter instance {}\"",
".",
"format",
"(",
"i_key",
")",
"... | Fill the Mor objects queue that will be asynchronously processed later.
Resolve the vCenter `rootFolder` and initiate hosts and virtual machines
discovery. | [
"Fill",
"the",
"Mor",
"objects",
"queue",
"that",
"will",
"be",
"asynchronously",
"processed",
"later",
".",
"Resolve",
"the",
"vCenter",
"rootFolder",
"and",
"initiate",
"hosts",
"and",
"virtual",
"machines",
"discovery",
"."
] | python | train | 49.722222 |
20c/grainy | grainy/core.py | https://github.com/20c/grainy/blob/cd956fd4144044993abc967974a127aab07a8ef6/grainy/core.py#L12-L40 | def int_flags(flags, mapper=const.PERM_STRING_MAP):
"""
Converts string permission flags into integer permission flags as
specified in const.PERM_STRING_MAP
Arguments:
- flags <str>: one or more flags
For example: "crud" or "ru" or "r"
- mapper <list=const.PERM_STRING_MAP>: a... | [
"def",
"int_flags",
"(",
"flags",
",",
"mapper",
"=",
"const",
".",
"PERM_STRING_MAP",
")",
":",
"r",
"=",
"0",
"if",
"not",
"flags",
":",
"return",
"r",
"if",
"isinstance",
"(",
"flags",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"flags",
... | Converts string permission flags into integer permission flags as
specified in const.PERM_STRING_MAP
Arguments:
- flags <str>: one or more flags
For example: "crud" or "ru" or "r"
- mapper <list=const.PERM_STRING_MAP>: a list containing tuples mapping
int permission flag ... | [
"Converts",
"string",
"permission",
"flags",
"into",
"integer",
"permission",
"flags",
"as",
"specified",
"in",
"const",
".",
"PERM_STRING_MAP",
"Arguments",
":",
"-",
"flags",
"<str",
">",
":",
"one",
"or",
"more",
"flags",
"For",
"example",
":",
"crud",
"o... | python | train | 28.896552 |
MartinThoma/mpu | mpu/math.py | https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/math.py#L23-L61 | def generate_primes():
"""
Generate an infinite sequence of prime numbers.
The algorithm was originally written by David Eppstein, UC Irvine. See:
http://code.activestate.com/recipes/117119/
Examples
--------
>>> g = generate_primes()
>>> next(g)
2
>>> next(g)
3
>>> nex... | [
"def",
"generate_primes",
"(",
")",
":",
"divisors",
"=",
"{",
"}",
"# map number to at least one divisor",
"candidate",
"=",
"2",
"# next potential prime",
"while",
"True",
":",
"if",
"candidate",
"in",
"divisors",
":",
"# candidate is composite. divisors[candidate] is t... | Generate an infinite sequence of prime numbers.
The algorithm was originally written by David Eppstein, UC Irvine. See:
http://code.activestate.com/recipes/117119/
Examples
--------
>>> g = generate_primes()
>>> next(g)
2
>>> next(g)
3
>>> next(g)
5 | [
"Generate",
"an",
"infinite",
"sequence",
"of",
"prime",
"numbers",
"."
] | python | train | 29.25641 |
apple/turicreate | src/unity/python/turicreate/data_structures/sframe.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sframe.py#L3295-L3347 | def remove_column(self, column_name, inplace=False):
"""
Returns an SFrame with a column removed.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
SFrame, ret... | [
"def",
"remove_column",
"(",
"self",
",",
"column_name",
",",
"inplace",
"=",
"False",
")",
":",
"column_name",
"=",
"str",
"(",
"column_name",
")",
"if",
"column_name",
"not",
"in",
"self",
".",
"column_names",
"(",
")",
":",
"raise",
"KeyError",
"(",
"... | Returns an SFrame with a column removed.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
SFrame, returning self.
Parameters
----------
column_name :... | [
"Returns",
"an",
"SFrame",
"with",
"a",
"column",
"removed",
"."
] | python | train | 26.377358 |
satellogic/telluric | telluric/vectors.py | https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/vectors.py#L98-L126 | def generate_tile_coordinates(roi, num_tiles):
# type: (GeoVector, Tuple[int, int]) -> Iterator[GeoVector]
"""Yields N x M rectangular tiles for a region of interest.
Parameters
----------
roi : GeoVector
Region of interest
num_tiles : tuple
Tuple (horizontal_tiles, vertical_til... | [
"def",
"generate_tile_coordinates",
"(",
"roi",
",",
"num_tiles",
")",
":",
"# type: (GeoVector, Tuple[int, int]) -> Iterator[GeoVector]",
"bounds",
"=",
"roi",
".",
"get_shape",
"(",
"roi",
".",
"crs",
")",
".",
"bounds",
"x_range",
"=",
"np",
".",
"linspace",
"(... | Yields N x M rectangular tiles for a region of interest.
Parameters
----------
roi : GeoVector
Region of interest
num_tiles : tuple
Tuple (horizontal_tiles, vertical_tiles)
Yields
------
~telluric.vectors.GeoVector | [
"Yields",
"N",
"x",
"M",
"rectangular",
"tiles",
"for",
"a",
"region",
"of",
"interest",
"."
] | python | train | 28.724138 |
SeabornGames/Logger | seaborn_logger/logger.py | https://github.com/SeabornGames/Logger/blob/fb8b1700557aaea8d3216bd4c4df33c302bece7f/seaborn_logger/logger.py#L45-L72 | def findCaller(self, stack_info=False):
"""
Find the stack frame of the caller so that we can note the source
file name, line number and function name.
"""
f = logging.currentframe()
# On some versions of IronPython, currentframe() returns None if
# IronPython isn... | [
"def",
"findCaller",
"(",
"self",
",",
"stack_info",
"=",
"False",
")",
":",
"f",
"=",
"logging",
".",
"currentframe",
"(",
")",
"# On some versions of IronPython, currentframe() returns None if",
"# IronPython isn't run with -X:Frames.",
"if",
"f",
"is",
"not",
"None",... | Find the stack frame of the caller so that we can note the source
file name, line number and function name. | [
"Find",
"the",
"stack",
"frame",
"of",
"the",
"caller",
"so",
"that",
"we",
"can",
"note",
"the",
"source",
"file",
"name",
"line",
"number",
"and",
"function",
"name",
"."
] | python | test | 38.607143 |
knipknap/exscript | Exscript/account.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L123-L138 | def release(self, signal=True):
"""
Unlocks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the released_event signal.
"""
if not self.needs_lock:
r... | [
"def",
"release",
"(",
"self",
",",
"signal",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"needs_lock",
":",
"return",
"with",
"self",
".",
"synclock",
":",
"self",
".",
"lock",
".",
"release",
"(",
")",
"if",
"signal",
":",
"self",
".",
"rele... | Unlocks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the released_event signal. | [
"Unlocks",
"the",
"account",
".",
"Method",
"has",
"no",
"effect",
"if",
"the",
"constructor",
"argument",
"needs_lock",
"wsa",
"set",
"to",
"False",
"."
] | python | train | 29.625 |
GoogleCloudPlatform/appengine-gcs-client | python/src/cloudstorage/common.py | https://github.com/GoogleCloudPlatform/appengine-gcs-client/blob/d11078331ecd915d753c886e96a80133599f3f98/python/src/cloudstorage/common.py#L347-L368 | def dt_str_to_posix(dt_str):
"""format str to posix.
datetime str is of format %Y-%m-%dT%H:%M:%S.%fZ,
e.g. 2013-04-12T00:22:27.978Z. According to ISO 8601, T is a separator
between date and time when they are on the same line.
Z indicates UTC (zero meridian).
A pointer: http://www.cl.cam.ac.uk/~mgk25/iso-... | [
"def",
"dt_str_to_posix",
"(",
"dt_str",
")",
":",
"parsable",
",",
"_",
"=",
"dt_str",
".",
"split",
"(",
"'.'",
")",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"parsable",
",",
"_DT_FORMAT",
")",
"return",
"calendar",
".",
"timegm",
... | format str to posix.
datetime str is of format %Y-%m-%dT%H:%M:%S.%fZ,
e.g. 2013-04-12T00:22:27.978Z. According to ISO 8601, T is a separator
between date and time when they are on the same line.
Z indicates UTC (zero meridian).
A pointer: http://www.cl.cam.ac.uk/~mgk25/iso-time.html
This is used to parse... | [
"format",
"str",
"to",
"posix",
"."
] | python | train | 30.454545 |
Neurita/boyle | scripts/compare_id_sets.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/scripts/compare_id_sets.py#L280-L308 | def _print_foreign_repetition_table(self, idset1, idset2):
"""
:param idset1:
:param idset2:
"""
assert(isinstance(idset1, idset_with_reference))
assert(isinstance(idset2, idset))
reps = idset2.get_repetitions()
if len(reps) < 1:
return
... | [
"def",
"_print_foreign_repetition_table",
"(",
"self",
",",
"idset1",
",",
"idset2",
")",
":",
"assert",
"(",
"isinstance",
"(",
"idset1",
",",
"idset_with_reference",
")",
")",
"assert",
"(",
"isinstance",
"(",
"idset2",
",",
"idset",
")",
")",
"reps",
"=",... | :param idset1:
:param idset2: | [
":",
"param",
"idset1",
":",
":",
"param",
"idset2",
":"
] | python | valid | 31.517241 |
cloudant/python-cloudant | src/cloudant/database.py | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L1048-L1096 | def get_query_indexes(self, raw_result=False):
"""
Retrieves query indexes from the remote database.
:param bool raw_result: If set to True then the raw JSON content for
the request is returned. Default is to return a list containing
:class:`~cloudant.index.Index`,
... | [
"def",
"get_query_indexes",
"(",
"self",
",",
"raw_result",
"=",
"False",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"database_url",
",",
"'_index'",
")",
")",
"resp",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"url",
")",
... | Retrieves query indexes from the remote database.
:param bool raw_result: If set to True then the raw JSON content for
the request is returned. Default is to return a list containing
:class:`~cloudant.index.Index`,
:class:`~cloudant.index.TextIndex`, and
:class:... | [
"Retrieves",
"query",
"indexes",
"from",
"the",
"remote",
"database",
"."
] | python | train | 37.122449 |
RediSearch/redisearch-py | redisearch/client.py | https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/client.py#L259-L267 | def delete_document(self, doc_id, conn=None):
"""
Delete a document from index
Returns 1 if the document was deleted, 0 if not
"""
if conn is None:
conn = self.redis
return conn.execute_command(self.DEL_CMD, self.index_name, doc_id) | [
"def",
"delete_document",
"(",
"self",
",",
"doc_id",
",",
"conn",
"=",
"None",
")",
":",
"if",
"conn",
"is",
"None",
":",
"conn",
"=",
"self",
".",
"redis",
"return",
"conn",
".",
"execute_command",
"(",
"self",
".",
"DEL_CMD",
",",
"self",
".",
"in... | Delete a document from index
Returns 1 if the document was deleted, 0 if not | [
"Delete",
"a",
"document",
"from",
"index",
"Returns",
"1",
"if",
"the",
"document",
"was",
"deleted",
"0",
"if",
"not"
] | python | valid | 31.666667 |
jeroyang/txttk | txttk/retools.py | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/retools.py#L75-L104 | def is_solid(regex):
"""
Check the given regular expression is solid.
>>> is_solid(r'a')
True
>>> is_solid(r'[ab]')
True
>>> is_solid(r'(a|b|c)')
True
>>> is_solid(r'(a|b|c)?')
True
>>> is_solid(r'(a|b)(c)')
False
>>> is_solid(r'(a|b)(c)?')
False
"""
sha... | [
"def",
"is_solid",
"(",
"regex",
")",
":",
"shape",
"=",
"re",
".",
"sub",
"(",
"r'(\\\\.|[^\\[\\]\\(\\)\\|\\?\\+\\*])'",
",",
"'#'",
",",
"regex",
")",
"skeleton",
"=",
"shape",
".",
"replace",
"(",
"'#'",
",",
"''",
")",
"if",
"len",
"(",
"shape",
")... | Check the given regular expression is solid.
>>> is_solid(r'a')
True
>>> is_solid(r'[ab]')
True
>>> is_solid(r'(a|b|c)')
True
>>> is_solid(r'(a|b|c)?')
True
>>> is_solid(r'(a|b)(c)')
False
>>> is_solid(r'(a|b)(c)?')
False | [
"Check",
"the",
"given",
"regular",
"expression",
"is",
"solid",
"."
] | python | train | 22.033333 |
fitnr/convertdate | convertdate/indian_civil.py | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/indian_civil.py#L77-L117 | def from_jd(jd):
'''Calculate Indian Civil date from Julian day
Offset in years from Saka era to Gregorian epoch'''
start = 80
# Day offset between Saka and Gregorian
jd = trunc(jd) + 0.5
greg = gregorian.from_jd(jd) # Gregorian date for Julian day
leap = isleap(greg[0]) # Is this a leap... | [
"def",
"from_jd",
"(",
"jd",
")",
":",
"start",
"=",
"80",
"# Day offset between Saka and Gregorian",
"jd",
"=",
"trunc",
"(",
"jd",
")",
"+",
"0.5",
"greg",
"=",
"gregorian",
".",
"from_jd",
"(",
"jd",
")",
"# Gregorian date for Julian day",
"leap",
"=",
"i... | Calculate Indian Civil date from Julian day
Offset in years from Saka era to Gregorian epoch | [
"Calculate",
"Indian",
"Civil",
"date",
"from",
"Julian",
"day",
"Offset",
"in",
"years",
"from",
"Saka",
"era",
"to",
"Gregorian",
"epoch"
] | python | train | 27.243902 |
saltstack/salt | salt/modules/rh_service.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_service.py#L461-L475 | def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
if _service_is_upstart(name):
cmd = 'reload {0}'.format(name)
else:
cmd = '/sbin/service {0} reload'.format(name)
return not __salt__['c... | [
"def",
"reload_",
"(",
"name",
")",
":",
"if",
"_service_is_upstart",
"(",
"name",
")",
":",
"cmd",
"=",
"'reload {0}'",
".",
"format",
"(",
"name",
")",
"else",
":",
"cmd",
"=",
"'/sbin/service {0} reload'",
".",
"format",
"(",
"name",
")",
"return",
"n... | Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name> | [
"Reload",
"the",
"named",
"service"
] | python | train | 22.866667 |
mdiener/grace | grace/py27/pyjsdoc.py | https://github.com/mdiener/grace/blob/2dab13a2cf636da5da989904c5885166fc94d36d/grace/py27/pyjsdoc.py#L1475-L1481 | def htmlize_paragraphs(text):
"""
Convert paragraphs delimited by blank lines into HTML text enclosed
in <p> tags.
"""
paragraphs = re.split('(\r?\n)\s*(\r?\n)', text)
return '\n'.join('<p>%s</p>' % paragraph for paragraph in paragraphs) | [
"def",
"htmlize_paragraphs",
"(",
"text",
")",
":",
"paragraphs",
"=",
"re",
".",
"split",
"(",
"'(\\r?\\n)\\s*(\\r?\\n)'",
",",
"text",
")",
"return",
"'\\n'",
".",
"join",
"(",
"'<p>%s</p>'",
"%",
"paragraph",
"for",
"paragraph",
"in",
"paragraphs",
")"
] | Convert paragraphs delimited by blank lines into HTML text enclosed
in <p> tags. | [
"Convert",
"paragraphs",
"delimited",
"by",
"blank",
"lines",
"into",
"HTML",
"text",
"enclosed",
"in",
"<p",
">",
"tags",
"."
] | python | train | 36.428571 |
estnltk/estnltk | estnltk/taggers/event_tagger.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/taggers/event_tagger.py#L129-L156 | def tag(self, text):
"""Retrieves list of keywords in text.
Parameters
----------
text: Text
The text to search for events.
Returns
-------
list of vents sorted by start, end
"""
if self.search_method == 'ahocorasick':
eve... | [
"def",
"tag",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"search_method",
"==",
"'ahocorasick'",
":",
"events",
"=",
"self",
".",
"_find_keywords_ahocorasick",
"(",
"text",
".",
"text",
")",
"elif",
"self",
".",
"search_method",
"==",
"'naive'"... | Retrieves list of keywords in text.
Parameters
----------
text: Text
The text to search for events.
Returns
-------
list of vents sorted by start, end | [
"Retrieves",
"list",
"of",
"keywords",
"in",
"text",
"."
] | python | train | 27.857143 |
raiden-network/raiden | raiden/network/transport/matrix/utils.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L196-L230 | def _presence_listener(self, event: Dict[str, Any]):
"""
Update cached user presence state from Matrix presence events.
Due to the possibility of nodes using accounts on multiple homeservers a composite
address state is synthesised from the cached individual user presence states.
... | [
"def",
"_presence_listener",
"(",
"self",
",",
"event",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"if",
"self",
".",
"_stop_event",
".",
"ready",
"(",
")",
":",
"return",
"user_id",
"=",
"event",
"[",
"'sender'",
"]",
"if",
"event",
"[",
... | Update cached user presence state from Matrix presence events.
Due to the possibility of nodes using accounts on multiple homeservers a composite
address state is synthesised from the cached individual user presence states. | [
"Update",
"cached",
"user",
"presence",
"state",
"from",
"Matrix",
"presence",
"events",
"."
] | python | train | 37.857143 |
oceanprotocol/squid-py | squid_py/agreements/register_service_agreement.py | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/register_service_agreement.py#L130-L171 | def process_agreement_events_publisher(publisher_account, agreement_id, did, service_agreement,
price, consumer_address, condition_ids):
"""
Process the agreement events during the register of the service agreement for the publisher side
:param publisher_account: Acco... | [
"def",
"process_agreement_events_publisher",
"(",
"publisher_account",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"price",
",",
"consumer_address",
",",
"condition_ids",
")",
":",
"conditions_dict",
"=",
"service_agreement",
".",
"condition_by_name",
... | Process the agreement events during the register of the service agreement for the publisher side
:param publisher_account: Account instance of the publisher
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param price: Asset... | [
"Process",
"the",
"agreement",
"events",
"during",
"the",
"register",
"of",
"the",
"service",
"agreement",
"for",
"the",
"publisher",
"side"
] | python | train | 40.02381 |
diging/tethne | tethne/classes/feature.py | https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/classes/feature.py#L301-L322 | def top(self, topn=10):
"""
Get a list of the top ``topn`` features in this :class:`.Feature`\.
Examples
--------
.. code-block:: python
>>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])
>>> myFeature.top(1)
[('trapezoid', 5)]
... | [
"def",
"top",
"(",
"self",
",",
"topn",
"=",
"10",
")",
":",
"return",
"[",
"self",
"[",
"i",
"]",
"for",
"i",
"in",
"argsort",
"(",
"list",
"(",
"zip",
"(",
"*",
"self",
")",
")",
"[",
"1",
"]",
")",
"[",
":",
":",
"-",
"1",
"]",
"[",
... | Get a list of the top ``topn`` features in this :class:`.Feature`\.
Examples
--------
.. code-block:: python
>>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])
>>> myFeature.top(1)
[('trapezoid', 5)]
Parameters
----------
topn... | [
"Get",
"a",
"list",
"of",
"the",
"top",
"topn",
"features",
"in",
"this",
":",
"class",
":",
".",
"Feature",
"\\",
"."
] | python | train | 21.954545 |
gawel/panoramisk | panoramisk/message.py | https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/message.py#L61-L77 | def success(self):
"""return True if a response status is Success or Follows:
.. code-block:: python
>>> resp = Message({'Response': 'Success'})
>>> print(resp.success)
True
>>> resp['Response'] = 'Failed'
>>> resp.success
False
... | [
"def",
"success",
"(",
"self",
")",
":",
"if",
"'event'",
"in",
"self",
":",
"return",
"True",
"if",
"self",
".",
"response",
"in",
"self",
".",
"success_responses",
":",
"return",
"True",
"return",
"False"
] | return True if a response status is Success or Follows:
.. code-block:: python
>>> resp = Message({'Response': 'Success'})
>>> print(resp.success)
True
>>> resp['Response'] = 'Failed'
>>> resp.success
False | [
"return",
"True",
"if",
"a",
"response",
"status",
"is",
"Success",
"or",
"Follows",
":"
] | python | test | 27.235294 |
woolfson-group/isambard | isambard/add_ons/knobs_into_holes.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/add_ons/knobs_into_holes.py#L502-L589 | def make_pymol(pdb_file, cutoff=7.0, min_kihs=2, outfile=None):
""" Pymol script for viewing classic coiled-coil Socket output.
Notes
-----
For examples of these views, browse the CC+ database here: http://coiledcoils.chm.bris.ac.uk/ccplus/search/.
Parameters
----------
pdb_file: str
... | [
"def",
"make_pymol",
"(",
"pdb_file",
",",
"cutoff",
"=",
"7.0",
",",
"min_kihs",
"=",
"2",
",",
"outfile",
"=",
"None",
")",
":",
"a",
"=",
"convert_pdb_to_ampal",
"(",
"pdb",
"=",
"pdb_file",
",",
"path",
"=",
"True",
")",
"kg",
"=",
"KnobGroup",
"... | Pymol script for viewing classic coiled-coil Socket output.
Notes
-----
For examples of these views, browse the CC+ database here: http://coiledcoils.chm.bris.ac.uk/ccplus/search/.
Parameters
----------
pdb_file: str
Path to a pdb_file.
cutoff: float
Socket cutoff in Angstr... | [
"Pymol",
"script",
"for",
"viewing",
"classic",
"coiled",
"-",
"coil",
"Socket",
"output",
"."
] | python | train | 51.545455 |
saltstack/salt | salt/modules/win_iis.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1220-L1294 | def get_container_setting(name, container, settings):
'''
Get the value of the setting for the IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, S... | [
"def",
"get_container_setting",
"(",
"name",
",",
"container",
",",
"settings",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"ps_cmd",
"=",
"list",
"(",
")",
"ps_cmd_validate",
"=",
"list",
"(",
")",
"container_path",
"=",
"r\"IIS:\\{0}\\{1}\"",
".",
"format",
... | Get the value of the setting for the IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, SslBindings
settings (dict): A dictionary of the setting na... | [
"Get",
"the",
"value",
"of",
"the",
"setting",
"for",
"the",
"IIS",
"container",
"."
] | python | train | 35.96 |
mapbox/mapbox-cli-py | mapboxcli/scripts/static.py | https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/static.py#L18-L47 | def staticmap(ctx, mapid, output, features, lat, lon, zoom, size):
"""
Generate static map images from existing Mapbox map ids.
Optionally overlay with geojson features.
$ mapbox staticmap --features features.geojson mapbox.satellite out.png
$ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 m... | [
"def",
"staticmap",
"(",
"ctx",
",",
"mapid",
",",
"output",
",",
"features",
",",
"lat",
",",
"lon",
",",
"zoom",
",",
"size",
")",
":",
"access_token",
"=",
"(",
"ctx",
".",
"obj",
"and",
"ctx",
".",
"obj",
".",
"get",
"(",
"'access_token'",
")",... | Generate static map images from existing Mapbox map ids.
Optionally overlay with geojson features.
$ mapbox staticmap --features features.geojson mapbox.satellite out.png
$ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 mapbox.satellite out2.png
An access token is required, see `mapbox --help`. | [
"Generate",
"static",
"map",
"images",
"from",
"existing",
"Mapbox",
"map",
"ids",
".",
"Optionally",
"overlay",
"with",
"geojson",
"features",
"."
] | python | train | 34.133333 |
mabuchilab/QNET | src/qnet/algebra/core/abstract_algebra.py | https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/core/abstract_algebra.py#L712-L790 | def _apply_rules(expr, rules):
"""Recursively re-instantiate the expression, while applying all of the
given `rules` to all encountered (sub-) expressions
Args:
expr: Any Expression or scalar object
rules (list, ~collections.OrderedDict): A list of rules dictionary
mapping name... | [
"def",
"_apply_rules",
"(",
"expr",
",",
"rules",
")",
":",
"if",
"LOG",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'QNET.create'",
")",
"stack",
"=",
"[",
"]",
"path",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"expr",
",",
"Expression",
")... | Recursively re-instantiate the expression, while applying all of the
given `rules` to all encountered (sub-) expressions
Args:
expr: Any Expression or scalar object
rules (list, ~collections.OrderedDict): A list of rules dictionary
mapping names to rules, where each rule is a tuple... | [
"Recursively",
"re",
"-",
"instantiate",
"the",
"expression",
"while",
"applying",
"all",
"of",
"the",
"given",
"rules",
"to",
"all",
"encountered",
"(",
"sub",
"-",
")",
"expressions"
] | python | train | 44.189873 |
OSSOS/MOP | src/jjk/preproc/MOPfits_old.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfits_old.py#L631-L646 | def find_proc_date(header):
"""Search the HISTORY fields of a header looking for the FLIPS
processing date.
"""
import string, re
for h in header.ascardlist():
if h.key=="HISTORY":
g=h.value
if ( string.find(g,'FLIPS 1.0 -:') ):
result=re.search('imred... | [
"def",
"find_proc_date",
"(",
"header",
")",
":",
"import",
"string",
",",
"re",
"for",
"h",
"in",
"header",
".",
"ascardlist",
"(",
")",
":",
"if",
"h",
".",
"key",
"==",
"\"HISTORY\"",
":",
"g",
"=",
"h",
".",
"value",
"if",
"(",
"string",
".",
... | Search the HISTORY fields of a header looking for the FLIPS
processing date. | [
"Search",
"the",
"HISTORY",
"fields",
"of",
"a",
"header",
"looking",
"for",
"the",
"FLIPS",
"processing",
"date",
"."
] | python | train | 35.25 |
chaoss/grimoirelab-perceval | perceval/backends/core/phabricator.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/phabricator.py#L544-L555 | def phids(self, *phids):
"""Retrieve data about PHIDs.
:params phids: list of PHIDs
"""
params = {
self.PHIDS: phids
}
response = self._call(self.PHAB_PHIDS, params)
return response | [
"def",
"phids",
"(",
"self",
",",
"*",
"phids",
")",
":",
"params",
"=",
"{",
"self",
".",
"PHIDS",
":",
"phids",
"}",
"response",
"=",
"self",
".",
"_call",
"(",
"self",
".",
"PHAB_PHIDS",
",",
"params",
")",
"return",
"response"
] | Retrieve data about PHIDs.
:params phids: list of PHIDs | [
"Retrieve",
"data",
"about",
"PHIDs",
"."
] | python | test | 20.083333 |
jakebasile/reap | reap/api/admin.py | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L84-L97 | def create_project(self, name, client_id, budget = None, budget_by =
'none', notes = None, billable = True):
'''Creates a Project with the given information.'''
project = {'project':{
'name': name,
'client_id': client_id,
'budget_by': budget_by,
'budg... | [
"def",
"create_project",
"(",
"self",
",",
"name",
",",
"client_id",
",",
"budget",
"=",
"None",
",",
"budget_by",
"=",
"'none'",
",",
"notes",
"=",
"None",
",",
"billable",
"=",
"True",
")",
":",
"project",
"=",
"{",
"'project'",
":",
"{",
"'name'",
... | Creates a Project with the given information. | [
"Creates",
"a",
"Project",
"with",
"the",
"given",
"information",
"."
] | python | train | 38.642857 |
poldracklab/niworkflows | niworkflows/viz/plots.py | https://github.com/poldracklab/niworkflows/blob/254f4b4fcc5e6ecb29d2f4602a30786b913ecce5/niworkflows/viz/plots.py#L550-L673 | def compcor_variance_plot(metadata_files, metadata_sources=None,
output_file=None, varexp_thresh=(0.5, 0.7, 0.9),
fig=None):
"""
Parameters
----------
metadata_files: list
List of paths to files containing component metadata. If more than one
... | [
"def",
"compcor_variance_plot",
"(",
"metadata_files",
",",
"metadata_sources",
"=",
"None",
",",
"output_file",
"=",
"None",
",",
"varexp_thresh",
"=",
"(",
"0.5",
",",
"0.7",
",",
"0.9",
")",
",",
"fig",
"=",
"None",
")",
":",
"metadata",
"=",
"{",
"}"... | Parameters
----------
metadata_files: list
List of paths to files containing component metadata. If more than one
decomposition has been performed (e.g., anatomical and temporal
CompCor decompositions), then all metadata files can be provided in
the list. However, each metadata f... | [
"Parameters",
"----------",
"metadata_files",
":",
"list",
"List",
"of",
"paths",
"to",
"files",
"containing",
"component",
"metadata",
".",
"If",
"more",
"than",
"one",
"decomposition",
"has",
"been",
"performed",
"(",
"e",
".",
"g",
".",
"anatomical",
"and",... | python | train | 38.41129 |
pywbem/pywbem | examples/wbemcli_server.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/examples/wbemcli_server.py#L12-L27 | def print_profile_info(org_vm, profile_instance):
"""
Print information on a profile defined by profile_instance.
Parameters:
org_vm: The value mapping for CIMRegisterdProfile and
RegisteredOrganization so that the value and not value mapping
is displayed.
profile_instance... | [
"def",
"print_profile_info",
"(",
"org_vm",
",",
"profile_instance",
")",
":",
"org",
"=",
"org_vm",
".",
"tovalues",
"(",
"profile_instance",
"[",
"'RegisteredOrganization'",
"]",
")",
"name",
"=",
"profile_instance",
"[",
"'RegisteredName'",
"]",
"vers",
"=",
... | Print information on a profile defined by profile_instance.
Parameters:
org_vm: The value mapping for CIMRegisterdProfile and
RegisteredOrganization so that the value and not value mapping
is displayed.
profile_instance: instance of a profile to be printed | [
"Print",
"information",
"on",
"a",
"profile",
"defined",
"by",
"profile_instance",
"."
] | python | train | 35.4375 |
wdbm/abstraction | abstraction.py | https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/abstraction.py#L314-L373 | def load_exchange_word_vectors(
filename = "database.db",
maximum_number_of_events = None
):
"""
Load exchange data and return dataset.
"""
log.info("load word vectors of database {filename}".format(
filename = filename
))
# Ensure that the database exists.
... | [
"def",
"load_exchange_word_vectors",
"(",
"filename",
"=",
"\"database.db\"",
",",
"maximum_number_of_events",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"load word vectors of database {filename}\"",
".",
"format",
"(",
"filename",
"=",
"filename",
")",
")",
... | Load exchange data and return dataset. | [
"Load",
"exchange",
"data",
"and",
"return",
"dataset",
"."
] | python | train | 44.6 |
ungarj/s2reader | s2reader/s2reader.py | https://github.com/ungarj/s2reader/blob/376fd7ee1d15cce0849709c149d694663a7bc0ef/s2reader/s2reader.py#L357-L428 | def band_path(self, band_id, for_gdal=False, absolute=False):
"""Return paths of given band's jp2 files for all granules."""
band_id = str(band_id).zfill(2)
if not isinstance(band_id, str) or band_id not in BAND_IDS:
raise ValueError("band ID not valid: %s" % band_id)
if self... | [
"def",
"band_path",
"(",
"self",
",",
"band_id",
",",
"for_gdal",
"=",
"False",
",",
"absolute",
"=",
"False",
")",
":",
"band_id",
"=",
"str",
"(",
"band_id",
")",
".",
"zfill",
"(",
"2",
")",
"if",
"not",
"isinstance",
"(",
"band_id",
",",
"str",
... | Return paths of given band's jp2 files for all granules. | [
"Return",
"paths",
"of",
"given",
"band",
"s",
"jp2",
"files",
"for",
"all",
"granules",
"."
] | python | train | 41.152778 |
MoseleyBioinformaticsLab/ctfile | ctfile/tokenizer.py | https://github.com/MoseleyBioinformaticsLab/ctfile/blob/eae864126cd9102207df5d363a3222256a0f1396/ctfile/tokenizer.py#L150-L162 | def _ctab_property_block(stream):
"""Process properties block of ``Ctab``.
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
:rtype: :class:`~ctfile.tokenizer.CtabPropertiesBlockLine`
"""
line = stream.popleft()
while lin... | [
"def",
"_ctab_property_block",
"(",
"stream",
")",
":",
"line",
"=",
"stream",
".",
"popleft",
"(",
")",
"while",
"line",
"!=",
"'M END'",
":",
"name",
"=",
"line",
".",
"split",
"(",
")",
"[",
"1",
"]",
"yield",
"CtabPropertiesBlockLine",
"(",
"name",
... | Process properties block of ``Ctab``.
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
:rtype: :class:`~ctfile.tokenizer.CtabPropertiesBlockLine` | [
"Process",
"properties",
"block",
"of",
"Ctab",
"."
] | python | train | 33.461538 |
F5Networks/f5-common-python | f5/bigip/mixins.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L220-L235 | def _check_command_result(self):
"""If command result exists run these checks."""
if self.commandResult.startswith('/bin/bash'):
raise UtilError('%s' % self.commandResult.split(' ', 1)[1])
if self.commandResult.startswith('/bin/mv'):
raise UtilError('%s' % self.commandRes... | [
"def",
"_check_command_result",
"(",
"self",
")",
":",
"if",
"self",
".",
"commandResult",
".",
"startswith",
"(",
"'/bin/bash'",
")",
":",
"raise",
"UtilError",
"(",
"'%s'",
"%",
"self",
".",
"commandResult",
".",
"split",
"(",
"' '",
",",
"1",
")",
"["... | If command result exists run these checks. | [
"If",
"command",
"result",
"exists",
"run",
"these",
"checks",
"."
] | python | train | 56.6875 |
taxjar/taxjar-python | taxjar/client.py | https://github.com/taxjar/taxjar-python/blob/be9b30d7dc968d24e066c7c133849fee180f8d95/taxjar/client.py#L126-L129 | def validate(self, vat_deets):
"""Validates an existing VAT identification number against VIES."""
request = self._get('validation', vat_deets)
return self.responder(request) | [
"def",
"validate",
"(",
"self",
",",
"vat_deets",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'validation'",
",",
"vat_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | Validates an existing VAT identification number against VIES. | [
"Validates",
"an",
"existing",
"VAT",
"identification",
"number",
"against",
"VIES",
"."
] | python | train | 48.75 |
edoburu/django-debugtools | debugtools/formatter.py | https://github.com/edoburu/django-debugtools/blob/5c609c00fa9954330cd135fc62a1e18b8e7fea8a/debugtools/formatter.py#L129-L152 | def _style_text(text):
"""
Apply some HTML highlighting to the contents.
This can't be done in the
"""
# Escape text and apply some formatting.
# To have really good highlighting, pprint would have to be re-implemented.
text = escape(text)
text = text.replace(' <iterator object>', ... | [
"def",
"_style_text",
"(",
"text",
")",
":",
"# Escape text and apply some formatting.",
"# To have really good highlighting, pprint would have to be re-implemented.",
"text",
"=",
"escape",
"(",
"text",
")",
"text",
"=",
"text",
".",
"replace",
"(",
"' <iterator object>... | Apply some HTML highlighting to the contents.
This can't be done in the | [
"Apply",
"some",
"HTML",
"highlighting",
"to",
"the",
"contents",
".",
"This",
"can",
"t",
"be",
"done",
"in",
"the"
] | python | test | 64.666667 |
fbcotter/py3nvml | py3nvml/py3nvml.py | https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/py3nvml.py#L4147-L4183 | def nvmlDeviceSetDefaultAutoBoostedClocksEnabled(handle, enabled, flags):
r"""
/**
* Try to set the default state of Auto Boosted clocks on a device. This is the default state that Auto Boosted clocks will
* return to when no compute running processes (e.g. CUDA application which have an active contex... | [
"def",
"nvmlDeviceSetDefaultAutoBoostedClocksEnabled",
"(",
"handle",
",",
"enabled",
",",
"flags",
")",
":",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlDeviceSetDefaultAutoBoostedClocksEnabled\"",
")",
"ret",
"=",
"fn",
"(",
"handle",
",",
"_nvmlEnableState_t",
... | r"""
/**
* Try to set the default state of Auto Boosted clocks on a device. This is the default state that Auto Boosted clocks will
* return to when no compute running processes (e.g. CUDA application which have an active context) are running
*
* For Kepler &tm; or newer non-GeForce fully suppor... | [
"r",
"/",
"**",
"*",
"Try",
"to",
"set",
"the",
"default",
"state",
"of",
"Auto",
"Boosted",
"clocks",
"on",
"a",
"device",
".",
"This",
"is",
"the",
"default",
"state",
"that",
"Auto",
"Boosted",
"clocks",
"will",
"*",
"return",
"to",
"when",
"no",
... | python | train | 63.486486 |
PGower/PyCanvas | pycanvas/apis/assignments.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/assignments.py#L40-L89 | def list_assignments(self, course_id, assignment_ids=None, bucket=None, include=None, needs_grading_count_by_section=None, override_assignment_dates=None, search_term=None):
"""
List assignments.
Returns the list of assignments for the current context.
"""
path = {}
... | [
"def",
"list_assignments",
"(",
"self",
",",
"course_id",
",",
"assignment_ids",
"=",
"None",
",",
"bucket",
"=",
"None",
",",
"include",
"=",
"None",
",",
"needs_grading_count_by_section",
"=",
"None",
",",
"override_assignment_dates",
"=",
"None",
",",
"search... | List assignments.
Returns the list of assignments for the current context. | [
"List",
"assignments",
".",
"Returns",
"the",
"list",
"of",
"assignments",
"for",
"the",
"current",
"context",
"."
] | python | train | 50.5 |
QuantEcon/QuantEcon.py | quantecon/random/utilities.py | https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/random/utilities.py#L66-L89 | def _probvec(r, out):
"""
Fill `out` with randomly sampled probability vectors as rows.
To be complied as a ufunc by guvectorize of Numba. The inputs must
have the same shape except the last axis; the length of the last
axis of `r` must be that of `out` minus 1, i.e., if out.shape[-1] is
k, the... | [
"def",
"_probvec",
"(",
"r",
",",
"out",
")",
":",
"n",
"=",
"r",
".",
"shape",
"[",
"0",
"]",
"r",
".",
"sort",
"(",
")",
"out",
"[",
"0",
"]",
"=",
"r",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"out",
... | Fill `out` with randomly sampled probability vectors as rows.
To be complied as a ufunc by guvectorize of Numba. The inputs must
have the same shape except the last axis; the length of the last
axis of `r` must be that of `out` minus 1, i.e., if out.shape[-1] is
k, then r.shape[-1] must be k-1.
Pa... | [
"Fill",
"out",
"with",
"randomly",
"sampled",
"probability",
"vectors",
"as",
"rows",
"."
] | python | train | 25.625 |
zarr-developers/zarr | zarr/hierarchy.py | https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L791-L810 | def require_dataset(self, name, shape, dtype=None, exact=False, **kwargs):
"""Obtain an array, creating if it doesn't exist. Other `kwargs` are
as per :func:`zarr.hierarchy.Group.create_dataset`.
Parameters
----------
name : string
Array name.
shape : int or ... | [
"def",
"require_dataset",
"(",
"self",
",",
"name",
",",
"shape",
",",
"dtype",
"=",
"None",
",",
"exact",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_write_op",
"(",
"self",
".",
"_require_dataset_nosync",
",",
"name",
",... | Obtain an array, creating if it doesn't exist. Other `kwargs` are
as per :func:`zarr.hierarchy.Group.create_dataset`.
Parameters
----------
name : string
Array name.
shape : int or tuple of ints
Array shape.
dtype : string or dtype, optional
... | [
"Obtain",
"an",
"array",
"creating",
"if",
"it",
"doesn",
"t",
"exist",
".",
"Other",
"kwargs",
"are",
"as",
"per",
":",
"func",
":",
"zarr",
".",
"hierarchy",
".",
"Group",
".",
"create_dataset",
"."
] | python | train | 35.95 |
hubo1016/vlcp | vlcp/event/pqueue.py | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/pqueue.py#L812-L828 | def append(self, event, force = False):
'''
Append an event to queue. The events are classified and appended to sub-queues
:param event: input event
:param force: if True, the event is appended even if the queue is full
:returns: None if appended succes... | [
"def",
"append",
"(",
"self",
",",
"event",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"tree",
"is",
"None",
":",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"raise",
"IndexError",
"(",
"'The queue is removed'",
")",
"else",
":",
"r... | Append an event to queue. The events are classified and appended to sub-queues
:param event: input event
:param force: if True, the event is appended even if the queue is full
:returns: None if appended successfully, or a matcher to match a QueueCanWriteEvent otherwise | [
"Append",
"an",
"event",
"to",
"queue",
".",
"The",
"events",
"are",
"classified",
"and",
"appended",
"to",
"sub",
"-",
"queues",
":",
"param",
"event",
":",
"input",
"event",
":",
"param",
"force",
":",
"if",
"True",
"the",
"event",
"is",
"appended",
... | python | train | 38.705882 |
scheibler/khard | khard/carddav_object.py | https://github.com/scheibler/khard/blob/0f69430c2680f1ff5f073a977a3c5b753b96cc17/khard/carddav_object.py#L221-L235 | def get_first_name_last_name(self):
"""
:rtype: str
"""
names = []
if self._get_first_names():
names += self._get_first_names()
if self._get_additional_names():
names += self._get_additional_names()
if self._get_last_names():
na... | [
"def",
"get_first_name_last_name",
"(",
"self",
")",
":",
"names",
"=",
"[",
"]",
"if",
"self",
".",
"_get_first_names",
"(",
")",
":",
"names",
"+=",
"self",
".",
"_get_first_names",
"(",
")",
"if",
"self",
".",
"_get_additional_names",
"(",
")",
":",
"... | :rtype: str | [
":",
"rtype",
":",
"str"
] | python | test | 30.733333 |
NICTA/revrand | revrand/mathfun/special.py | https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/mathfun/special.py#L91-L124 | def softplus(X):
""" Pass X through a soft-plus function, , in a numerically
stable way (using the log-sum-exp trick).
The softplus transformation is:
.. math::
\log(1 + \exp\{X\})
Parameters
----------
X: ndarray
shape (N,) array or... | [
"def",
"softplus",
"(",
"X",
")",
":",
"if",
"np",
".",
"isscalar",
"(",
"X",
")",
":",
"return",
"logsumexp",
"(",
"np",
".",
"vstack",
"(",
"(",
"np",
".",
"zeros",
"(",
"1",
")",
",",
"[",
"X",
"]",
")",
")",
".",
"T",
",",
"axis",
"=",
... | Pass X through a soft-plus function, , in a numerically
stable way (using the log-sum-exp trick).
The softplus transformation is:
.. math::
\log(1 + \exp\{X\})
Parameters
----------
X: ndarray
shape (N,) array or shape (N, D) array of da... | [
"Pass",
"X",
"through",
"a",
"soft",
"-",
"plus",
"function",
"in",
"a",
"numerically",
"stable",
"way",
"(",
"using",
"the",
"log",
"-",
"sum",
"-",
"exp",
"trick",
")",
"."
] | python | train | 27.323529 |
fracpete/python-weka-wrapper3 | python/weka/flow/source.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/source.py#L116-L133 | def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(Fil... | [
"def",
"fix_config",
"(",
"self",
",",
"options",
")",
":",
"options",
"=",
"super",
"(",
"FileSupplier",
",",
"self",
")",
".",
"fix_config",
"(",
"options",
")",
"opt",
"=",
"\"files\"",
"if",
"opt",
"not",
"in",
"options",
":",
"options",
"[",
"opt"... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | [
"Fixes",
"the",
"options",
"if",
"necessary",
".",
"I",
".",
"e",
".",
"it",
"adds",
"all",
"required",
"elements",
"to",
"the",
"dictionary",
"."
] | python | train | 30.5 |
ellmetha/django-machina | machina/apps/forum_conversation/forms.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forms.py#L197-L224 | def save(self, commit=True):
""" Saves the instance. """
if not self.instance.pk:
# First, handle topic creation
if 'topic_type' in self.cleaned_data and len(self.cleaned_data['topic_type']):
topic_type = self.cleaned_data['topic_type']
else:
... | [
"def",
"save",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"instance",
".",
"pk",
":",
"# First, handle topic creation",
"if",
"'topic_type'",
"in",
"self",
".",
"cleaned_data",
"and",
"len",
"(",
"self",
".",
"cleaned_data... | Saves the instance. | [
"Saves",
"the",
"instance",
"."
] | python | train | 42.571429 |
johnnoone/aioconsul | aioconsul/client/health_endpoint.py | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/health_endpoint.py#L16-L69 | async def node(self, node, *, dc=None, watch=None, consistency=None):
"""Returns the health info of a node.
Parameters:
node (ObjectID): Node ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blo... | [
"async",
"def",
"node",
"(",
"self",
",",
"node",
",",
"*",
",",
"dc",
"=",
"None",
",",
"watch",
"=",
"None",
",",
"consistency",
"=",
"None",
")",
":",
"node_id",
"=",
"extract_attr",
"(",
"node",
",",
"keys",
"=",
"[",
"\"Node\"",
",",
"\"ID\"",... | Returns the health info of a node.
Parameters:
node (ObjectID): Node ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blocking): Do a blocking query
consistency (Consistency): Force consiste... | [
"Returns",
"the",
"health",
"info",
"of",
"a",
"node",
"."
] | python | train | 37.740741 |
NAMD/pypln.api | pypln/api.py | https://github.com/NAMD/pypln.api/blob/ccb73fd80ca094669a85bd3991dc84a8564ab016/pypln/api.py#L275-L282 | def documents(self, full=False):
'''Return list of documents owned by user.
If `full=True`, it'll download all pages returned by the HTTP server'''
url = self.base_url + self.DOCUMENTS_PAGE
class_ = Document
results = self._retrieve_resources(url, class_, full)
return re... | [
"def",
"documents",
"(",
"self",
",",
"full",
"=",
"False",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"self",
".",
"DOCUMENTS_PAGE",
"class_",
"=",
"Document",
"results",
"=",
"self",
".",
"_retrieve_resources",
"(",
"url",
",",
"class_",
",",
... | Return list of documents owned by user.
If `full=True`, it'll download all pages returned by the HTTP server | [
"Return",
"list",
"of",
"documents",
"owned",
"by",
"user",
"."
] | python | train | 39.75 |
ultrabug/py3status | py3status/modules/xrandr.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/xrandr.py#L272-L279 | def _get_string_and_set_width(self, combination, mode):
"""
Construct the string to be displayed and record the max width.
"""
show = "{}".format(self._separator(mode)).join(combination)
show = show.rstrip("{}".format(self._separator(mode)))
self.max_width = max([self.max... | [
"def",
"_get_string_and_set_width",
"(",
"self",
",",
"combination",
",",
"mode",
")",
":",
"show",
"=",
"\"{}\"",
".",
"format",
"(",
"self",
".",
"_separator",
"(",
"mode",
")",
")",
".",
"join",
"(",
"combination",
")",
"show",
"=",
"show",
".",
"rs... | Construct the string to be displayed and record the max width. | [
"Construct",
"the",
"string",
"to",
"be",
"displayed",
"and",
"record",
"the",
"max",
"width",
"."
] | python | train | 44 |
jrderuiter/pybiomart | src/pybiomart/base.py | https://github.com/jrderuiter/pybiomart/blob/7802d45fe88549ab0512d6f37f815fc43b172b39/src/pybiomart/base.py#L95-L112 | def get(self, **params):
"""Performs get request to the biomart service.
Args:
**params (dict of str: any): Arbitrary keyword arguments, which
are added as parameters to the get request to biomart.
Returns:
requests.models.Response: Response from biomart... | [
"def",
"get",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"if",
"self",
".",
"_use_cache",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"url",
",",
"params",
"=",
"params",
")",
"else",
":",
"with",
"requests_cache",
".",
"disabled"... | Performs get request to the biomart service.
Args:
**params (dict of str: any): Arbitrary keyword arguments, which
are added as parameters to the get request to biomart.
Returns:
requests.models.Response: Response from biomart for the request. | [
"Performs",
"get",
"request",
"to",
"the",
"biomart",
"service",
"."
] | python | train | 32.055556 |
pymc-devs/pymc | pymc/Node.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Node.py#L42-L54 | def logp_gradient_of_set(variable_set, calculation_set=None):
"""
Calculates the gradient of the joint log posterior with respect to all the variables in variable_set.
Calculation of the log posterior is restricted to the variables in calculation_set.
Returns a dictionary of the gradients.
"""
... | [
"def",
"logp_gradient_of_set",
"(",
"variable_set",
",",
"calculation_set",
"=",
"None",
")",
":",
"logp_gradients",
"=",
"{",
"}",
"for",
"variable",
"in",
"variable_set",
":",
"logp_gradients",
"[",
"variable",
"]",
"=",
"logp_gradient",
"(",
"variable",
",",
... | Calculates the gradient of the joint log posterior with respect to all the variables in variable_set.
Calculation of the log posterior is restricted to the variables in calculation_set.
Returns a dictionary of the gradients. | [
"Calculates",
"the",
"gradient",
"of",
"the",
"joint",
"log",
"posterior",
"with",
"respect",
"to",
"all",
"the",
"variables",
"in",
"variable_set",
".",
"Calculation",
"of",
"the",
"log",
"posterior",
"is",
"restricted",
"to",
"the",
"variables",
"in",
"calcu... | python | train | 35.769231 |
DataKitchen/DKCloudCommand | DKCloudCommand/cli/__main__.py | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L822-L827 | def delete_orderrun(backend, orderrun_id):
"""
Delete the orderrun specified by the argument.
"""
click.secho('%s - Deleting orderrun %s' % (get_datetime(), orderrun_id), fg='green')
check_and_print(DKCloudCommandRunner.delete_orderrun(backend.dki, orderrun_id.strip())) | [
"def",
"delete_orderrun",
"(",
"backend",
",",
"orderrun_id",
")",
":",
"click",
".",
"secho",
"(",
"'%s - Deleting orderrun %s'",
"%",
"(",
"get_datetime",
"(",
")",
",",
"orderrun_id",
")",
",",
"fg",
"=",
"'green'",
")",
"check_and_print",
"(",
"DKCloudComm... | Delete the orderrun specified by the argument. | [
"Delete",
"the",
"orderrun",
"specified",
"by",
"the",
"argument",
"."
] | python | train | 47.5 |
GeorgeArgyros/sfalearn | sfalearn/observationtableinit.py | https://github.com/GeorgeArgyros/sfalearn/blob/68a93f507e2fb7d89ca04bd8a8f0da2d6c680443/sfalearn/observationtableinit.py#L200-L287 | def _init_using_k_equivalence(self, given_graph, sfa=False):
"""
Args:
given_graph (DFA): The DFA states
sfa (boolean): A boolean for chosing SFA
Return:
list, list, list: sm_vector, smi_vector, em_vector initialization vectors
"""
graph = DFA(... | [
"def",
"_init_using_k_equivalence",
"(",
"self",
",",
"given_graph",
",",
"sfa",
"=",
"False",
")",
":",
"graph",
"=",
"DFA",
"(",
"self",
".",
"alphabet",
")",
"graph",
".",
"init_from_acceptor",
"(",
"given_graph",
")",
"graph",
".",
"fixminimized",
"(",
... | Args:
given_graph (DFA): The DFA states
sfa (boolean): A boolean for chosing SFA
Return:
list, list, list: sm_vector, smi_vector, em_vector initialization vectors | [
"Args",
":",
"given_graph",
"(",
"DFA",
")",
":",
"The",
"DFA",
"states",
"sfa",
"(",
"boolean",
")",
":",
"A",
"boolean",
"for",
"chosing",
"SFA",
"Return",
":",
"list",
"list",
"list",
":",
"sm_vector",
"smi_vector",
"em_vector",
"initialization",
"vecto... | python | train | 44.681818 |
O365/python-o365 | O365/drive.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/drive.py#L549-L577 | def get_thumbnails(self, size=None):
""" Returns this Item Thumbnails. Thumbnails are not supported on
SharePoint Server 2016.
:param size: request only the specified size: ej: "small",
Custom 300x400 px: "c300x400", Crop: "c300x400_Crop"
:return: Thumbnail Data
:rtype:... | [
"def",
"get_thumbnails",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"object_id",
":",
"return",
"[",
"]",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'thumbnails'",
")",
".",... | Returns this Item Thumbnails. Thumbnails are not supported on
SharePoint Server 2016.
:param size: request only the specified size: ej: "small",
Custom 300x400 px: "c300x400", Crop: "c300x400_Crop"
:return: Thumbnail Data
:rtype: dict | [
"Returns",
"this",
"Item",
"Thumbnails",
".",
"Thumbnails",
"are",
"not",
"supported",
"on",
"SharePoint",
"Server",
"2016",
"."
] | python | train | 27.206897 |
maraujop/requests-oauth2 | requests_oauth2/oauth2.py | https://github.com/maraujop/requests-oauth2/blob/191995aa571d0fbdf5bb166fb0668d5e73fe7817/requests_oauth2/oauth2.py#L41-L46 | def _check_configuration(self, *attrs):
"""Check that each named attr has been configured
"""
for attr in attrs:
if getattr(self, attr, None) is None:
raise ConfigurationError("{} not configured".format(attr)) | [
"def",
"_check_configuration",
"(",
"self",
",",
"*",
"attrs",
")",
":",
"for",
"attr",
"in",
"attrs",
":",
"if",
"getattr",
"(",
"self",
",",
"attr",
",",
"None",
")",
"is",
"None",
":",
"raise",
"ConfigurationError",
"(",
"\"{} not configured\"",
".",
... | Check that each named attr has been configured | [
"Check",
"that",
"each",
"named",
"attr",
"has",
"been",
"configured"
] | python | train | 42.666667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.