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 |
|---|---|---|---|---|---|---|---|---|---|
coumbole/mailscanner | mailscanner/reader.py | https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/reader.py#L60-L72 | def get_subject(self, msg):
"""Extracts the subject line from an EmailMessage object."""
text, encoding = decode_header(msg['subject'])[-1]
try:
text = text.decode(encoding)
# If it's already decoded, ignore error
except AttributeError:
pass
re... | [
"def",
"get_subject",
"(",
"self",
",",
"msg",
")",
":",
"text",
",",
"encoding",
"=",
"decode_header",
"(",
"msg",
"[",
"'subject'",
"]",
")",
"[",
"-",
"1",
"]",
"try",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"encoding",
")",
"# If it's alrea... | Extracts the subject line from an EmailMessage object. | [
"Extracts",
"the",
"subject",
"line",
"from",
"an",
"EmailMessage",
"object",
"."
] | python | train | 24.384615 |
timkpaine/pyEX | pyEX/marketdata/http.py | https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/marketdata/http.py#L525-L556 | def tradingStatus(symbol=None, token='', version=''):
'''The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination ... | [
"def",
"tradingStatus",
"(",
"symbol",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"_raiseIfNotStr",
"(",
"symbol",
")",
"if",
"symbol",
":",
"return",
"_getJson",
"(",
"'deep/trading-status?symbols='",
"+",
"symbol",
",",
"t... | The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination or regulatory reasons.
For non-IEX-listed securities, IE... | [
"The",
"Trading",
"status",
"message",
"is",
"used",
"to",
"indicate",
"the",
"current",
"trading",
"status",
"of",
"a",
"security",
".",
"For",
"IEX",
"-",
"listed",
"securities",
"IEX",
"acts",
"as",
"the",
"primary",
"market",
"and",
"has",
"the",
"auth... | python | valid | 56.21875 |
msmbuilder/osprey | osprey/plugins/plugin_pylearn2.py | https://github.com/msmbuilder/osprey/blob/ea09da24e45820e1300e24a52fefa6c849f7a986/osprey/plugins/plugin_pylearn2.py#L31-L41 | def _get_param_names(self):
"""
Get mappable parameters from YAML.
"""
template = Template(self.yaml_string)
names = ['yaml_string'] # always include the template
for match in re.finditer(template.pattern, template.template):
name = match.group('named') or ma... | [
"def",
"_get_param_names",
"(",
"self",
")",
":",
"template",
"=",
"Template",
"(",
"self",
".",
"yaml_string",
")",
"names",
"=",
"[",
"'yaml_string'",
"]",
"# always include the template",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"template",
".",
... | Get mappable parameters from YAML. | [
"Get",
"mappable",
"parameters",
"from",
"YAML",
"."
] | python | valid | 37.909091 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py#L312-L374 | def acquire_hosting_device_slots(self, context, hosting_device, resource,
resource_type, resource_service, num,
exclusive=False):
"""Assign <num> slots in <hosting_device> to logical <resource>.
If exclusive is True the hosting d... | [
"def",
"acquire_hosting_device_slots",
"(",
"self",
",",
"context",
",",
"hosting_device",
",",
"resource",
",",
"resource_type",
",",
"resource_service",
",",
"num",
",",
"exclusive",
"=",
"False",
")",
":",
"bound",
"=",
"hosting_device",
"[",
"'tenant_bound'",
... | Assign <num> slots in <hosting_device> to logical <resource>.
If exclusive is True the hosting device is bound to the resource's
tenant. Otherwise it is not bound to any tenant.
Returns True if allocation was granted, False otherwise. | [
"Assign",
"<num",
">",
"slots",
"in",
"<hosting_device",
">",
"to",
"logical",
"<resource",
">",
"."
] | python | train | 56.079365 |
JasonKessler/scattertext | scattertext/termcompaction/AssociationCompactor.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termcompaction/AssociationCompactor.py#L85-L98 | def compact(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
TermDocMatrix
'''
rank_df = self.scorer.get_rank_df(term_doc_matrix)
return s... | [
"def",
"compact",
"(",
"self",
",",
"term_doc_matrix",
")",
":",
"rank_df",
"=",
"self",
".",
"scorer",
".",
"get_rank_df",
"(",
"term_doc_matrix",
")",
"return",
"self",
".",
"_prune_higher_ranked_terms",
"(",
"term_doc_matrix",
",",
"rank_df",
",",
"self",
"... | Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
TermDocMatrix | [
"Parameters",
"----------",
"term_doc_matrix",
":",
"TermDocMatrix",
"Term",
"document",
"matrix",
"object",
"to",
"compact",
"Returns",
"-------",
"TermDocMatrix"
] | python | train | 26.714286 |
PGower/PyCanvas | pycanvas/apis/assignments.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/assignments.py#L865-L890 | def batch_retrieve_overrides_in_course(self, course_id, assignment_overrides_id, assignment_overrides_assignment_id):
"""
Batch retrieve overrides in a course.
Returns a list of specified overrides in this course, providing
they target sections/groups/students visible to the curren... | [
"def",
"batch_retrieve_overrides_in_course",
"(",
"self",
",",
"course_id",
",",
"assignment_overrides_id",
",",
"assignment_overrides_assignment_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
... | Batch retrieve overrides in a course.
Returns a list of specified overrides in this course, providing
they target sections/groups/students visible to the current user.
Returns null elements in the list for requests that were not found. | [
"Batch",
"retrieve",
"overrides",
"in",
"a",
"course",
".",
"Returns",
"a",
"list",
"of",
"specified",
"overrides",
"in",
"this",
"course",
"providing",
"they",
"target",
"sections",
"/",
"groups",
"/",
"students",
"visible",
"to",
"the",
"current",
"user",
... | python | train | 47.961538 |
Microsoft/LightGBM | python-package/lightgbm/basic.py | https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1232-L1245 | def _set_predictor(self, predictor):
"""Set predictor for continued training.
It is not recommended for user to call this function.
Please use init_model argument in engine.train() or engine.cv() instead.
"""
if predictor is self._predictor:
return self
if se... | [
"def",
"_set_predictor",
"(",
"self",
",",
"predictor",
")",
":",
"if",
"predictor",
"is",
"self",
".",
"_predictor",
":",
"return",
"self",
"if",
"self",
".",
"data",
"is",
"not",
"None",
":",
"self",
".",
"_predictor",
"=",
"predictor",
"return",
"self... | Set predictor for continued training.
It is not recommended for user to call this function.
Please use init_model argument in engine.train() or engine.cv() instead. | [
"Set",
"predictor",
"for",
"continued",
"training",
"."
] | python | train | 42.5 |
a1ezzz/wasp-general | wasp_general/types/binarray.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/types/binarray.py#L178-L194 | def split(self, bits_count):
""" Split array into smaller parts. Each small array is fixed-length WBinArray (length of that array is
bits_count).
:param bits_count: array length
:return: list of WBinArray
"""
result = []
array = WBinArray(self.__value, self.__size)
if (len(array) % bits_count) > 0:
... | [
"def",
"split",
"(",
"self",
",",
"bits_count",
")",
":",
"result",
"=",
"[",
"]",
"array",
"=",
"WBinArray",
"(",
"self",
".",
"__value",
",",
"self",
".",
"__size",
")",
"if",
"(",
"len",
"(",
"array",
")",
"%",
"bits_count",
")",
">",
"0",
":"... | Split array into smaller parts. Each small array is fixed-length WBinArray (length of that array is
bits_count).
:param bits_count: array length
:return: list of WBinArray | [
"Split",
"array",
"into",
"smaller",
"parts",
".",
"Each",
"small",
"array",
"is",
"fixed",
"-",
"length",
"WBinArray",
"(",
"length",
"of",
"that",
"array",
"is",
"bits_count",
")",
"."
] | python | train | 29.352941 |
kdeldycke/maildir-deduplicate | maildir_deduplicate/deduplicate.py | https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L122-L157 | def check_differences(self):
""" In-depth check of mail differences.
Compare all mails of the duplicate set with each other, both in size
and content. Raise an error if we're not within the limits imposed by
the threshold setting.
"""
logger.info("Check that mail differe... | [
"def",
"check_differences",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Check that mail differences are within the limits.\"",
")",
"if",
"self",
".",
"conf",
".",
"size_threshold",
"<",
"0",
":",
"logger",
".",
"info",
"(",
"\"Skip checking for size diffe... | In-depth check of mail differences.
Compare all mails of the duplicate set with each other, both in size
and content. Raise an error if we're not within the limits imposed by
the threshold setting. | [
"In",
"-",
"depth",
"check",
"of",
"mail",
"differences",
"."
] | python | train | 46.833333 |
spacetelescope/synphot_refactor | synphot/spectrum.py | https://github.com/spacetelescope/synphot_refactor/blob/9c064f3cff0c41dd8acadc0f67c6350931275b9f/synphot/spectrum.py#L495-L521 | def avgwave(self, wavelengths=None):
"""Calculate the :ref:`average wavelength <synphot-formula-avgwv>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be... | [
"def",
"avgwave",
"(",
"self",
",",
"wavelengths",
"=",
"None",
")",
":",
"x",
"=",
"self",
".",
"_validate_wavelengths",
"(",
"wavelengths",
")",
".",
"value",
"y",
"=",
"self",
"(",
"x",
")",
".",
"value",
"num",
"=",
"np",
".",
"trapz",
"(",
"y"... | Calculate the :ref:`average wavelength <synphot-formula-avgwv>`.
Parameters
----------
wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None`
Wavelength values for sampling.
If not a Quantity, assumed to be in Angstrom.
If `None`, `waveset` i... | [
"Calculate",
"the",
":",
"ref",
":",
"average",
"wavelength",
"<synphot",
"-",
"formula",
"-",
"avgwv",
">",
"."
] | python | train | 29.777778 |
sirfoga/pyhal | hal/ml/correlation.py | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/ml/correlation.py#L42-L50 | def show_correlation_matrix(self, correlation_matrix):
"""Shows the given correlation matrix as image
:param correlation_matrix: Correlation matrix of features
"""
cr_plot.create_correlation_matrix_plot(
correlation_matrix, self.title, self.headers_to_test
)
... | [
"def",
"show_correlation_matrix",
"(",
"self",
",",
"correlation_matrix",
")",
":",
"cr_plot",
".",
"create_correlation_matrix_plot",
"(",
"correlation_matrix",
",",
"self",
".",
"title",
",",
"self",
".",
"headers_to_test",
")",
"pyplot",
".",
"show",
"(",
")"
] | Shows the given correlation matrix as image
:param correlation_matrix: Correlation matrix of features | [
"Shows",
"the",
"given",
"correlation",
"matrix",
"as",
"image"
] | python | train | 36.111111 |
textX/textX | textx/model.py | https://github.com/textX/textX/blob/5796ac38116ad86584392dbecdbf923ede746361/textx/model.py#L49-L66 | def get_parent_of_type(typ, obj):
"""
Finds first object up the parent chain of the given type.
If no parent of the given type exists None is returned.
Args:
typ(str or python class): The type of the model object we are
looking for.
obj (model object): Python model object wh... | [
"def",
"get_parent_of_type",
"(",
"typ",
",",
"obj",
")",
":",
"if",
"type",
"(",
"typ",
")",
"is",
"not",
"text",
":",
"typ",
"=",
"typ",
".",
"__name__",
"while",
"hasattr",
"(",
"obj",
",",
"'parent'",
")",
":",
"obj",
"=",
"obj",
".",
"parent",... | Finds first object up the parent chain of the given type.
If no parent of the given type exists None is returned.
Args:
typ(str or python class): The type of the model object we are
looking for.
obj (model object): Python model object which is the start of the
search pro... | [
"Finds",
"first",
"object",
"up",
"the",
"parent",
"chain",
"of",
"the",
"given",
"type",
".",
"If",
"no",
"parent",
"of",
"the",
"given",
"type",
"exists",
"None",
"is",
"returned",
"."
] | python | train | 30.222222 |
Captricity/captools | captools/api/client.py | https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L258-L269 | def launch_job(self, job_id):
"""
Convenience method for launching a job. We use POST for actions
outside of HTTP verbs (job launch in this case).
"""
assert self.api_version.lower() in ['0.01a', '0.1'], \
'This method is only supported in BETA (0.01) and ALPHA (0.01... | [
"def",
"launch_job",
"(",
"self",
",",
"job_id",
")",
":",
"assert",
"self",
".",
"api_version",
".",
"lower",
"(",
")",
"in",
"[",
"'0.01a'",
",",
"'0.1'",
"]",
",",
"'This method is only supported in BETA (0.01) and ALPHA (0.01a) versions'",
"try",
":",
"self",
... | Convenience method for launching a job. We use POST for actions
outside of HTTP verbs (job launch in this case). | [
"Convenience",
"method",
"for",
"launching",
"a",
"job",
".",
"We",
"use",
"POST",
"for",
"actions",
"outside",
"of",
"HTTP",
"verbs",
"(",
"job",
"launch",
"in",
"this",
"case",
")",
"."
] | python | train | 40 |
haikuginger/beekeeper | beekeeper/api.py | https://github.com/haikuginger/beekeeper/blob/b647d3add0b407ec5dc3a2a39c4f6dac31243b18/beekeeper/api.py#L208-L219 | def printed_out(self, name):
"""
Create a string representation of the action
"""
opt = self.variables().optional_namestring()
req = self.variables().required_namestring()
out = ''
out += '| |\n'
out += '| |---{}({}{})\n'.format(name, req, opt)
... | [
"def",
"printed_out",
"(",
"self",
",",
"name",
")",
":",
"opt",
"=",
"self",
".",
"variables",
"(",
")",
".",
"optional_namestring",
"(",
")",
"req",
"=",
"self",
".",
"variables",
"(",
")",
".",
"required_namestring",
"(",
")",
"out",
"=",
"''",
"o... | Create a string representation of the action | [
"Create",
"a",
"string",
"representation",
"of",
"the",
"action"
] | python | train | 34.333333 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/localization.py | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/localization.py#L113-L122 | def send_short_lpp_packet(self, dest_id, data):
"""
Send ultra-wide-band LPP packet to dest_id
"""
pk = CRTPPacket()
pk.port = CRTPPort.LOCALIZATION
pk.channel = self.GENERIC_CH
pk.data = struct.pack('<BB', self.LPS_SHORT_LPP_PACKET, dest_id) + data
self.... | [
"def",
"send_short_lpp_packet",
"(",
"self",
",",
"dest_id",
",",
"data",
")",
":",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"port",
"=",
"CRTPPort",
".",
"LOCALIZATION",
"pk",
".",
"channel",
"=",
"self",
".",
"GENERIC_CH",
"pk",
".",
"data",
"="... | Send ultra-wide-band LPP packet to dest_id | [
"Send",
"ultra",
"-",
"wide",
"-",
"band",
"LPP",
"packet",
"to",
"dest_id"
] | python | train | 33 |
openstack/networking-cisco | networking_cisco/apps/saf/server/dfa_server.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/dfa_server.py#L809-L849 | def network_delete_event(self, network_info):
"""Process network delete event."""
net_id = network_info['network_id']
if net_id not in self.network:
LOG.error('network_delete_event: net_id %s does not exist.',
net_id)
return
segid = self.ne... | [
"def",
"network_delete_event",
"(",
"self",
",",
"network_info",
")",
":",
"net_id",
"=",
"network_info",
"[",
"'network_id'",
"]",
"if",
"net_id",
"not",
"in",
"self",
".",
"network",
":",
"LOG",
".",
"error",
"(",
"'network_delete_event: net_id %s does not exist... | Process network delete event. | [
"Process",
"network",
"delete",
"event",
"."
] | python | train | 43.195122 |
rossdylan/sham | sham/storage/pools.py | https://github.com/rossdylan/sham/blob/d938ae3da43814c3c45ae95b6116bd87282c8691/sham/storage/pools.py#L21-L54 | def create_backed_vol(self, name, backer, _format='qcow2'):
"""
TODO(rdelinger) think about changing _format
This is a pretty specialized function.
It takes an existing volume, and creates a new volume
that is backed by the existing volume
Sadly there is no easy way to do... | [
"def",
"create_backed_vol",
"(",
"self",
",",
"name",
",",
"backer",
",",
"_format",
"=",
"'qcow2'",
")",
":",
"vol_xml",
"=",
"ElementTree",
".",
"Element",
"(",
"'volume'",
")",
"vol_name",
"=",
"ElementTree",
".",
"SubElement",
"(",
"vol_xml",
",",
"'na... | TODO(rdelinger) think about changing _format
This is a pretty specialized function.
It takes an existing volume, and creates a new volume
that is backed by the existing volume
Sadly there is no easy way to do this in libvirt, the
best way I've found is to just create some xml and... | [
"TODO",
"(",
"rdelinger",
")",
"think",
"about",
"changing",
"_format",
"This",
"is",
"a",
"pretty",
"specialized",
"function",
".",
"It",
"takes",
"an",
"existing",
"volume",
"and",
"creates",
"a",
"new",
"volume",
"that",
"is",
"backed",
"by",
"the",
"ex... | python | train | 40.176471 |
ellmetha/django-machina | machina/apps/forum_conversation/views.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L97-L116 | def get_context_data(self, **kwargs):
""" Returns the context data to provide to the template. """
context = super().get_context_data(**kwargs)
# Insert the considered topic and the associated forum into the context
topic = self.get_topic()
context['topic'] = topic
conte... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"# Insert the considered topic and the associated forum into the context",
"topic",
"=",
"self",
".... | Returns the context data to provide to the template. | [
"Returns",
"the",
"context",
"data",
"to",
"provide",
"to",
"the",
"template",
"."
] | python | train | 43.85 |
bokeh/bokeh | bokeh/util/paths.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/paths.py#L44-L50 | def serverdir():
""" Get the location of the server subpackage
"""
path = join(ROOT_DIR, 'server')
path = normpath(path)
if sys.platform == 'cygwin': path = realpath(path)
return path | [
"def",
"serverdir",
"(",
")",
":",
"path",
"=",
"join",
"(",
"ROOT_DIR",
",",
"'server'",
")",
"path",
"=",
"normpath",
"(",
"path",
")",
"if",
"sys",
".",
"platform",
"==",
"'cygwin'",
":",
"path",
"=",
"realpath",
"(",
"path",
")",
"return",
"path"... | Get the location of the server subpackage | [
"Get",
"the",
"location",
"of",
"the",
"server",
"subpackage"
] | python | train | 28.714286 |
neuropsychology/NeuroKit.py | neurokit/signal/events.py | https://github.com/neuropsychology/NeuroKit.py/blob/c9589348fbbde0fa7e986048c48f38e6b488adfe/neurokit/signal/events.py#L19-L65 | def binarize_signal(signal, treshold="auto", cut="higher"):
"""
Binarize a channel based on a continuous channel.
Parameters
----------
signal = array or list
The signal channel.
treshold = float
The treshold value by which to select the events. If "auto", takes the value betwee... | [
"def",
"binarize_signal",
"(",
"signal",
",",
"treshold",
"=",
"\"auto\"",
",",
"cut",
"=",
"\"higher\"",
")",
":",
"if",
"treshold",
"==",
"\"auto\"",
":",
"treshold",
"=",
"(",
"np",
".",
"max",
"(",
"np",
".",
"array",
"(",
"signal",
")",
")",
"-"... | Binarize a channel based on a continuous channel.
Parameters
----------
signal = array or list
The signal channel.
treshold = float
The treshold value by which to select the events. If "auto", takes the value between the max and the min.
cut = str
"higher" or "lower", define... | [
"Binarize",
"a",
"channel",
"based",
"on",
"a",
"continuous",
"channel",
"."
] | python | train | 30.744681 |
nikdon/pyEntropy | pyentrp/entropy.py | https://github.com/nikdon/pyEntropy/blob/ae2bf71c2e5b6edb2e468ff52183b30acf7073e6/pyentrp/entropy.py#L212-L278 | def permutation_entropy(time_series, order=3, delay=1, normalize=False):
"""Permutation Entropy.
Parameters
----------
time_series : list or np.array
Time series
order : int
Order of permutation entropy
delay : int
Time delay
normalize : bool
If True, divide ... | [
"def",
"permutation_entropy",
"(",
"time_series",
",",
"order",
"=",
"3",
",",
"delay",
"=",
"1",
",",
"normalize",
"=",
"False",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"time_series",
")",
"hashmult",
"=",
"np",
".",
"power",
"(",
"order",
",",... | Permutation Entropy.
Parameters
----------
time_series : list or np.array
Time series
order : int
Order of permutation entropy
delay : int
Time delay
normalize : bool
If True, divide by log2(factorial(m)) to normalize the entropy
between 0 and 1. Otherwis... | [
"Permutation",
"Entropy",
"."
] | python | train | 31.641791 |
tensorflow/probability | tensorflow_probability/python/internal/nest_util.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/nest_util.py#L76-L79 | def expand_as_args(args):
"""Returns `True` if `args` should be expanded as `*args`."""
return (isinstance(args, collections.Sequence) and
not _is_namedtuple(args) and not _force_leaf(args)) | [
"def",
"expand_as_args",
"(",
"args",
")",
":",
"return",
"(",
"isinstance",
"(",
"args",
",",
"collections",
".",
"Sequence",
")",
"and",
"not",
"_is_namedtuple",
"(",
"args",
")",
"and",
"not",
"_force_leaf",
"(",
"args",
")",
")"
] | Returns `True` if `args` should be expanded as `*args`. | [
"Returns",
"True",
"if",
"args",
"should",
"be",
"expanded",
"as",
"*",
"args",
"."
] | python | test | 50.25 |
bugra/angel-list | angel/angel.py | https://github.com/bugra/angel-list/blob/75ac453e873727675ba18e1f45b5bc0cfda26fd7/angel/angel.py#L375-L381 | def get_startup(self, id_):
""" Get startup based on id
"""
return _get_request(_STARTUP.format(c_api=_C_API_BEGINNING,
api=_API_VERSION,
id_=id_,
at=self.access_token)) | [
"def",
"get_startup",
"(",
"self",
",",
"id_",
")",
":",
"return",
"_get_request",
"(",
"_STARTUP",
".",
"format",
"(",
"c_api",
"=",
"_C_API_BEGINNING",
",",
"api",
"=",
"_API_VERSION",
",",
"id_",
"=",
"id_",
",",
"at",
"=",
"self",
".",
"access_token"... | Get startup based on id | [
"Get",
"startup",
"based",
"on",
"id"
] | python | train | 42.142857 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2626-L2635 | def set_ifo(self,ifo):
"""
Set the ifo name to analyze. If the channel name for the job is defined,
then the name of the ifo is prepended to the channel name obtained
from the job configuration file and passed with a --channel-name option.
@param ifo: two letter ifo code (e.g. L1, H1 or H2).
"""... | [
"def",
"set_ifo",
"(",
"self",
",",
"ifo",
")",
":",
"self",
".",
"__ifo",
"=",
"ifo",
"if",
"self",
".",
"job",
"(",
")",
".",
"channel",
"(",
")",
":",
"self",
".",
"add_var_opt",
"(",
"'channel-name'",
",",
"ifo",
"+",
"':'",
"+",
"self",
".",... | Set the ifo name to analyze. If the channel name for the job is defined,
then the name of the ifo is prepended to the channel name obtained
from the job configuration file and passed with a --channel-name option.
@param ifo: two letter ifo code (e.g. L1, H1 or H2). | [
"Set",
"the",
"ifo",
"name",
"to",
"analyze",
".",
"If",
"the",
"channel",
"name",
"for",
"the",
"job",
"is",
"defined",
"then",
"the",
"name",
"of",
"the",
"ifo",
"is",
"prepended",
"to",
"the",
"channel",
"name",
"obtained",
"from",
"the",
"job",
"co... | python | train | 43.4 |
ask/redish | redish/client.py | https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L135-L142 | def rename(self, old_name, new_name):
"""Rename key to a new name."""
try:
self.api.rename(mkey(old_name), mkey(new_name))
except ResponseError, exc:
if "no such key" in exc.args:
raise KeyError(old_name)
raise | [
"def",
"rename",
"(",
"self",
",",
"old_name",
",",
"new_name",
")",
":",
"try",
":",
"self",
".",
"api",
".",
"rename",
"(",
"mkey",
"(",
"old_name",
")",
",",
"mkey",
"(",
"new_name",
")",
")",
"except",
"ResponseError",
",",
"exc",
":",
"if",
"\... | Rename key to a new name. | [
"Rename",
"key",
"to",
"a",
"new",
"name",
"."
] | python | train | 34.875 |
tanghaibao/goatools | goatools/cli/wr_sections.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/wr_sections.py#L66-L93 | def cli(self, prt=sys.stdout):
"""Command-line interface for go_draw script."""
kws = self.objdoc.get_docargs(prt=None)
godag = get_godag(kws['obo'], prt=None, loading_bar=False, optional_attrs=['relationship'])
usrgos = GetGOs(godag, max_gos=200).get_usrgos(kws.get('GO_FILE'), prt)
... | [
"def",
"cli",
"(",
"self",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"kws",
"=",
"self",
".",
"objdoc",
".",
"get_docargs",
"(",
"prt",
"=",
"None",
")",
"godag",
"=",
"get_godag",
"(",
"kws",
"[",
"'obo'",
"]",
",",
"prt",
"=",
"None",
... | Command-line interface for go_draw script. | [
"Command",
"-",
"line",
"interface",
"for",
"go_draw",
"script",
"."
] | python | train | 56.821429 |
CloudGenix/sdk-python | cloudgenix/interactive.py | https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L706-L734 | def quick_str_input(prompt, default_value):
"""
Function to display a quick question for text input.
**Parameters:**
- **prompt:** Text / question to display
- **default_value:** Default value for no entry
**Returns:** text_type() or default_value.
"""
... | [
"def",
"quick_str_input",
"(",
"prompt",
",",
"default_value",
")",
":",
"valid",
"=",
"False",
"str_val",
"=",
"default_value",
"while",
"not",
"valid",
":",
"input_val",
"=",
"raw_input",
"(",
"prompt",
"+",
"\"[{0}]: \"",
".",
"format",
"(",
"default_value"... | Function to display a quick question for text input.
**Parameters:**
- **prompt:** Text / question to display
- **default_value:** Default value for no entry
**Returns:** text_type() or default_value. | [
"Function",
"to",
"display",
"a",
"quick",
"question",
"for",
"text",
"input",
"."
] | python | train | 27.965517 |
coursera-dl/coursera-dl | coursera/coursera_dl.py | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/coursera_dl.py#L217-L283 | def main():
"""
Main entry point for execution as a program (instead of as a module).
"""
args = parse_args()
logging.info('coursera_dl version %s', __version__)
completed_classes = []
classes_with_errors = []
mkdir_p(PATH_CACHE, 0o700)
if args.clear_cache:
shutil.rmtree(PA... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"logging",
".",
"info",
"(",
"'coursera_dl version %s'",
",",
"__version__",
")",
"completed_classes",
"=",
"[",
"]",
"classes_with_errors",
"=",
"[",
"]",
"mkdir_p",
"(",
"PATH_CACHE",
",",
... | Main entry point for execution as a program (instead of as a module). | [
"Main",
"entry",
"point",
"for",
"execution",
"as",
"a",
"program",
"(",
"instead",
"of",
"as",
"a",
"module",
")",
"."
] | python | train | 38.298507 |
lk-geimfari/mimesis | mimesis/builtins/nl.py | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/nl.py#L23-L49 | def bsn(self) -> str:
"""Generate a random, but valid ``Burgerservicenummer``.
:returns: Random BSN.
:Example:
255159705
"""
def _is_valid_bsn(number: str) -> bool:
total = 0
multiplier = 9
for char in number:
mul... | [
"def",
"bsn",
"(",
"self",
")",
"->",
"str",
":",
"def",
"_is_valid_bsn",
"(",
"number",
":",
"str",
")",
"->",
"bool",
":",
"total",
"=",
"0",
"multiplier",
"=",
"9",
"for",
"char",
"in",
"number",
":",
"multiplier",
"=",
"-",
"multiplier",
"if",
... | Generate a random, but valid ``Burgerservicenummer``.
:returns: Random BSN.
:Example:
255159705 | [
"Generate",
"a",
"random",
"but",
"valid",
"Burgerservicenummer",
"."
] | python | train | 25.851852 |
ConsenSys/mythril-classic | mythril/ethereum/interface/leveldb/client.py | https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/ethereum/interface/leveldb/client.py#L273-L284 | def eth_getBlockByNumber(self, number):
"""Get block body by block number.
:param number:
:return:
"""
block_hash = self.reader._get_block_hash(number)
block_number = _format_block_number(number)
body_key = body_prefix + block_number + block_hash
block_da... | [
"def",
"eth_getBlockByNumber",
"(",
"self",
",",
"number",
")",
":",
"block_hash",
"=",
"self",
".",
"reader",
".",
"_get_block_hash",
"(",
"number",
")",
"block_number",
"=",
"_format_block_number",
"(",
"number",
")",
"body_key",
"=",
"body_prefix",
"+",
"bl... | Get block body by block number.
:param number:
:return: | [
"Get",
"block",
"body",
"by",
"block",
"number",
"."
] | python | train | 33.833333 |
sprockets/sprockets.clients.cassandra | sprockets/clients/cassandra/__init__.py | https://github.com/sprockets/sprockets.clients.cassandra/blob/c0a3ffe550ceb89b23a59959a0645d29d257e624/sprockets/clients/cassandra/__init__.py#L108-L119 | def execute(self, query, *args, **kwargs):
"""Asynchronously execute the specified CQL query.
The execute command also takes optional parameters and trace
keyword arguments. See cassandra-python documentation for
definition of those parameters.
"""
tornado_future = Futur... | [
"def",
"execute",
"(",
"self",
",",
"query",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tornado_future",
"=",
"Future",
"(",
")",
"cassandra_future",
"=",
"self",
".",
"_session",
".",
"execute_async",
"(",
"query",
",",
"*",
"args",
",",
... | Asynchronously execute the specified CQL query.
The execute command also takes optional parameters and trace
keyword arguments. See cassandra-python documentation for
definition of those parameters. | [
"Asynchronously",
"execute",
"the",
"specified",
"CQL",
"query",
"."
] | python | train | 43.166667 |
materialsproject/pymatgen | pymatgen/analysis/elasticity/elastic.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/elasticity/elastic.py#L684-L711 | def thermal_expansion_coeff(self, structure, temperature, mode="debye"):
"""
Gets thermal expansion coefficient from third-order constants.
Args:
temperature (float): Temperature in kelvin, if not specified
will return non-cv-normalized value
structure (S... | [
"def",
"thermal_expansion_coeff",
"(",
"self",
",",
"structure",
",",
"temperature",
",",
"mode",
"=",
"\"debye\"",
")",
":",
"soec",
"=",
"ElasticTensor",
"(",
"self",
"[",
"0",
"]",
")",
"v0",
"=",
"(",
"structure",
".",
"volume",
"*",
"1e-30",
"/",
... | Gets thermal expansion coefficient from third-order constants.
Args:
temperature (float): Temperature in kelvin, if not specified
will return non-cv-normalized value
structure (Structure): Structure to be used in directional heat
capacity determination, o... | [
"Gets",
"thermal",
"expansion",
"coefficient",
"from",
"third",
"-",
"order",
"constants",
"."
] | python | train | 46.535714 |
pschmitt/python-opsview | opsview/opsview.py | https://github.com/pschmitt/python-opsview/blob/720acc06c491db32d18c79d20f04cae16e57a7fb/opsview/opsview.py#L86-L91 | def api_version(self, verbose=False):
'''
Get information about the API
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#api_version_information
'''
return self.__auth_req_get(self.rest_url, verbose=verbose) | [
"def",
"api_version",
"(",
"self",
",",
"verbose",
"=",
"False",
")",
":",
"return",
"self",
".",
"__auth_req_get",
"(",
"self",
".",
"rest_url",
",",
"verbose",
"=",
"verbose",
")"
] | Get information about the API
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#api_version_information | [
"Get",
"information",
"about",
"the",
"API",
"http",
":",
"//",
"docs",
".",
"opsview",
".",
"com",
"/",
"doku",
".",
"php?id",
"=",
"opsview4",
".",
"6",
":",
"restapi#api_version_information"
] | python | train | 41.333333 |
mardix/Mocha | mocha/contrib/auth/decorators.py | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/decorators.py#L186-L200 | def accepts_contributor_roles(func):
"""
Decorator that accepts only contributor roles
:param func:
:return:
"""
if inspect.isclass(func):
apply_function_to_members(func, accepts_contributor_roles)
return func
else:
@functools.wraps(func)
def decorator(*args, ... | [
"def",
"accepts_contributor_roles",
"(",
"func",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"func",
")",
":",
"apply_function_to_members",
"(",
"func",
",",
"accepts_contributor_roles",
")",
"return",
"func",
"else",
":",
"@",
"functools",
".",
"wraps",
"... | Decorator that accepts only contributor roles
:param func:
:return: | [
"Decorator",
"that",
"accepts",
"only",
"contributor",
"roles",
":",
"param",
"func",
":",
":",
"return",
":"
] | python | train | 27.866667 |
eerimoq/bincopy | bincopy.py | https://github.com/eerimoq/bincopy/blob/5e02cd001c3e9b54729425db6bffad5f03e1beac/bincopy.py#L738-L752 | def add(self, data, overwrite=False):
"""Add given data string by guessing its format. The format must be
Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to
``True`` to allow already added data to be overwritten.
"""
if is_srec(data):
self.add_srec(data, ov... | [
"def",
"add",
"(",
"self",
",",
"data",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"is_srec",
"(",
"data",
")",
":",
"self",
".",
"add_srec",
"(",
"data",
",",
"overwrite",
")",
"elif",
"is_ihex",
"(",
"data",
")",
":",
"self",
".",
"add_ihex"... | Add given data string by guessing its format. The format must be
Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to
``True`` to allow already added data to be overwritten. | [
"Add",
"given",
"data",
"string",
"by",
"guessing",
"its",
"format",
".",
"The",
"format",
"must",
"be",
"Motorola",
"S",
"-",
"Records",
"Intel",
"HEX",
"or",
"TI",
"-",
"TXT",
".",
"Set",
"overwrite",
"to",
"True",
"to",
"allow",
"already",
"added",
... | python | train | 34.733333 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/wxhorizon_ui.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/wxhorizon_ui.py#L154-L160 | def calcFontScaling(self):
'''Calculates the current font size and left position for the current window.'''
self.ypx = self.figure.get_size_inches()[1]*self.figure.dpi
self.xpx = self.figure.get_size_inches()[0]*self.figure.dpi
self.fontSize = self.vertSize*(self.ypx/2.0)
self.le... | [
"def",
"calcFontScaling",
"(",
"self",
")",
":",
"self",
".",
"ypx",
"=",
"self",
".",
"figure",
".",
"get_size_inches",
"(",
")",
"[",
"1",
"]",
"*",
"self",
".",
"figure",
".",
"dpi",
"self",
".",
"xpx",
"=",
"self",
".",
"figure",
".",
"get_size... | Calculates the current font size and left position for the current window. | [
"Calculates",
"the",
"current",
"font",
"size",
"and",
"left",
"position",
"for",
"the",
"current",
"window",
"."
] | python | train | 56.142857 |
adrn/gala | gala/potential/frame/builtin/transformations.py | https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/frame/builtin/transformations.py#L31-L49 | def z_angle_rotate(xy, theta):
"""
Rotated the input vector or set of vectors `xy` by the angle `theta`.
Parameters
----------
xy : array_like
The vector or array of vectors to transform. Must have shape
"""
xy = np.array(xy).T
theta = np.array(theta).T
out = np.zeros_lik... | [
"def",
"z_angle_rotate",
"(",
"xy",
",",
"theta",
")",
":",
"xy",
"=",
"np",
".",
"array",
"(",
"xy",
")",
".",
"T",
"theta",
"=",
"np",
".",
"array",
"(",
"theta",
")",
".",
"T",
"out",
"=",
"np",
".",
"zeros_like",
"(",
"xy",
")",
"out",
"[... | Rotated the input vector or set of vectors `xy` by the angle `theta`.
Parameters
----------
xy : array_like
The vector or array of vectors to transform. Must have shape | [
"Rotated",
"the",
"input",
"vector",
"or",
"set",
"of",
"vectors",
"xy",
"by",
"the",
"angle",
"theta",
"."
] | python | train | 24.157895 |
exosite-labs/pyonep | pyonep/portals/__init__.py | https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L91-L111 | def get_portal_by_name(self, portal_name):
"""
Set active portal according to the name passed in 'portal_name'.
Returns dictionary of device 'serial_number: rid'
"""
portals = self.get_portals_list()
for p in portals:
# print("Checking {!r}".format(p... | [
"def",
"get_portal_by_name",
"(",
"self",
",",
"portal_name",
")",
":",
"portals",
"=",
"self",
".",
"get_portals_list",
"(",
")",
"for",
"p",
"in",
"portals",
":",
"# print(\"Checking {!r}\".format(p))",
"if",
"portal_name",
"==",
"p",
"[",
"1",
"]",
":",
"... | Set active portal according to the name passed in 'portal_name'.
Returns dictionary of device 'serial_number: rid' | [
"Set",
"active",
"portal",
"according",
"to",
"the",
"name",
"passed",
"in",
"portal_name",
"."
] | python | train | 41.095238 |
ejeschke/ginga | ginga/opengl/Camera.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/opengl/Camera.py#L155-L175 | def pan_delta(self, dx_px, dy_px):
"""
This causes the scene to appear to translate right and up
(i.e., what really happens is the camera is translated left and down).
This is also called "panning" in some software packages.
Passing in negative delta values causes the opposite mo... | [
"def",
"pan_delta",
"(",
"self",
",",
"dx_px",
",",
"dy_px",
")",
":",
"direction",
"=",
"self",
".",
"target",
"-",
"self",
".",
"position",
"distance_from_target",
"=",
"direction",
".",
"length",
"(",
")",
"direction",
"=",
"direction",
".",
"normalized... | This causes the scene to appear to translate right and up
(i.e., what really happens is the camera is translated left and down).
This is also called "panning" in some software packages.
Passing in negative delta values causes the opposite motion. | [
"This",
"causes",
"the",
"scene",
"to",
"appear",
"to",
"translate",
"right",
"and",
"up",
"(",
"i",
".",
"e",
".",
"what",
"really",
"happens",
"is",
"the",
"camera",
"is",
"translated",
"left",
"and",
"down",
")",
".",
"This",
"is",
"also",
"called",... | python | train | 40.428571 |
ansible/ansible-container | container/core.py | https://github.com/ansible/ansible-container/blob/d031c1a6133d5482a5d054fcbdbecafb923f8b4b/container/core.py#L371-L390 | def hostcmd_push(base_path, project_name, engine_name, vars_files=None, config_file=None, **kwargs):
"""
Push images to a registry. Requires authenticating with the registry prior to starting
the push. If your engine's config file does not already contain an authorization for the
registry, pass username... | [
"def",
"hostcmd_push",
"(",
"base_path",
",",
"project_name",
",",
"engine_name",
",",
"vars_files",
"=",
"None",
",",
"config_file",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert_initialized",
"(",
"base_path",
",",
"config_file",
")",
"config",
"... | Push images to a registry. Requires authenticating with the registry prior to starting
the push. If your engine's config file does not already contain an authorization for the
registry, pass username and/or password. If you exclude password, you will be prompted. | [
"Push",
"images",
"to",
"a",
"registry",
".",
"Requires",
"authenticating",
"with",
"the",
"registry",
"prior",
"to",
"starting",
"the",
"push",
".",
"If",
"your",
"engine",
"s",
"config",
"file",
"does",
"not",
"already",
"contain",
"an",
"authorization",
"... | python | train | 50.8 |
marrow/mailer | marrow/mailer/message.py | https://github.com/marrow/mailer/blob/3995ef98a3f7feb75f1aeb652e6afe40a5c94def/marrow/mailer/message.py#L209-L252 | def mime(self):
"""Produce the final MIME message."""
author = self.author
sender = self.sender
if not author:
raise ValueError("You must specify an author.")
if not self.subject:
raise ValueError("You must specify a subject.")
if len(self.recipients) == 0:
raise ValueError("You must specify a... | [
"def",
"mime",
"(",
"self",
")",
":",
"author",
"=",
"self",
".",
"author",
"sender",
"=",
"self",
".",
"sender",
"if",
"not",
"author",
":",
"raise",
"ValueError",
"(",
"\"You must specify an author.\"",
")",
"if",
"not",
"self",
".",
"subject",
":",
"r... | Produce the final MIME message. | [
"Produce",
"the",
"final",
"MIME",
"message",
"."
] | python | train | 26.636364 |
cni/MRS | MRS/utils.py | https://github.com/cni/MRS/blob/16098b3cf4830780efd787fee9efa46513850283/MRS/utils.py#L479-L490 | def two_lorentzian(freq, freq0_1, freq0_2, area1, area2, hwhm1, hwhm2, phase1,
phase2, offset, drift):
"""
A two-Lorentzian model.
This is simply the sum of two lorentzian functions in some part of the
spectrum. Each individual Lorentzian has its own peak frequency, area, hwhm
and pha... | [
"def",
"two_lorentzian",
"(",
"freq",
",",
"freq0_1",
",",
"freq0_2",
",",
"area1",
",",
"area2",
",",
"hwhm1",
",",
"hwhm2",
",",
"phase1",
",",
"phase2",
",",
"offset",
",",
"drift",
")",
":",
"return",
"(",
"lorentzian",
"(",
"freq",
",",
"freq0_1",... | A two-Lorentzian model.
This is simply the sum of two lorentzian functions in some part of the
spectrum. Each individual Lorentzian has its own peak frequency, area, hwhm
and phase, but they share common offset and drift parameters. | [
"A",
"two",
"-",
"Lorentzian",
"model",
"."
] | python | train | 43.75 |
pytroll/satpy | satpy/multiscene.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/multiscene.py#L258-L273 | def blend(self, blend_function=stack):
"""Blend the datasets into one scene.
.. note::
Blending is not currently optimized for generator-based
MultiScene.
"""
new_scn = Scene()
common_datasets = self.shared_dataset_ids
for ds_id in common_datase... | [
"def",
"blend",
"(",
"self",
",",
"blend_function",
"=",
"stack",
")",
":",
"new_scn",
"=",
"Scene",
"(",
")",
"common_datasets",
"=",
"self",
".",
"shared_dataset_ids",
"for",
"ds_id",
"in",
"common_datasets",
":",
"datasets",
"=",
"[",
"scn",
"[",
"ds_id... | Blend the datasets into one scene.
.. note::
Blending is not currently optimized for generator-based
MultiScene. | [
"Blend",
"the",
"datasets",
"into",
"one",
"scene",
"."
] | python | train | 28.8125 |
Erotemic/ubelt | ubelt/util_import.py | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_import.py#L430-L479 | def normalize_modpath(modpath, hide_init=True, hide_main=False):
"""
Normalizes __init__ and __main__ paths.
Notes:
Adds __init__ if reasonable, but only removes __main__ by default
Args:
hide_init (bool): if True, always return package modules
as __init__.py files otherwise... | [
"def",
"normalize_modpath",
"(",
"modpath",
",",
"hide_init",
"=",
"True",
",",
"hide_main",
"=",
"False",
")",
":",
"if",
"six",
".",
"PY2",
":",
"if",
"modpath",
".",
"endswith",
"(",
"'.pyc'",
")",
":",
"modpath",
"=",
"modpath",
"[",
":",
"-",
"1... | Normalizes __init__ and __main__ paths.
Notes:
Adds __init__ if reasonable, but only removes __main__ by default
Args:
hide_init (bool): if True, always return package modules
as __init__.py files otherwise always return the dpath.
hide_init (bool): if True, always strip awa... | [
"Normalizes",
"__init__",
"and",
"__main__",
"paths",
"."
] | python | valid | 39.4 |
earwig/mwparserfromhell | mwparserfromhell/wikicode.py | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/wikicode.py#L70-L74 | def _slice_replace(code, index, old, new):
"""Replace the string *old* with *new* across *index* in *code*."""
nodes = [str(node) for node in code.get(index)]
substring = "".join(nodes).replace(old, new)
code.nodes[index] = parse_anything(substring).nodes | [
"def",
"_slice_replace",
"(",
"code",
",",
"index",
",",
"old",
",",
"new",
")",
":",
"nodes",
"=",
"[",
"str",
"(",
"node",
")",
"for",
"node",
"in",
"code",
".",
"get",
"(",
"index",
")",
"]",
"substring",
"=",
"\"\"",
".",
"join",
"(",
"nodes"... | Replace the string *old* with *new* across *index* in *code*. | [
"Replace",
"the",
"string",
"*",
"old",
"*",
"with",
"*",
"new",
"*",
"across",
"*",
"index",
"*",
"in",
"*",
"code",
"*",
"."
] | python | train | 56.6 |
APSL/transmanager | transmanager/manager.py | https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/manager.py#L306-L318 | def get_languages_from_item(ct_item, item):
"""
Get the languages configured for the current item
:param ct_item:
:param item:
:return:
"""
try:
item_lan = TransItemLanguage.objects.filter(content_type__pk=ct_item.id, object_id=item.id).get()
... | [
"def",
"get_languages_from_item",
"(",
"ct_item",
",",
"item",
")",
":",
"try",
":",
"item_lan",
"=",
"TransItemLanguage",
".",
"objects",
".",
"filter",
"(",
"content_type__pk",
"=",
"ct_item",
".",
"id",
",",
"object_id",
"=",
"item",
".",
"id",
")",
"."... | Get the languages configured for the current item
:param ct_item:
:param item:
:return: | [
"Get",
"the",
"languages",
"configured",
"for",
"the",
"current",
"item",
":",
"param",
"ct_item",
":",
":",
"param",
"item",
":",
":",
"return",
":"
] | python | train | 36.076923 |
zblz/naima | naima/plot.py | https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L741-L782 | def plot_blob(
sampler, blobidx=0, label=None, last_step=False, figure=None, **kwargs
):
"""
Plot a metadata blob as a fit to spectral data or value distribution
Additional ``kwargs`` are passed to `plot_fit`.
Parameters
----------
sampler : `emcee.EnsembleSampler`
Sampler with a s... | [
"def",
"plot_blob",
"(",
"sampler",
",",
"blobidx",
"=",
"0",
",",
"label",
"=",
"None",
",",
"last_step",
"=",
"False",
",",
"figure",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"modelx",
",",
"model",
"=",
"_process_blob",
"(",
"sampler",
",",... | Plot a metadata blob as a fit to spectral data or value distribution
Additional ``kwargs`` are passed to `plot_fit`.
Parameters
----------
sampler : `emcee.EnsembleSampler`
Sampler with a stored chain.
blobidx : int, optional
Metadata blob index to plot.
label : str, optional
... | [
"Plot",
"a",
"metadata",
"blob",
"as",
"a",
"fit",
"to",
"spectral",
"data",
"or",
"value",
"distribution"
] | python | train | 27.166667 |
python-visualization/folium | folium/features.py | https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L725-L736 | def style_data(self):
"""Applies self.style_function to each feature of self.data."""
def recursive_get(data, keys):
if len(keys):
return recursive_get(data.get(keys[0]), keys[1:])
else:
return data
geometries = recursive_get(self.data, s... | [
"def",
"style_data",
"(",
"self",
")",
":",
"def",
"recursive_get",
"(",
"data",
",",
"keys",
")",
":",
"if",
"len",
"(",
"keys",
")",
":",
"return",
"recursive_get",
"(",
"data",
".",
"get",
"(",
"keys",
"[",
"0",
"]",
")",
",",
"keys",
"[",
"1"... | Applies self.style_function to each feature of self.data. | [
"Applies",
"self",
".",
"style_function",
"to",
"each",
"feature",
"of",
"self",
".",
"data",
"."
] | python | train | 41.916667 |
bharadwajyarlagadda/bingmaps | bingmaps/urls/elevations_build_urls.py | https://github.com/bharadwajyarlagadda/bingmaps/blob/6bb3cdadfb121aaff96704509cedff2710a62b6d/bingmaps/urls/elevations_build_urls.py#L285-L309 | def build_query_string(self, data):
"""This method occurs after dumping the data into the class.
Args:
data (dict): dictionary of all the query values
Returns:
data (dict): ordered dict of all the values
"""
query = []
keys_to_be_removed = []
... | [
"def",
"build_query_string",
"(",
"self",
",",
"data",
")",
":",
"query",
"=",
"[",
"]",
"keys_to_be_removed",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"[",
"'version'",
",",
"'... | This method occurs after dumping the data into the class.
Args:
data (dict): dictionary of all the query values
Returns:
data (dict): ordered dict of all the values | [
"This",
"method",
"occurs",
"after",
"dumping",
"the",
"data",
"into",
"the",
"class",
"."
] | python | train | 38.48 |
the01/python-paps | paps/person.py | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/person.py#L103-L118 | def from_bits(self, bits):
"""
Set this person from bits (ignores the id)
:param bits: Bits representing a person
:type bits: bytearray
:rtype: Person
:raises ValueError: Bits has an unexpected length
"""
# TODO include id
if len(bits) != Person.B... | [
"def",
"from_bits",
"(",
"self",
",",
"bits",
")",
":",
"# TODO include id",
"if",
"len",
"(",
"bits",
")",
"!=",
"Person",
".",
"BITS_PER_PERSON",
":",
"raise",
"ValueError",
"(",
"u\"Person requires exactly {} bits\"",
".",
"format",
"(",
"Person",
".",
"BIT... | Set this person from bits (ignores the id)
:param bits: Bits representing a person
:type bits: bytearray
:rtype: Person
:raises ValueError: Bits has an unexpected length | [
"Set",
"this",
"person",
"from",
"bits",
"(",
"ignores",
"the",
"id",
")"
] | python | train | 31.4375 |
apple/turicreate | src/unity/python/turicreate/toolkits/style_transfer/style_transfer.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/style_transfer/style_transfer.py#L35-L402 | def create(style_dataset, content_dataset, style_feature=None,
content_feature=None, max_iterations=None, model='resnet-16',
verbose=True, batch_size = 6, **kwargs):
"""
Create a :class:`StyleTransfer` model.
Parameters
----------
style_dataset: SFrame
Input style images. Th... | [
"def",
"create",
"(",
"style_dataset",
",",
"content_dataset",
",",
"style_feature",
"=",
"None",
",",
"content_feature",
"=",
"None",
",",
"max_iterations",
"=",
"None",
",",
"model",
"=",
"'resnet-16'",
",",
"verbose",
"=",
"True",
",",
"batch_size",
"=",
... | Create a :class:`StyleTransfer` model.
Parameters
----------
style_dataset: SFrame
Input style images. The columns named by the ``style_feature`` parameters will
be extracted for training the model.
content_dataset : SFrame
Input content images. The columns named by the ``conte... | [
"Create",
"a",
":",
"class",
":",
"StyleTransfer",
"model",
"."
] | python | train | 39.059783 |
pyca/pyopenssl | src/OpenSSL/SSL.py | https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/SSL.py#L931-L943 | def use_certificate(self, cert):
"""
Load a certificate from a X509 object
:param cert: The X509 object
:return: None
"""
if not isinstance(cert, X509):
raise TypeError("cert must be an X509 instance")
use_result = _lib.SSL_CTX_use_certificate(self._... | [
"def",
"use_certificate",
"(",
"self",
",",
"cert",
")",
":",
"if",
"not",
"isinstance",
"(",
"cert",
",",
"X509",
")",
":",
"raise",
"TypeError",
"(",
"\"cert must be an X509 instance\"",
")",
"use_result",
"=",
"_lib",
".",
"SSL_CTX_use_certificate",
"(",
"s... | Load a certificate from a X509 object
:param cert: The X509 object
:return: None | [
"Load",
"a",
"certificate",
"from",
"a",
"X509",
"object"
] | python | test | 30 |
peri-source/peri | peri/viz/plots.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/viz/plots.py#L1056-L1103 | def circles(st, layer, axis, ax=None, talpha=1.0, cedge='white', cface='white'):
"""
Plots a set of circles corresponding to a slice through the platonic
structure. Copied from twoslice_overlay with comments, standaloneness.
Inputs
------
pos : array of particle positions; [N,3]
rad... | [
"def",
"circles",
"(",
"st",
",",
"layer",
",",
"axis",
",",
"ax",
"=",
"None",
",",
"talpha",
"=",
"1.0",
",",
"cedge",
"=",
"'white'",
",",
"cface",
"=",
"'white'",
")",
":",
"pos",
"=",
"st",
".",
"obj_get_positions",
"(",
")",
"rad",
"=",
"st... | Plots a set of circles corresponding to a slice through the platonic
structure. Copied from twoslice_overlay with comments, standaloneness.
Inputs
------
pos : array of particle positions; [N,3]
rad : array of particle radii; [N]
ax : plt.axis instance
layer : Which layer of... | [
"Plots",
"a",
"set",
"of",
"circles",
"corresponding",
"to",
"a",
"slice",
"through",
"the",
"platonic",
"structure",
".",
"Copied",
"from",
"twoslice_overlay",
"with",
"comments",
"standaloneness",
"."
] | python | valid | 36.5625 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L753-L794 | def visit_exact_match_value(self, node, fieldnames=None):
"""Generates a term query (exact search in ElasticSearch)."""
if not fieldnames:
fieldnames = ['_all']
else:
fieldnames = force_list(fieldnames)
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['exact-autho... | [
"def",
"visit_exact_match_value",
"(",
"self",
",",
"node",
",",
"fieldnames",
"=",
"None",
")",
":",
"if",
"not",
"fieldnames",
":",
"fieldnames",
"=",
"[",
"'_all'",
"]",
"else",
":",
"fieldnames",
"=",
"force_list",
"(",
"fieldnames",
")",
"if",
"Elasti... | Generates a term query (exact search in ElasticSearch). | [
"Generates",
"a",
"term",
"query",
"(",
"exact",
"search",
"in",
"ElasticSearch",
")",
"."
] | python | train | 46.333333 |
faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L352-L356 | def _handleDelete(self):
""" Handles "delete" characters """
if self.cursorPos < len(self.inputBuffer):
self.inputBuffer = self.inputBuffer[0:self.cursorPos] + self.inputBuffer[self.cursorPos+1:]
self._refreshInputPrompt(len(self.inputBuffer)+1) | [
"def",
"_handleDelete",
"(",
"self",
")",
":",
"if",
"self",
".",
"cursorPos",
"<",
"len",
"(",
"self",
".",
"inputBuffer",
")",
":",
"self",
".",
"inputBuffer",
"=",
"self",
".",
"inputBuffer",
"[",
"0",
":",
"self",
".",
"cursorPos",
"]",
"+",
"sel... | Handles "delete" characters | [
"Handles",
"delete",
"characters"
] | python | train | 61 |
deepmipt/DeepPavlov | deeppavlov/utils/alexa/ssl_tools.py | https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alexa/ssl_tools.py#L29-L58 | def verify_sc_url(url: str) -> bool:
"""Verify signature certificate URL against Amazon Alexa requirements.
Each call of Agent passes incoming utterances batch through skills filter,
agent skills, skills processor. Batch of dialog IDs can be provided, in
other case utterances indexes in incoming batch ... | [
"def",
"verify_sc_url",
"(",
"url",
":",
"str",
")",
"->",
"bool",
":",
"parsed",
"=",
"urlsplit",
"(",
"url",
")",
"scheme",
":",
"str",
"=",
"parsed",
".",
"scheme",
"netloc",
":",
"str",
"=",
"parsed",
".",
"netloc",
"path",
":",
"str",
"=",
"pa... | Verify signature certificate URL against Amazon Alexa requirements.
Each call of Agent passes incoming utterances batch through skills filter,
agent skills, skills processor. Batch of dialog IDs can be provided, in
other case utterances indexes in incoming batch are used as dialog IDs.
Args:
u... | [
"Verify",
"signature",
"certificate",
"URL",
"against",
"Amazon",
"Alexa",
"requirements",
"."
] | python | test | 30.633333 |
EmbodiedCognition/py-c3d | c3d.py | https://github.com/EmbodiedCognition/py-c3d/blob/391493d9cb4c6b4aaeee4de2930685e3a67f5845/c3d.py#L1023-L1094 | def write(self, handle):
'''Write metadata and point + analog frames to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
if not self._frames... | [
"def",
"write",
"(",
"self",
",",
"handle",
")",
":",
"if",
"not",
"self",
".",
"_frames",
":",
"return",
"def",
"add",
"(",
"name",
",",
"desc",
",",
"bpe",
",",
"format",
",",
"bytes",
",",
"*",
"dimensions",
")",
":",
"group",
".",
"add_param",
... | Write metadata and point + analog frames to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle. | [
"Write",
"metadata",
"and",
"point",
"+",
"analog",
"frames",
"to",
"a",
"file",
"handle",
"."
] | python | train | 43.333333 |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L4006-L4096 | def sort_values(self, by=None, axis=0, ascending=True, inplace=False,
kind='quicksort', na_position='last'):
"""
Sort by the values along either axis.
Parameters
----------%(optional_by)s
axis : %(axes_single_arg)s, default 0
Axis to be sorted.
... | [
"def",
"sort_values",
"(",
"self",
",",
"by",
"=",
"None",
",",
"axis",
"=",
"0",
",",
"ascending",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"kind",
"=",
"'quicksort'",
",",
"na_position",
"=",
"'last'",
")",
":",
"raise",
"NotImplementedError",
... | Sort by the values along either axis.
Parameters
----------%(optional_by)s
axis : %(axes_single_arg)s, default 0
Axis to be sorted.
ascending : bool or list of bool, default True
Sort ascending vs. descending. Specify list for multiple sort
orders.... | [
"Sort",
"by",
"the",
"values",
"along",
"either",
"axis",
"."
] | python | train | 30.252747 |
mottosso/be | be/vendor/requests/sessions.py | https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/sessions.py#L538-L615 | def send(self, request, **kwargs):
"""Send a given PreparedRequest."""
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.verify... | [
"def",
"send",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set defaults that the hooks can utilize to ensure they always have",
"# the correct parameters to reproduce the previous request.",
"kwargs",
".",
"setdefault",
"(",
"'stream'",
",",
"self",
"... | Send a given PreparedRequest. | [
"Send",
"a",
"given",
"PreparedRequest",
"."
] | python | train | 34.089744 |
jaraco/jaraco.itertools | jaraco/itertools.py | https://github.com/jaraco/jaraco.itertools/blob/0dc47c8924fa3d9ab676c3a6e195f03f728b72c6/jaraco/itertools.py#L379-L401 | def grouper_nofill_str(n, iterable):
"""
Take a sequence and break it up into chunks of the specified size.
The last chunk may be smaller than size.
This works very similar to grouper_nofill, except
it works with strings as well.
>>> tuple(grouper_nofill_str(3, 'foobarbaz'))
('foo', 'bar', 'baz')
You can sti... | [
"def",
"grouper_nofill_str",
"(",
"n",
",",
"iterable",
")",
":",
"res",
"=",
"more_itertools",
".",
"chunked",
"(",
"iterable",
",",
"n",
")",
"if",
"isinstance",
"(",
"iterable",
",",
"six",
".",
"string_types",
")",
":",
"res",
"=",
"(",
"''",
".",
... | Take a sequence and break it up into chunks of the specified size.
The last chunk may be smaller than size.
This works very similar to grouper_nofill, except
it works with strings as well.
>>> tuple(grouper_nofill_str(3, 'foobarbaz'))
('foo', 'bar', 'baz')
You can still use it on non-strings too if you like.
... | [
"Take",
"a",
"sequence",
"and",
"break",
"it",
"up",
"into",
"chunks",
"of",
"the",
"specified",
"size",
".",
"The",
"last",
"chunk",
"may",
"be",
"smaller",
"than",
"size",
"."
] | python | test | 26.913043 |
GoogleCloudPlatform/compute-image-packages | packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py | https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py#L262-L282 | def GetForwardedIps(self, interface, interface_ip=None):
"""Retrieve the list of configured forwarded IP addresses.
Args:
interface: string, the output device to query.
interface_ip: string, current interface ip address.
Returns:
list, the IP address strings.
"""
try:
ips =... | [
"def",
"GetForwardedIps",
"(",
"self",
",",
"interface",
",",
"interface_ip",
"=",
"None",
")",
":",
"try",
":",
"ips",
"=",
"netifaces",
".",
"ifaddresses",
"(",
"interface",
")",
"ips",
"=",
"ips",
"[",
"netifaces",
".",
"AF_INET",
"]",
"except",
"(",
... | Retrieve the list of configured forwarded IP addresses.
Args:
interface: string, the output device to query.
interface_ip: string, current interface ip address.
Returns:
list, the IP address strings. | [
"Retrieve",
"the",
"list",
"of",
"configured",
"forwarded",
"IP",
"addresses",
"."
] | python | train | 32.428571 |
CodeReclaimers/neat-python | examples/xor/evolve-feedforward-parallel.py | https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/examples/xor/evolve-feedforward-parallel.py#L32-L50 | def eval_genome(genome, config):
"""
This function will be run in parallel by ParallelEvaluator. It takes two
arguments (a single genome and the genome class configuration data) and
should return one float (that genome's fitness).
Note that this function needs to be in module scope for multiproces... | [
"def",
"eval_genome",
"(",
"genome",
",",
"config",
")",
":",
"net",
"=",
"neat",
".",
"nn",
".",
"FeedForwardNetwork",
".",
"create",
"(",
"genome",
",",
"config",
")",
"error",
"=",
"4.0",
"for",
"xi",
",",
"xo",
"in",
"zip",
"(",
"xor_inputs",
","... | This function will be run in parallel by ParallelEvaluator. It takes two
arguments (a single genome and the genome class configuration data) and
should return one float (that genome's fitness).
Note that this function needs to be in module scope for multiprocessing.Pool
(which is what ParallelEvaluato... | [
"This",
"function",
"will",
"be",
"run",
"in",
"parallel",
"by",
"ParallelEvaluator",
".",
"It",
"takes",
"two",
"arguments",
"(",
"a",
"single",
"genome",
"and",
"the",
"genome",
"class",
"configuration",
"data",
")",
"and",
"should",
"return",
"one",
"floa... | python | train | 42.526316 |
apache/incubator-mxnet | python/mxnet/contrib/quantization.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/quantization.py#L422-L544 | def quantize_model(sym, arg_params, aux_params,
data_names=('data',), label_names=('softmax_label',),
ctx=cpu(), excluded_sym_names=None, calib_mode='entropy',
calib_data=None, num_calib_examples=None, calib_layer=None,
quantized_dtype='int8', ... | [
"def",
"quantize_model",
"(",
"sym",
",",
"arg_params",
",",
"aux_params",
",",
"data_names",
"=",
"(",
"'data'",
",",
")",
",",
"label_names",
"=",
"(",
"'softmax_label'",
",",
")",
",",
"ctx",
"=",
"cpu",
"(",
")",
",",
"excluded_sym_names",
"=",
"None... | User-level API for generating a quantized model from a FP32 model w/ or w/o calibration.
The backend quantized operators are only enabled for Linux systems. Please do not run
inference using the quantized models on Windows for now.
The quantization implementation adopts the TensorFlow's approach:
https:... | [
"User",
"-",
"level",
"API",
"for",
"generating",
"a",
"quantized",
"model",
"from",
"a",
"FP32",
"model",
"w",
"/",
"or",
"w",
"/",
"o",
"calibration",
".",
"The",
"backend",
"quantized",
"operators",
"are",
"only",
"enabled",
"for",
"Linux",
"systems",
... | python | train | 55.98374 |
idlesign/django-dev | django_dev/dev.py | https://github.com/idlesign/django-dev/blob/e21725a8f2e880d3d246656e0dc19df5dbbf572f/django_dev/dev.py#L162-L176 | def make_venv(self, dj_version):
"""Creates a virtual environment for a given Django version.
:param str dj_version:
:rtype: str
:return: path to created virtual env
"""
venv_path = self._get_venv_path(dj_version)
self.logger.info('Creating virtual environment fo... | [
"def",
"make_venv",
"(",
"self",
",",
"dj_version",
")",
":",
"venv_path",
"=",
"self",
".",
"_get_venv_path",
"(",
"dj_version",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'Creating virtual environment for Django %s ...'",
"%",
"dj_version",
")",
"try",
":"... | Creates a virtual environment for a given Django version.
:param str dj_version:
:rtype: str
:return: path to created virtual env | [
"Creates",
"a",
"virtual",
"environment",
"for",
"a",
"given",
"Django",
"version",
"."
] | python | train | 40.8 |
RedHatInsights/insights-core | insights/contrib/importlib.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/importlib.py#L6-L17 | def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
if not hasattr(package, 'rindex'):
raise ValueError("'package' not set to a string")
dot = len(package)
for x in xrange(level, 1, -1):
try:
dot = package.rindex('.', 0, dot)
... | [
"def",
"_resolve_name",
"(",
"name",
",",
"package",
",",
"level",
")",
":",
"if",
"not",
"hasattr",
"(",
"package",
",",
"'rindex'",
")",
":",
"raise",
"ValueError",
"(",
"\"'package' not set to a string\"",
")",
"dot",
"=",
"len",
"(",
"package",
")",
"f... | Return the absolute name of the module to be imported. | [
"Return",
"the",
"absolute",
"name",
"of",
"the",
"module",
"to",
"be",
"imported",
"."
] | python | train | 41.166667 |
todbot/blink1-python | blink1/blink1.py | https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L274-L282 | def readPattern(self):
"""Read the entire color pattern
:return List of pattern line tuples
"""
if ( self.dev == None ): return ''
pattern=[]
for i in range(0,16): # FIXME: adjustable for diff blink(1) models
pattern.append( self.readPatternLine(i) )
... | [
"def",
"readPattern",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"dev",
"==",
"None",
")",
":",
"return",
"''",
"pattern",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"16",
")",
":",
"# FIXME: adjustable for diff blink(1) models",
"pat... | Read the entire color pattern
:return List of pattern line tuples | [
"Read",
"the",
"entire",
"color",
"pattern",
":",
"return",
"List",
"of",
"pattern",
"line",
"tuples"
] | python | train | 36.444444 |
abseil/abseil-py | absl/flags/_validators.py | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_validators.py#L387-L421 | def mark_flags_as_mutual_exclusive(flag_names, required=False,
flag_values=_flagvalues.FLAGS):
"""Ensures that only one flag among flag_names is not None.
Important note: This validator checks if flag values are None, and it does not
distinguish between default and explicit val... | [
"def",
"mark_flags_as_mutual_exclusive",
"(",
"flag_names",
",",
"required",
"=",
"False",
",",
"flag_values",
"=",
"_flagvalues",
".",
"FLAGS",
")",
":",
"for",
"flag_name",
"in",
"flag_names",
":",
"if",
"flag_values",
"[",
"flag_name",
"]",
".",
"default",
... | Ensures that only one flag among flag_names is not None.
Important note: This validator checks if flag values are None, and it does not
distinguish between default and explicit values. Therefore, this validator
does not make sense when applied to flags with default values other than None,
including other false... | [
"Ensures",
"that",
"only",
"one",
"flag",
"among",
"flag_names",
"is",
"not",
"None",
"."
] | python | train | 49.257143 |
reincubate/ricloud | ricloud/asmaster_api.py | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L59-L66 | def _set_allowed_services_and_actions(self, services):
"""Expect services to be a list of service dictionaries, each with `name` and `actions` keys."""
for service in services:
self.services[service['name']] = {}
for action in service['actions']:
name = action.po... | [
"def",
"_set_allowed_services_and_actions",
"(",
"self",
",",
"services",
")",
":",
"for",
"service",
"in",
"services",
":",
"self",
".",
"services",
"[",
"service",
"[",
"'name'",
"]",
"]",
"=",
"{",
"}",
"for",
"action",
"in",
"service",
"[",
"'actions'"... | Expect services to be a list of service dictionaries, each with `name` and `actions` keys. | [
"Expect",
"services",
"to",
"be",
"a",
"list",
"of",
"service",
"dictionaries",
"each",
"with",
"name",
"and",
"actions",
"keys",
"."
] | python | train | 48 |
readbeyond/aeneas | aeneas/textfile.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L879-L896 | def _read_parsed(self, lines):
"""
Read text fragments from a parsed format text file.
:param list lines: the lines of the parsed text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings)
"""
self.l... | [
"def",
"_read_parsed",
"(",
"self",
",",
"lines",
")",
":",
"self",
".",
"log",
"(",
"u\"Parsing fragments from parsed text format\"",
")",
"pairs",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"pieces",
"=",
"line",
".",
"split",
"(",
"gc",
".",
"P... | Read text fragments from a parsed format text file.
:param list lines: the lines of the parsed text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings) | [
"Read",
"text",
"fragments",
"from",
"a",
"parsed",
"format",
"text",
"file",
"."
] | python | train | 39.666667 |
wesyoung/pyzyre | czmq/_czmq_ctypes.py | https://github.com/wesyoung/pyzyre/blob/22d4c757acefcfdb700d3802adaf30b402bb9eea/czmq/_czmq_ctypes.py#L4588-L4594 | def addmsg(self, msg_p):
"""
Push encoded message as a new frame. Message takes ownership of
submessage, so the original is destroyed in this call. Returns 0 on
success, -1 on error.
"""
return lib.zmsg_addmsg(self._as_parameter_, byref(zmsg_p.from_param(msg_p))) | [
"def",
"addmsg",
"(",
"self",
",",
"msg_p",
")",
":",
"return",
"lib",
".",
"zmsg_addmsg",
"(",
"self",
".",
"_as_parameter_",
",",
"byref",
"(",
"zmsg_p",
".",
"from_param",
"(",
"msg_p",
")",
")",
")"
] | Push encoded message as a new frame. Message takes ownership of
submessage, so the original is destroyed in this call. Returns 0 on
success, -1 on error. | [
"Push",
"encoded",
"message",
"as",
"a",
"new",
"frame",
".",
"Message",
"takes",
"ownership",
"of",
"submessage",
"so",
"the",
"original",
"is",
"destroyed",
"in",
"this",
"call",
".",
"Returns",
"0",
"on",
"success",
"-",
"1",
"on",
"error",
"."
] | python | train | 41.285714 |
trailofbits/manticore | manticore/platforms/linux.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2262-L2273 | def check_timers(self):
""" Awake process if timer has expired """
if self._current is None:
# Advance the clocks. Go to future!!
advance = min([self.clocks] + [x for x in self.timers if x is not None]) + 1
logger.debug(f"Advancing the clock from {self.clocks} to {adv... | [
"def",
"check_timers",
"(",
"self",
")",
":",
"if",
"self",
".",
"_current",
"is",
"None",
":",
"# Advance the clocks. Go to future!!",
"advance",
"=",
"min",
"(",
"[",
"self",
".",
"clocks",
"]",
"+",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"timers",
... | Awake process if timer has expired | [
"Awake",
"process",
"if",
"timer",
"has",
"expired"
] | python | valid | 51.583333 |
bbusenius/Diablo-Python | simple_math/simple_math.py | https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/simple_math/simple_math.py#L190-L218 | def triangle_area(point1, point2, point3):
"""
Uses Heron's formula to find the area of a triangle
based on the coordinates of three points.
Args:
point1: list or tuple, the x y coordinate of point one.
point2: list or tuple, the x y coordinate of point two.
point3: list or tu... | [
"def",
"triangle_area",
"(",
"point1",
",",
"point2",
",",
"point3",
")",
":",
"\"\"\"Lengths of the three sides of the triangle\"\"\"",
"a",
"=",
"point_distance",
"(",
"point1",
",",
"point2",
")",
"b",
"=",
"point_distance",
"(",
"point1",
",",
"point3",
")",
... | Uses Heron's formula to find the area of a triangle
based on the coordinates of three points.
Args:
point1: list or tuple, the x y coordinate of point one.
point2: list or tuple, the x y coordinate of point two.
point3: list or tuple, the x y coordinate of point three.
Returns:
... | [
"Uses",
"Heron",
"s",
"formula",
"to",
"find",
"the",
"area",
"of",
"a",
"triangle",
"based",
"on",
"the",
"coordinates",
"of",
"three",
"points",
"."
] | python | valid | 28.551724 |
saltstack/salt | salt/modules/boto_cognitoidentity.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cognitoidentity.py#L289-L299 | def _get_role_arn(name, **conn_params):
'''
Helper function to turn a name into an arn string,
returns None if not able to resolve
'''
if name.startswith('arn:aws:iam'):
return name
role = __salt__['boto_iam.describe_role'](name, **conn_params)
rolearn = role.get('arn') if role else ... | [
"def",
"_get_role_arn",
"(",
"name",
",",
"*",
"*",
"conn_params",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'arn:aws:iam'",
")",
":",
"return",
"name",
"role",
"=",
"__salt__",
"[",
"'boto_iam.describe_role'",
"]",
"(",
"name",
",",
"*",
"*",
"co... | Helper function to turn a name into an arn string,
returns None if not able to resolve | [
"Helper",
"function",
"to",
"turn",
"a",
"name",
"into",
"an",
"arn",
"string",
"returns",
"None",
"if",
"not",
"able",
"to",
"resolve"
] | python | train | 30.363636 |
ulfalizer/Kconfiglib | examples/print_config_tree.py | https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/examples/print_config_tree.py#L70-L101 | def value_str(sc):
"""
Returns the value part ("[*]", "<M>", "(foo)" etc.) of a menu entry.
sc: Symbol or Choice.
"""
if sc.type in (STRING, INT, HEX):
return "({})".format(sc.str_value)
# BOOL or TRISTATE
# The choice mode is an upper bound on the visibility of choice symbols, so... | [
"def",
"value_str",
"(",
"sc",
")",
":",
"if",
"sc",
".",
"type",
"in",
"(",
"STRING",
",",
"INT",
",",
"HEX",
")",
":",
"return",
"\"({})\"",
".",
"format",
"(",
"sc",
".",
"str_value",
")",
"# BOOL or TRISTATE",
"# The choice mode is an upper bound on the ... | Returns the value part ("[*]", "<M>", "(foo)" etc.) of a menu entry.
sc: Symbol or Choice. | [
"Returns",
"the",
"value",
"part",
"(",
"[",
"*",
"]",
"<M",
">",
"(",
"foo",
")",
"etc",
".",
")",
"of",
"a",
"menu",
"entry",
"."
] | python | train | 32.25 |
ianmiell/shutit | shutit_class.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L3067-L3128 | def load_mod_from_file(self, fpath):
"""Loads modules from a .py file into ShutIt if there are no modules from
this file already.
We expect to have a callable 'module/0' which returns one or more module
objects.
If this doesn't exist we assume that the .py file works in the old style
(automatically insertin... | [
"def",
"load_mod_from_file",
"(",
"self",
",",
"fpath",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"fpath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"fpath",
")",
"file_ext",
"=",
"os",
".",
"path",
".",
"... | Loads modules from a .py file into ShutIt if there are no modules from
this file already.
We expect to have a callable 'module/0' which returns one or more module
objects.
If this doesn't exist we assume that the .py file works in the old style
(automatically inserting the module into shutit_global) or it's n... | [
"Loads",
"modules",
"from",
"a",
".",
"py",
"file",
"into",
"ShutIt",
"if",
"there",
"are",
"no",
"modules",
"from",
"this",
"file",
"already",
".",
"We",
"expect",
"to",
"have",
"a",
"callable",
"module",
"/",
"0",
"which",
"returns",
"one",
"or",
"mo... | python | train | 36.645161 |
jeremylow/pyshk | pyshk/models.py | https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/models.py#L90-L111 | def NewFromJSON(data):
"""
Create a new User instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a user.
Returns:
A User instance.
"""
if data.get('shakes', None):
shakes = [Shake.NewFromJSON(shk) for shk in dat... | [
"def",
"NewFromJSON",
"(",
"data",
")",
":",
"if",
"data",
".",
"get",
"(",
"'shakes'",
",",
"None",
")",
":",
"shakes",
"=",
"[",
"Shake",
".",
"NewFromJSON",
"(",
"shk",
")",
"for",
"shk",
"in",
"data",
".",
"get",
"(",
"'shakes'",
")",
"]",
"e... | Create a new User instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a user.
Returns:
A User instance. | [
"Create",
"a",
"new",
"User",
"instance",
"from",
"a",
"JSON",
"dict",
"."
] | python | train | 29.045455 |
apache/incubator-mxnet | python/mxnet/image/detection.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/detection.py#L702-L714 | def _estimate_label_shape(self):
"""Helper function to estimate label shape"""
max_count = 0
self.reset()
try:
while True:
label, _ = self.next_sample()
label = self._parse_label(label)
max_count = max(max_count, label.shape[0])... | [
"def",
"_estimate_label_shape",
"(",
"self",
")",
":",
"max_count",
"=",
"0",
"self",
".",
"reset",
"(",
")",
"try",
":",
"while",
"True",
":",
"label",
",",
"_",
"=",
"self",
".",
"next_sample",
"(",
")",
"label",
"=",
"self",
".",
"_parse_label",
"... | Helper function to estimate label shape | [
"Helper",
"function",
"to",
"estimate",
"label",
"shape"
] | python | train | 32.230769 |
pytroll/trollimage | trollimage/xrimage.py | https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/xrimage.py#L885-L894 | def stretch_weber_fechner(self, k, s0):
"""Stretch according to the Weber-Fechner law.
p = k.ln(S/S0)
p is perception, S is the stimulus, S0 is the stimulus threshold (the
highest unpercieved stimulus), and k is the factor.
"""
attrs = self.data.attrs
self.data =... | [
"def",
"stretch_weber_fechner",
"(",
"self",
",",
"k",
",",
"s0",
")",
":",
"attrs",
"=",
"self",
".",
"data",
".",
"attrs",
"self",
".",
"data",
"=",
"k",
"*",
"xu",
".",
"log",
"(",
"self",
".",
"data",
"/",
"s0",
")",
"self",
".",
"data",
".... | Stretch according to the Weber-Fechner law.
p = k.ln(S/S0)
p is perception, S is the stimulus, S0 is the stimulus threshold (the
highest unpercieved stimulus), and k is the factor. | [
"Stretch",
"according",
"to",
"the",
"Weber",
"-",
"Fechner",
"law",
"."
] | python | train | 37 |
alefnula/tea | tea/shell/__init__.py | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L381-L396 | def read(path, encoding="utf-8"):
"""Read the content of the file.
Args:
path (str): Path to the file
encoding (str): File encoding. Default: utf-8
Returns:
str: File content or empty string if there was an error
"""
try:
with io.open(path, encoding=encoding) as f:
... | [
"def",
"read",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"try",
":",
"with",
"io",
".",
"open",
"(",
"path",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")",
"except",
"Exception",
"as",
... | Read the content of the file.
Args:
path (str): Path to the file
encoding (str): File encoding. Default: utf-8
Returns:
str: File content or empty string if there was an error | [
"Read",
"the",
"content",
"of",
"the",
"file",
"."
] | python | train | 27.3125 |
theiviaxx/Frog | frog/send_file.py | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/send_file.py#L46-L63 | def send_zipfile(request, fileList):
"""
Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files.... | [
"def",
"send_zipfile",
"(",
"request",
",",
"fileList",
")",
":",
"temp",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
")",
"archive",
"=",
"zipfile",
".",
"ZipFile",
"(",
"temp",
",",
"'w'",
",",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"for",
"artist",
",",... | Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files. | [
"Create",
"a",
"ZIP",
"file",
"on",
"disk",
"and",
"transmit",
"it",
"in",
"chunks",
"of",
"8KB",
"without",
"loading",
"the",
"whole",
"file",
"into",
"memory",
".",
"A",
"similar",
"approach",
"can",
"be",
"used",
"for",
"large",
"dynamic",
"PDF",
"fil... | python | train | 47.944444 |
tjcsl/cslbot | cslbot/commands/morse.py | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/morse.py#L23-L35 | def cmd(send, msg, args):
"""Converts text to morse code.
Syntax: {command} [text]
"""
if not msg:
msg = gen_word()
morse = gen_morse(msg)
if len(morse) > 100:
send("Your morse is too long. Have you considered Western Union?")
else:
send(morse) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"msg",
"=",
"gen_word",
"(",
")",
"morse",
"=",
"gen_morse",
"(",
"msg",
")",
"if",
"len",
"(",
"morse",
")",
">",
"100",
":",
"send",
"(",
"\"Your morse is to... | Converts text to morse code.
Syntax: {command} [text] | [
"Converts",
"text",
"to",
"morse",
"code",
"."
] | python | train | 22 |
wummel/linkchecker | third_party/dnspython/dns/inet.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/inet.py#L92-L107 | def is_multicast(text):
"""Is the textual-form network address a multicast address?
@param text: the textual address
@raises ValueError: the address family cannot be determined from the input.
@rtype: bool
"""
try:
first = ord(dns.ipv4.inet_aton(text)[0])
return (first >= 224 an... | [
"def",
"is_multicast",
"(",
"text",
")",
":",
"try",
":",
"first",
"=",
"ord",
"(",
"dns",
".",
"ipv4",
".",
"inet_aton",
"(",
"text",
")",
"[",
"0",
"]",
")",
"return",
"(",
"first",
">=",
"224",
"and",
"first",
"<=",
"239",
")",
"except",
"Exce... | Is the textual-form network address a multicast address?
@param text: the textual address
@raises ValueError: the address family cannot be determined from the input.
@rtype: bool | [
"Is",
"the",
"textual",
"-",
"form",
"network",
"address",
"a",
"multicast",
"address?"
] | python | train | 31.0625 |
openid/python-openid | openid/extensions/ax.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/ax.py#L149-L179 | def toTypeURIs(namespace_map, alias_list_s):
"""Given a namespace mapping and a string containing a
comma-separated list of namespace aliases, return a list of type
URIs that correspond to those aliases.
@param namespace_map: The mapping from namespace URI to alias
@type namespace_map: openid.messa... | [
"def",
"toTypeURIs",
"(",
"namespace_map",
",",
"alias_list_s",
")",
":",
"uris",
"=",
"[",
"]",
"if",
"alias_list_s",
":",
"for",
"alias",
"in",
"alias_list_s",
".",
"split",
"(",
"','",
")",
":",
"type_uri",
"=",
"namespace_map",
".",
"getNamespaceURI",
... | Given a namespace mapping and a string containing a
comma-separated list of namespace aliases, return a list of type
URIs that correspond to those aliases.
@param namespace_map: The mapping from namespace URI to alias
@type namespace_map: openid.message.NamespaceMap
@param alias_list_s: The string... | [
"Given",
"a",
"namespace",
"mapping",
"and",
"a",
"string",
"containing",
"a",
"comma",
"-",
"separated",
"list",
"of",
"namespace",
"aliases",
"return",
"a",
"list",
"of",
"type",
"URIs",
"that",
"correspond",
"to",
"those",
"aliases",
"."
] | python | train | 36.483871 |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/cursor.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/cursor.py#L301-L355 | def __query_spec(self):
"""Get the spec to use for a query.
"""
operators = self.__modifiers.copy()
if self.__ordering:
operators["$orderby"] = self.__ordering
if self.__explain:
operators["$explain"] = True
if self.__hint:
operators["$... | [
"def",
"__query_spec",
"(",
"self",
")",
":",
"operators",
"=",
"self",
".",
"__modifiers",
".",
"copy",
"(",
")",
"if",
"self",
".",
"__ordering",
":",
"operators",
"[",
"\"$orderby\"",
"]",
"=",
"self",
".",
"__ordering",
"if",
"self",
".",
"__explain"... | Get the spec to use for a query. | [
"Get",
"the",
"spec",
"to",
"use",
"for",
"a",
"query",
"."
] | python | train | 39 |
7sDream/zhihu-py3 | zhihu/author.py | https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/author.py#L356-L367 | def followed_topic_num(self):
"""获取用户关注的话题数
:return: 关注的话题数
:rtype: int
"""
if self.url is not None:
tag = self.soup.find('div', class_='zm-profile-side-topics')
if tag is not None:
return int(re_get_number.match(
tag.p... | [
"def",
"followed_topic_num",
"(",
"self",
")",
":",
"if",
"self",
".",
"url",
"is",
"not",
"None",
":",
"tag",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'div'",
",",
"class_",
"=",
"'zm-profile-side-topics'",
")",
"if",
"tag",
"is",
"not",
"None",
... | 获取用户关注的话题数
:return: 关注的话题数
:rtype: int | [
"获取用户关注的话题数"
] | python | train | 29.5 |
cloudant/python-cloudant | src/cloudant/_common_util.py | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/_common_util.py#L283-L294 | def response_to_json_dict(response, **kwargs):
"""
Standard place to convert responses to JSON.
:param response: requests response object
:param **kwargs: arguments accepted by json.loads
:returns: dict of JSON response
"""
if response.encoding is None:
response.encoding = 'utf-8'
... | [
"def",
"response_to_json_dict",
"(",
"response",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"response",
".",
"encoding",
"is",
"None",
":",
"response",
".",
"encoding",
"=",
"'utf-8'",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"text",
",",
"*",... | Standard place to convert responses to JSON.
:param response: requests response object
:param **kwargs: arguments accepted by json.loads
:returns: dict of JSON response | [
"Standard",
"place",
"to",
"convert",
"responses",
"to",
"JSON",
"."
] | python | train | 29.583333 |
ErikBjare/pyzenobase | examples/upload_lifelogger_spreadsheet/main.py | https://github.com/ErikBjare/pyzenobase/blob/eb0572c7441a350bf5578bc5287f3be53d32ea19/examples/upload_lifelogger_spreadsheet/main.py#L63-L87 | def get_dates(raw_table) -> "list of dates":
"""
Goes through the first column of input table and
returns the first sequence of dates it finds.
"""
dates = []
found_first = False
for i, dstr in enumerate([raw_table[i][0] for i in range(0, len(raw_table))])... | [
"def",
"get_dates",
"(",
"raw_table",
")",
"->",
"\"list of dates\"",
":",
"dates",
"=",
"[",
"]",
"found_first",
"=",
"False",
"for",
"i",
",",
"dstr",
"in",
"enumerate",
"(",
"[",
"raw_table",
"[",
"i",
"]",
"[",
"0",
"]",
"for",
"i",
"in",
"range"... | Goes through the first column of input table and
returns the first sequence of dates it finds. | [
"Goes",
"through",
"the",
"first",
"column",
"of",
"input",
"table",
"and",
"returns",
"the",
"first",
"sequence",
"of",
"dates",
"it",
"finds",
"."
] | python | train | 43.36 |
wummel/linkchecker | linkcheck/logger/html.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/html.py#L171-L177 | def write_url (self, url_data):
"""Write url_data.base_url."""
self.writeln(u"<tr>")
self.writeln(u'<td class="url">%s</td>' % self.part("url"))
self.write(u'<td class="url">')
self.write(u"`%s'" % cgi.escape(url_data.base_url))
self.writeln(u"</td></tr>") | [
"def",
"write_url",
"(",
"self",
",",
"url_data",
")",
":",
"self",
".",
"writeln",
"(",
"u\"<tr>\"",
")",
"self",
".",
"writeln",
"(",
"u'<td class=\"url\">%s</td>'",
"%",
"self",
".",
"part",
"(",
"\"url\"",
")",
")",
"self",
".",
"write",
"(",
"u'<td ... | Write url_data.base_url. | [
"Write",
"url_data",
".",
"base_url",
"."
] | python | train | 42.571429 |
Nike-Inc/cerberus-python-client | cerberus/client.py | https://github.com/Nike-Inc/cerberus-python-client/blob/ef38356822e722fcb6a6ed4a1b38a5b493e753ae/cerberus/client.py#L74-L89 | def _set_token(self):
"""Set the Cerberus token based on auth type"""
try:
self.token = os.environ['CERBERUS_TOKEN']
if self.verbose:
print("Overriding Cerberus token with environment variable.", file=sys.stderr)
logger.info("Overriding Cerberus token ... | [
"def",
"_set_token",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"token",
"=",
"os",
".",
"environ",
"[",
"'CERBERUS_TOKEN'",
"]",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Overriding Cerberus token with environment variable.\"",
",",
"file",
"="... | Set the Cerberus token based on auth type | [
"Set",
"the",
"Cerberus",
"token",
"based",
"on",
"auth",
"type"
] | python | train | 43.75 |
johnnoone/aioconsul | aioconsul/client/session_endpoint.py | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/session_endpoint.py#L198-L237 | async def renew(self, session, *, dc=None):
"""Renews a TTL-based session
Parameters:
session (ObjectID): Session ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Returns:
ObjectMeta: where val... | [
"async",
"def",
"renew",
"(",
"self",
",",
"session",
",",
"*",
",",
"dc",
"=",
"None",
")",
":",
"session_id",
"=",
"extract_attr",
"(",
"session",
",",
"keys",
"=",
"[",
"\"ID\"",
"]",
")",
"response",
"=",
"await",
"self",
".",
"_api",
".",
"put... | Renews a TTL-based session
Parameters:
session (ObjectID): Session ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Returns:
ObjectMeta: where value is session
Raises:
NotFound: ses... | [
"Renews",
"a",
"TTL",
"-",
"based",
"session"
] | python | train | 37.25 |
vxgmichel/aiostream | aiostream/stream/aggregate.py | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/aggregate.py#L43-L52 | def reduce(source, func, initializer=None):
"""Apply a function of two arguments cumulatively to the items
of an asynchronous sequence, reducing the sequence to a single value.
If ``initializer`` is present, it is placed before the items
of the sequence in the calculation, and serves as a default when ... | [
"def",
"reduce",
"(",
"source",
",",
"func",
",",
"initializer",
"=",
"None",
")",
":",
"acc",
"=",
"accumulate",
".",
"raw",
"(",
"source",
",",
"func",
",",
"initializer",
")",
"return",
"select",
".",
"item",
".",
"raw",
"(",
"acc",
",",
"-",
"1... | Apply a function of two arguments cumulatively to the items
of an asynchronous sequence, reducing the sequence to a single value.
If ``initializer`` is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty. | [
"Apply",
"a",
"function",
"of",
"two",
"arguments",
"cumulatively",
"to",
"the",
"items",
"of",
"an",
"asynchronous",
"sequence",
"reducing",
"the",
"sequence",
"to",
"a",
"single",
"value",
"."
] | python | train | 43.3 |
matthewdeanmartin/jiggle_version | jiggle_version/file_makers.py | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/jiggle_version/file_makers.py#L32-L45 | def create_init(self, path): # type: (str) -> None
"""
Create a minimal __init__ file with enough boiler plate to not add to lint messages
:param path:
:return:
"""
source = """# coding=utf-8
\"\"\"
Version
\"\"\"
__version__ = \"0.0.0\"
"""
with io.open(path, "w... | [
"def",
"create_init",
"(",
"self",
",",
"path",
")",
":",
"# type: (str) -> None",
"source",
"=",
"\"\"\"# coding=utf-8\n\\\"\\\"\\\"\nVersion\n\\\"\\\"\\\"\n__version__ = \\\"0.0.0\\\"\n\"\"\"",
"with",
"io",
".",
"open",
"(",
"path",
",",
"\"w\"",
",",
"encoding",
"=",
... | Create a minimal __init__ file with enough boiler plate to not add to lint messages
:param path:
:return: | [
"Create",
"a",
"minimal",
"__init__",
"file",
"with",
"enough",
"boiler",
"plate",
"to",
"not",
"add",
"to",
"lint",
"messages",
":",
"param",
"path",
":",
":",
"return",
":"
] | python | train | 26.642857 |
Clinical-Genomics/scout | scout/adapter/mongo/panel.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/adapter/mongo/panel.py#L265-L296 | def gene_to_panels(self, case_obj):
"""Fetch all gene panels and group them by gene
Args:
case_obj(scout.models.Case)
Returns:
gene_dict(dict): A dictionary with gene as keys and a set of
panel names as value
"""
... | [
"def",
"gene_to_panels",
"(",
"self",
",",
"case_obj",
")",
":",
"LOG",
".",
"info",
"(",
"\"Building gene to panels\"",
")",
"gene_dict",
"=",
"{",
"}",
"for",
"panel_info",
"in",
"case_obj",
".",
"get",
"(",
"'panels'",
",",
"[",
"]",
")",
":",
"panel_... | Fetch all gene panels and group them by gene
Args:
case_obj(scout.models.Case)
Returns:
gene_dict(dict): A dictionary with gene as keys and a set of
panel names as value | [
"Fetch",
"all",
"gene",
"panels",
"and",
"group",
"them",
"by",
"gene"
] | python | test | 34.78125 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1846-L1849 | def get_count(self, prefix=''):
"""Return the total count of errors and warnings."""
return sum([self.counters[key]
for key in self.messages if key.startswith(prefix)]) | [
"def",
"get_count",
"(",
"self",
",",
"prefix",
"=",
"''",
")",
":",
"return",
"sum",
"(",
"[",
"self",
".",
"counters",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
".",
"messages",
"if",
"key",
".",
"startswith",
"(",
"prefix",
")",
"]",
")"
] | Return the total count of errors and warnings. | [
"Return",
"the",
"total",
"count",
"of",
"errors",
"and",
"warnings",
"."
] | python | train | 50.25 |
dmbee/seglearn | seglearn/datasets.py | https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/datasets.py#L13-L46 | def load_watch():
'''
Loads some of the 6-axis inertial sensor data from my smartwatch project. The sensor data was
recorded as study subjects performed sets of 20 shoulder exercise repetitions while wearing a
smartwatch. It is a multivariate time series.
The study can be found here: https://arxiv.... | [
"def",
"load_watch",
"(",
")",
":",
"module_path",
"=",
"dirname",
"(",
"__file__",
")",
"data",
"=",
"np",
".",
"load",
"(",
"module_path",
"+",
"\"/data/watch_dataset.npy\"",
")",
".",
"item",
"(",
")",
"return",
"data"
] | Loads some of the 6-axis inertial sensor data from my smartwatch project. The sensor data was
recorded as study subjects performed sets of 20 shoulder exercise repetitions while wearing a
smartwatch. It is a multivariate time series.
The study can be found here: https://arxiv.org/abs/1802.01489
Return... | [
"Loads",
"some",
"of",
"the",
"6",
"-",
"axis",
"inertial",
"sensor",
"data",
"from",
"my",
"smartwatch",
"project",
".",
"The",
"sensor",
"data",
"was",
"recorded",
"as",
"study",
"subjects",
"performed",
"sets",
"of",
"20",
"shoulder",
"exercise",
"repetit... | python | train | 35.735294 |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/util/bottle3.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/util/bottle3.py#L371-L378 | def add_filter(self, ftype, func):
''' Register a new output filter. Whenever bottle hits a handler output
matching `ftype`, `func` is applyed to it. '''
if not isinstance(ftype, type):
raise TypeError("Expected type object, got %s" % type(ftype))
self.castfilter = [(t, f... | [
"def",
"add_filter",
"(",
"self",
",",
"ftype",
",",
"func",
")",
":",
"if",
"not",
"isinstance",
"(",
"ftype",
",",
"type",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected type object, got %s\"",
"%",
"type",
"(",
"ftype",
")",
")",
"self",
".",
"castf... | Register a new output filter. Whenever bottle hits a handler output
matching `ftype`, `func` is applyed to it. | [
"Register",
"a",
"new",
"output",
"filter",
".",
"Whenever",
"bottle",
"hits",
"a",
"handler",
"output",
"matching",
"ftype",
"func",
"is",
"applyed",
"to",
"it",
"."
] | python | train | 54.5 |
saltstack/salt | salt/modules/linux_lvm.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/linux_lvm.py#L320-L348 | def vgcreate(vgname, devices, **kwargs):
'''
Create an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgcreate my_vg /dev/sdb1,/dev/sdb2
salt mymachine lvm.vgcreate my_vg /dev/sdb1 clustered=y
'''
if not vgname or not devices:
return 'Error: vgn... | [
"def",
"vgcreate",
"(",
"vgname",
",",
"devices",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"vgname",
"or",
"not",
"devices",
":",
"return",
"'Error: vgname and device(s) are both required'",
"if",
"isinstance",
"(",
"devices",
",",
"six",
".",
"string_t... | Create an LVM volume group
CLI Examples:
.. code-block:: bash
salt mymachine lvm.vgcreate my_vg /dev/sdb1,/dev/sdb2
salt mymachine lvm.vgcreate my_vg /dev/sdb1 clustered=y | [
"Create",
"an",
"LVM",
"volume",
"group"
] | python | train | 32.827586 |
gc3-uzh-ch/elasticluster | elasticluster/providers/gce.py | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/gce.py#L586-L616 | def stop_instance(self, instance_id):
"""Stops the instance gracefully.
:param str instance_id: instance identifier
:raises: `InstanceError` if instance can not be stopped
"""
if not instance_id:
log.info("Instance to stop has no instance id")
return
... | [
"def",
"stop_instance",
"(",
"self",
",",
"instance_id",
")",
":",
"if",
"not",
"instance_id",
":",
"log",
".",
"info",
"(",
"\"Instance to stop has no instance id\"",
")",
"return",
"gce",
"=",
"self",
".",
"_connect",
"(",
")",
"try",
":",
"request",
"=",
... | Stops the instance gracefully.
:param str instance_id: instance identifier
:raises: `InstanceError` if instance can not be stopped | [
"Stops",
"the",
"instance",
"gracefully",
"."
] | python | train | 40 |
bitprophet/ssh | ssh/transport.py | https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/transport.py#L969-L1026 | def connect(self, hostkey=None, username='', password=None, pkey=None):
"""
Negotiate an SSH2 session, and optionally verify the server's host key
and authenticate using a password or private key. This is a shortcut
for L{start_client}, L{get_remote_server_key}, and
L{Transport.... | [
"def",
"connect",
"(",
"self",
",",
"hostkey",
"=",
"None",
",",
"username",
"=",
"''",
",",
"password",
"=",
"None",
",",
"pkey",
"=",
"None",
")",
":",
"if",
"hostkey",
"is",
"not",
"None",
":",
"self",
".",
"_preferred_keys",
"=",
"[",
"hostkey",
... | Negotiate an SSH2 session, and optionally verify the server's host key
and authenticate using a password or private key. This is a shortcut
for L{start_client}, L{get_remote_server_key}, and
L{Transport.auth_password} or L{Transport.auth_publickey}. Use those
methods if you want more c... | [
"Negotiate",
"an",
"SSH2",
"session",
"and",
"optionally",
"verify",
"the",
"server",
"s",
"host",
"key",
"and",
"authenticate",
"using",
"a",
"password",
"or",
"private",
"key",
".",
"This",
"is",
"a",
"shortcut",
"for",
"L",
"{",
"start_client",
"}",
"L"... | python | train | 48.551724 |
mwgielen/jackal | jackal/scripts/services.py | https://github.com/mwgielen/jackal/blob/7fe62732eb5194b7246215d5277fb37c398097bf/jackal/scripts/services.py#L21-L34 | def overview():
"""
Function to create an overview of the services.
Will print a list of ports found an the number of times the port was seen.
"""
search = Service.search()
search = search.filter("term", state='open')
search.aggs.bucket('port_count', 'terms', field='port', order={'_c... | [
"def",
"overview",
"(",
")",
":",
"search",
"=",
"Service",
".",
"search",
"(",
")",
"search",
"=",
"search",
".",
"filter",
"(",
"\"term\"",
",",
"state",
"=",
"'open'",
")",
"search",
".",
"aggs",
".",
"bucket",
"(",
"'port_count'",
",",
"'terms'",
... | Function to create an overview of the services.
Will print a list of ports found an the number of times the port was seen. | [
"Function",
"to",
"create",
"an",
"overview",
"of",
"the",
"services",
".",
"Will",
"print",
"a",
"list",
"of",
"ports",
"found",
"an",
"the",
"number",
"of",
"times",
"the",
"port",
"was",
"seen",
"."
] | python | valid | 45.285714 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.