repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
paramiko/paramiko | tasks.py | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/tasks.py#L86-L91 | def guard(ctx, opts=""):
"""
Execute all tests and then watch for changes, re-running.
"""
# TODO if coverage was run via pytest-cov, we could add coverage here too
return test(ctx, include_slow=True, loop_on_fail=True, opts=opts) | [
"def",
"guard",
"(",
"ctx",
",",
"opts",
"=",
"\"\"",
")",
":",
"# TODO if coverage was run via pytest-cov, we could add coverage here too",
"return",
"test",
"(",
"ctx",
",",
"include_slow",
"=",
"True",
",",
"loop_on_fail",
"=",
"True",
",",
"opts",
"=",
"opts",... | Execute all tests and then watch for changes, re-running. | [
"Execute",
"all",
"tests",
"and",
"then",
"watch",
"for",
"changes",
"re",
"-",
"running",
"."
] | python | train |
bokeh/bokeh | bokeh/core/property/descriptors.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L620-L637 | def trigger_if_changed(self, obj, old):
''' Send a change event notification if the property is set to a
value is not equal to ``old``.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the pr... | [
"def",
"trigger_if_changed",
"(",
"self",
",",
"obj",
",",
"old",
")",
":",
"new_value",
"=",
"self",
".",
"__get__",
"(",
"obj",
",",
"obj",
".",
"__class__",
")",
"if",
"not",
"self",
".",
"property",
".",
"matches",
"(",
"old",
",",
"new_value",
"... | Send a change event notification if the property is set to a
value is not equal to ``old``.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property to compare
Returns:
None | [
"Send",
"a",
"change",
"event",
"notification",
"if",
"the",
"property",
"is",
"set",
"to",
"a",
"value",
"is",
"not",
"equal",
"to",
"old",
"."
] | python | train |
hazelcast/hazelcast-python-client | hazelcast/client.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/client.py#L251-L264 | def shutdown(self):
"""
Shuts down this HazelcastClient.
"""
if self.lifecycle.is_live:
self.lifecycle.fire_lifecycle_event(LIFECYCLE_STATE_SHUTTING_DOWN)
self.near_cache_manager.destroy_all_near_caches()
self.statistics.shutdown()
self.par... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"self",
".",
"lifecycle",
".",
"is_live",
":",
"self",
".",
"lifecycle",
".",
"fire_lifecycle_event",
"(",
"LIFECYCLE_STATE_SHUTTING_DOWN",
")",
"self",
".",
"near_cache_manager",
".",
"destroy_all_near_caches",
"(",... | Shuts down this HazelcastClient. | [
"Shuts",
"down",
"this",
"HazelcastClient",
"."
] | python | train |
GoogleCloudPlatform/datastore-ndb-python | ndb/context.py | https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/context.py#L103-L126 | def _make_ctx_options(ctx_options, config_cls=ContextOptions):
"""Helper to construct a ContextOptions object from keyword arguments.
Args:
ctx_options: A dict of keyword arguments.
config_cls: Optional Configuration class to use, default ContextOptions.
Note that either 'options' or 'config' can be use... | [
"def",
"_make_ctx_options",
"(",
"ctx_options",
",",
"config_cls",
"=",
"ContextOptions",
")",
":",
"if",
"not",
"ctx_options",
":",
"return",
"None",
"for",
"key",
"in",
"list",
"(",
"ctx_options",
")",
":",
"translation",
"=",
"_OPTION_TRANSLATIONS",
".",
"g... | Helper to construct a ContextOptions object from keyword arguments.
Args:
ctx_options: A dict of keyword arguments.
config_cls: Optional Configuration class to use, default ContextOptions.
Note that either 'options' or 'config' can be used to pass another
Configuration object, but not both. If another ... | [
"Helper",
"to",
"construct",
"a",
"ContextOptions",
"object",
"from",
"keyword",
"arguments",
"."
] | python | train |
dvdotsenko/jsonrpc.py | jsonrpcparts/serializers.py | https://github.com/dvdotsenko/jsonrpc.py/blob/19673edd77a9518ac5655bd407f6b93ffbb2cafc/jsonrpcparts/serializers.py#L526-L553 | def parse_response(cls, response_string):
"""JSONRPC allows for **batch** responses to be communicated
as arrays of dicts. This method parses out each individual
element in the batch and returns a list of tuples, each
tuple a result of parsing of each item in the batch.
:Returns... | [
"def",
"parse_response",
"(",
"cls",
",",
"response_string",
")",
":",
"try",
":",
"batch",
"=",
"cls",
".",
"json_loads",
"(",
"response_string",
")",
"except",
"ValueError",
"as",
"err",
":",
"raise",
"errors",
".",
"RPCParseError",
"(",
"\"No valid JSON. (%... | JSONRPC allows for **batch** responses to be communicated
as arrays of dicts. This method parses out each individual
element in the batch and returns a list of tuples, each
tuple a result of parsing of each item in the batch.
:Returns: | tuple of (results, is_batch_mode_flag)
... | [
"JSONRPC",
"allows",
"for",
"**",
"batch",
"**",
"responses",
"to",
"be",
"communicated",
"as",
"arrays",
"of",
"dicts",
".",
"This",
"method",
"parses",
"out",
"each",
"individual",
"element",
"in",
"the",
"batch",
"and",
"returns",
"a",
"list",
"of",
"tu... | python | train |
python-cmd2/cmd2 | cmd2/argparse_completer.py | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/argparse_completer.py#L622-L634 | def complete_command_help(self, tokens: List[str], text: str, line: str, begidx: int, endidx: int) -> List[str]:
"""Supports the completion of sub-commands for commands through the cmd2 help command."""
for idx, token in enumerate(tokens):
if idx >= self._token_start_index:
i... | [
"def",
"complete_command_help",
"(",
"self",
",",
"tokens",
":",
"List",
"[",
"str",
"]",
",",
"text",
":",
"str",
",",
"line",
":",
"str",
",",
"begidx",
":",
"int",
",",
"endidx",
":",
"int",
")",
"->",
"List",
"[",
"str",
"]",
":",
"for",
"idx... | Supports the completion of sub-commands for commands through the cmd2 help command. | [
"Supports",
"the",
"completion",
"of",
"sub",
"-",
"commands",
"for",
"commands",
"through",
"the",
"cmd2",
"help",
"command",
"."
] | python | train |
gagneurlab/concise | concise/preprocessing/sequence.py | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/preprocessing/sequence.py#L243-L261 | def encodeAA(seq_vec, maxlen=None, seq_align="start", encode_type="one_hot"):
"""Convert the Amino-acid sequence into 1-hot-encoding numpy array
# Arguments
seq_vec: List of strings/amino-acid sequences
maxlen: Maximum sequence length. See `pad_sequences` for more detail
seq_align: How ... | [
"def",
"encodeAA",
"(",
"seq_vec",
",",
"maxlen",
"=",
"None",
",",
"seq_align",
"=",
"\"start\"",
",",
"encode_type",
"=",
"\"one_hot\"",
")",
":",
"return",
"encodeSequence",
"(",
"seq_vec",
",",
"vocab",
"=",
"AMINO_ACIDS",
",",
"neutral_vocab",
"=",
"\"_... | Convert the Amino-acid sequence into 1-hot-encoding numpy array
# Arguments
seq_vec: List of strings/amino-acid sequences
maxlen: Maximum sequence length. See `pad_sequences` for more detail
seq_align: How to align the sequences of variable lengths. See `pad_sequences` for more detail
... | [
"Convert",
"the",
"Amino",
"-",
"acid",
"sequence",
"into",
"1",
"-",
"hot",
"-",
"encoding",
"numpy",
"array"
] | python | train |
idlesign/django-sitemessage | sitemessage/toolbox.py | https://github.com/idlesign/django-sitemessage/blob/25b179b798370354c5988042ec209e255d23793f/sitemessage/toolbox.py#L30-L54 | def schedule_messages(messages, recipients=None, sender=None, priority=None):
"""Schedules a message or messages.
:param MessageBase|str|list messages: str or MessageBase heir or list - use str to create PlainTextMessage.
:param list|None recipients: recipients addresses or Django User model heir instances... | [
"def",
"schedule_messages",
"(",
"messages",
",",
"recipients",
"=",
"None",
",",
"sender",
"=",
"None",
",",
"priority",
"=",
"None",
")",
":",
"if",
"not",
"is_iterable",
"(",
"messages",
")",
":",
"messages",
"=",
"(",
"messages",
",",
")",
"results",... | Schedules a message or messages.
:param MessageBase|str|list messages: str or MessageBase heir or list - use str to create PlainTextMessage.
:param list|None recipients: recipients addresses or Django User model heir instances
If `None` Dispatches should be created before send using `prepare_dispatches... | [
"Schedules",
"a",
"message",
"or",
"messages",
"."
] | python | train |
quodlibet/mutagen | mutagen/id3/_frames.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/id3/_frames.py#L236-L292 | def _fromData(cls, header, tflags, data):
"""Construct this ID3 frame from raw string data.
Raises:
ID3JunkFrameError in case parsing failed
NotImplementedError in case parsing isn't implemented
ID3EncryptionUnsupportedError in case the frame is encrypted.
"""
... | [
"def",
"_fromData",
"(",
"cls",
",",
"header",
",",
"tflags",
",",
"data",
")",
":",
"if",
"header",
".",
"version",
">=",
"header",
".",
"_V24",
":",
"if",
"tflags",
"&",
"(",
"Frame",
".",
"FLAG24_COMPRESS",
"|",
"Frame",
".",
"FLAG24_DATALEN",
")",
... | Construct this ID3 frame from raw string data.
Raises:
ID3JunkFrameError in case parsing failed
NotImplementedError in case parsing isn't implemented
ID3EncryptionUnsupportedError in case the frame is encrypted. | [
"Construct",
"this",
"ID3",
"frame",
"from",
"raw",
"string",
"data",
"."
] | python | train |
Galarzaa90/tibia.py | tibiapy/utils.py | https://github.com/Galarzaa90/tibia.py/blob/02ba1a8f1e18177ef5c7dcd44affc8d761d59e12/tibiapy/utils.py#L183-L207 | def try_datetime(obj) -> Optional[datetime.datetime]:
"""Attempts to convert an object into a datetime.
If the date format is known, it's recommended to use the corresponding function
This is meant to be used in constructors.
Parameters
----------
obj: :class:`str`, :class:`dict`, :class:`date... | [
"def",
"try_datetime",
"(",
"obj",
")",
"->",
"Optional",
"[",
"datetime",
".",
"datetime",
"]",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"obj",
"res",
... | Attempts to convert an object into a datetime.
If the date format is known, it's recommended to use the corresponding function
This is meant to be used in constructors.
Parameters
----------
obj: :class:`str`, :class:`dict`, :class:`datetime.datetime`
The object to convert.
Returns
... | [
"Attempts",
"to",
"convert",
"an",
"object",
"into",
"a",
"datetime",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/openpy.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/openpy.py#L163-L191 | def read_py_url(url, errors='replace', skip_encoding_cookie=True):
"""Read a Python file from a URL, using the encoding declared inside the file.
Parameters
----------
url : str
The URL from which to fetch the file.
errors : str
How to handle decoding errors in the file. Options are... | [
"def",
"read_py_url",
"(",
"url",
",",
"errors",
"=",
"'replace'",
",",
"skip_encoding_cookie",
"=",
"True",
")",
":",
"response",
"=",
"urllib",
".",
"urlopen",
"(",
"url",
")",
"buffer",
"=",
"io",
".",
"BytesIO",
"(",
"response",
".",
"read",
"(",
"... | Read a Python file from a URL, using the encoding declared inside the file.
Parameters
----------
url : str
The URL from which to fetch the file.
errors : str
How to handle decoding errors in the file. Options are the same as for
bytes.decode(), but here 'replace' is the default.
... | [
"Read",
"a",
"Python",
"file",
"from",
"a",
"URL",
"using",
"the",
"encoding",
"declared",
"inside",
"the",
"file",
".",
"Parameters",
"----------",
"url",
":",
"str",
"The",
"URL",
"from",
"which",
"to",
"fetch",
"the",
"file",
".",
"errors",
":",
"str"... | python | test |
jcalogovic/lightning | stormstats/misc.py | https://github.com/jcalogovic/lightning/blob/f9e52731c9dd40cb302295ec36a444e0377d0570/stormstats/misc.py#L81-L131 | def count_lightning(datain, time_step):
"""**Count lightning strikes detected within a defined time_step**
Generate time intervals according to the time_step defined and count
lightning strikes in these intervals. Statistics are also calculated for
lightning detection errors and the number of stations ... | [
"def",
"count_lightning",
"(",
"datain",
",",
"time_step",
")",
":",
"if",
"(",
"1440",
"%",
"time_step",
"==",
"0",
")",
":",
"# check if time_step is multiple of 1 day",
"i",
"=",
"0",
"# run for loop for all time steps in one day",
"for",
"time_interval",
"in",
"... | **Count lightning strikes detected within a defined time_step**
Generate time intervals according to the time_step defined and count
lightning strikes in these intervals. Statistics are also calculated for
lightning detection errors and the number of stations and added to an
output dataframe. Time stam... | [
"**",
"Count",
"lightning",
"strikes",
"detected",
"within",
"a",
"defined",
"time_step",
"**"
] | python | train |
elemoine/papyrus | papyrus/protocol.py | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/protocol.py#L106-L141 | def create_attr_filter(request, mapped_class):
"""Create an ``and_`` SQLAlchemy filter (a ClauseList object) based
on the request params (``queryable``, ``eq``, ``ne``, ...).
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class.
"""
mapping = {
... | [
"def",
"create_attr_filter",
"(",
"request",
",",
"mapped_class",
")",
":",
"mapping",
"=",
"{",
"'eq'",
":",
"'__eq__'",
",",
"'ne'",
":",
"'__ne__'",
",",
"'lt'",
":",
"'__lt__'",
",",
"'lte'",
":",
"'__le__'",
",",
"'gt'",
":",
"'__gt__'",
",",
"'gte'... | Create an ``and_`` SQLAlchemy filter (a ClauseList object) based
on the request params (``queryable``, ``eq``, ``ne``, ...).
Arguments:
request
the request.
mapped_class
the SQLAlchemy mapped class. | [
"Create",
"an",
"and_",
"SQLAlchemy",
"filter",
"(",
"a",
"ClauseList",
"object",
")",
"based",
"on",
"the",
"request",
"params",
"(",
"queryable",
"eq",
"ne",
"...",
")",
"."
] | python | train |
steffann/pylisp | pylisp/packet/ip/ipv6/base.py | https://github.com/steffann/pylisp/blob/907340f0c7ef2c4d4fe0c8e0a48df5be0d969407/pylisp/packet/ip/ipv6/base.py#L158-L190 | def to_bytes(self):
'''
Create bytes from properties
'''
# Verify that the properties make sense
self.sanitize()
# Write the version
bitstream = BitStream('uint:4=%d' % self.version)
# Write the traffic class
bitstream += BitStream('uint:8=%d' % ... | [
"def",
"to_bytes",
"(",
"self",
")",
":",
"# Verify that the properties make sense",
"self",
".",
"sanitize",
"(",
")",
"# Write the version",
"bitstream",
"=",
"BitStream",
"(",
"'uint:4=%d'",
"%",
"self",
".",
"version",
")",
"# Write the traffic class",
"bitstream"... | Create bytes from properties | [
"Create",
"bytes",
"from",
"properties"
] | python | train |
tradenity/python-sdk | tradenity/resources/table_rate_shipping.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/table_rate_shipping.py#L660-L680 | def get_table_rate_shipping_by_id(cls, table_rate_shipping_id, **kwargs):
"""Find TableRateShipping
Return single instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> th... | [
"def",
"get_table_rate_shipping_by_id",
"(",
"cls",
",",
"table_rate_shipping_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_g... | Find TableRateShipping
Return single instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_table_rate_shipping_by_id(table_rate_shipping_id, async=True)
... | [
"Find",
"TableRateShipping"
] | python | train |
thespacedoctor/tastic | tastic/tastic.py | https://github.com/thespacedoctor/tastic/blob/a0a16cf329a50057906ac3f696bb60b6fcee25e0/tastic/tastic.py#L1117-L1195 | def add_task(
self,
title,
tags=None):
"""*Add a task to this taskpaper object*
**Key Arguments:**
- ``title`` -- the title for the task.
- ``tags`` -- tag string (*'@one @two(data)'*) or list of tags (*['one', 'two(data)']*)
**Return... | [
"def",
"add_task",
"(",
"self",
",",
"title",
",",
"tags",
"=",
"None",
")",
":",
"self",
".",
"refresh",
"task",
"=",
"title",
".",
"strip",
"(",
")",
"if",
"task",
"[",
":",
"2",
"]",
"!=",
"\"- \"",
":",
"task",
"=",
"\"- \"",
"+",
"task",
"... | *Add a task to this taskpaper object*
**Key Arguments:**
- ``title`` -- the title for the task.
- ``tags`` -- tag string (*'@one @two(data)'*) or list of tags (*['one', 'two(data)']*)
**Return:**
- ``task`` -- the new taskpaper task object
**Usage:**
... | [
"*",
"Add",
"a",
"task",
"to",
"this",
"taskpaper",
"object",
"*"
] | python | train |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L859-L897 | def whitespace_before_comment(logical_line, tokens):
r"""Separate inline comments by at least two spaces.
An inline comment is a comment on the same line as a statement. Inline
comments should be separated by at least two spaces from the statement.
They should start with a # and a single space.
E... | [
"def",
"whitespace_before_comment",
"(",
"logical_line",
",",
"tokens",
")",
":",
"prev_end",
"=",
"(",
"0",
",",
"0",
")",
"for",
"token_type",
",",
"text",
",",
"start",
",",
"end",
",",
"line",
"in",
"tokens",
":",
"if",
"token_type",
"==",
"tokenize"... | r"""Separate inline comments by at least two spaces.
An inline comment is a comment on the same line as a statement. Inline
comments should be separated by at least two spaces from the statement.
They should start with a # and a single space.
Each line of a block comment starts with a # and a single ... | [
"r",
"Separate",
"inline",
"comments",
"by",
"at",
"least",
"two",
"spaces",
"."
] | python | train |
tensorflow/cleverhans | scripts/make_confidence_report_bundled.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/make_confidence_report_bundled.py#L42-L56 | def main(argv=None):
"""
Make a confidence report and save it to disk.
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
print(filepath)
make_confidence_report_bundled(filepath=filepath,
test_start=FLAGS.test_start,
... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"try",
":",
"_name_of_script",
",",
"filepath",
"=",
"argv",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"argv",
")",
"print",
"(",
"filepath",
")",
"make_confidence_report_bundled",
"(",
"filep... | Make a confidence report and save it to disk. | [
"Make",
"a",
"confidence",
"report",
"and",
"save",
"it",
"to",
"disk",
"."
] | python | train |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L203-L221 | def on_touch_move(self, touch):
"""If an entity is selected, drag it."""
if hasattr(self, '_lasttouch') and self._lasttouch == touch:
return
if self.app.selection in self.selection_candidates:
self.selection_candidates.remove(self.app.selection)
if self.app.select... | [
"def",
"on_touch_move",
"(",
"self",
",",
"touch",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_lasttouch'",
")",
"and",
"self",
".",
"_lasttouch",
"==",
"touch",
":",
"return",
"if",
"self",
".",
"app",
".",
"selection",
"in",
"self",
".",
"selecti... | If an entity is selected, drag it. | [
"If",
"an",
"entity",
"is",
"selected",
"drag",
"it",
"."
] | python | train |
ternaris/marv | docs/tutorial/code/marv_tutorial/__init__.py | https://github.com/ternaris/marv/blob/c221354d912ff869bbdb4f714a86a70be30d823e/docs/tutorial/code/marv_tutorial/__init__.py#L124-L147 | def gallery_section(images, title):
"""Create detail section with gallery.
Args:
title (str): Title to be displayed for detail section.
images: stream of marv image files
Returns
One detail section.
"""
# pull all images
imgs = []
while True:
img = yield mar... | [
"def",
"gallery_section",
"(",
"images",
",",
"title",
")",
":",
"# pull all images",
"imgs",
"=",
"[",
"]",
"while",
"True",
":",
"img",
"=",
"yield",
"marv",
".",
"pull",
"(",
"images",
")",
"if",
"img",
"is",
"None",
":",
"break",
"imgs",
".",
"ap... | Create detail section with gallery.
Args:
title (str): Title to be displayed for detail section.
images: stream of marv image files
Returns
One detail section. | [
"Create",
"detail",
"section",
"with",
"gallery",
"."
] | python | train |
mkoura/dump2polarion | dump2polarion/parselogs.py | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/parselogs.py#L208-L214 | def get_requirement_warn(self, line):
"""Gets name of test case that was not successfully imported."""
res = self.REQ_WARN_SEARCH.search(line)
try:
return LogItem(res.group(1), None, None)
except (AttributeError, IndexError):
return None | [
"def",
"get_requirement_warn",
"(",
"self",
",",
"line",
")",
":",
"res",
"=",
"self",
".",
"REQ_WARN_SEARCH",
".",
"search",
"(",
"line",
")",
"try",
":",
"return",
"LogItem",
"(",
"res",
".",
"group",
"(",
"1",
")",
",",
"None",
",",
"None",
")",
... | Gets name of test case that was not successfully imported. | [
"Gets",
"name",
"of",
"test",
"case",
"that",
"was",
"not",
"successfully",
"imported",
"."
] | python | train |
OSSOS/MOP | src/ossos/core/ossos/storage.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L1546-L1554 | def get_header(uri):
"""
Pull a FITS header from observation at the given URI
@param uri: The URI of the image in VOSpace.
"""
if uri not in astheaders:
astheaders[uri] = get_hdu(uri, cutout="[1:1,1:1]")[0].header
return astheaders[uri] | [
"def",
"get_header",
"(",
"uri",
")",
":",
"if",
"uri",
"not",
"in",
"astheaders",
":",
"astheaders",
"[",
"uri",
"]",
"=",
"get_hdu",
"(",
"uri",
",",
"cutout",
"=",
"\"[1:1,1:1]\"",
")",
"[",
"0",
"]",
".",
"header",
"return",
"astheaders",
"[",
"u... | Pull a FITS header from observation at the given URI
@param uri: The URI of the image in VOSpace. | [
"Pull",
"a",
"FITS",
"header",
"from",
"observation",
"at",
"the",
"given",
"URI"
] | python | train |
greenbone/ospd | ospd/misc.py | https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L902-L917 | def print_version(wrapper):
""" Prints the server version and license information."""
scanner_name = wrapper.get_scanner_name()
server_version = wrapper.get_server_version()
print("OSP Server for {0} version {1}".format(scanner_name, server_version))
protocol_version = wrapper.get_protocol_version(... | [
"def",
"print_version",
"(",
"wrapper",
")",
":",
"scanner_name",
"=",
"wrapper",
".",
"get_scanner_name",
"(",
")",
"server_version",
"=",
"wrapper",
".",
"get_server_version",
"(",
")",
"print",
"(",
"\"OSP Server for {0} version {1}\"",
".",
"format",
"(",
"sca... | Prints the server version and license information. | [
"Prints",
"the",
"server",
"version",
"and",
"license",
"information",
"."
] | python | train |
rigetti/quantumflow | quantumflow/ops.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L337-L342 | def choi(self) -> bk.BKTensor:
"""Return the Choi matrix representation of this super
operator"""
# Put superop axes in [ok, ib, ob, ik] and reshape to matrix
N = self.qubit_nb
return bk.reshape(self.sharp.tensor, [2**(N*2)] * 2) | [
"def",
"choi",
"(",
"self",
")",
"->",
"bk",
".",
"BKTensor",
":",
"# Put superop axes in [ok, ib, ob, ik] and reshape to matrix",
"N",
"=",
"self",
".",
"qubit_nb",
"return",
"bk",
".",
"reshape",
"(",
"self",
".",
"sharp",
".",
"tensor",
",",
"[",
"2",
"**... | Return the Choi matrix representation of this super
operator | [
"Return",
"the",
"Choi",
"matrix",
"representation",
"of",
"this",
"super",
"operator"
] | python | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/flexible_shape_utils.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/flexible_shape_utils.py#L220-L229 | def isFlexible(self):
"""
Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value.
"""
for key, value in self.arrayShapeRange.items():
if key in _CONSTRAINED_KEYS:
if value.isFlexible:
r... | [
"def",
"isFlexible",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"arrayShapeRange",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"_CONSTRAINED_KEYS",
":",
"if",
"value",
".",
"isFlexible",
":",
"return",
"True",
"return",
"... | Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value. | [
"Returns",
"true",
"if",
"any",
"one",
"of",
"the",
"channel",
"height",
"or",
"width",
"ranges",
"of",
"this",
"shape",
"allow",
"more",
"than",
"one",
"input",
"value",
"."
] | python | train |
dcos/shakedown | shakedown/dcos/master.py | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/master.py#L93-L101 | def get_all_masters():
""" Returns the json object that represents each of the masters.
"""
masters = []
for master in __master_zk_nodes_keys():
master_zk_str = get_zk_node_data(master)['str']
masters.append(json.loads(master_zk_str))
return masters | [
"def",
"get_all_masters",
"(",
")",
":",
"masters",
"=",
"[",
"]",
"for",
"master",
"in",
"__master_zk_nodes_keys",
"(",
")",
":",
"master_zk_str",
"=",
"get_zk_node_data",
"(",
"master",
")",
"[",
"'str'",
"]",
"masters",
".",
"append",
"(",
"json",
".",
... | Returns the json object that represents each of the masters. | [
"Returns",
"the",
"json",
"object",
"that",
"represents",
"each",
"of",
"the",
"masters",
"."
] | python | train |
dcoker/awsmfa | awsmfa/__main__.py | https://github.com/dcoker/awsmfa/blob/18a8216bfd3184c78b4067edf5198250f66e003d/awsmfa/__main__.py#L157-L170 | def acquire_code(args, session, session3):
"""returns the user's token serial number, MFA token code, and an
error code."""
serial_number = find_mfa_for_user(args.serial_number, session, session3)
if not serial_number:
print("There are no MFA devices associated with this user.",
fi... | [
"def",
"acquire_code",
"(",
"args",
",",
"session",
",",
"session3",
")",
":",
"serial_number",
"=",
"find_mfa_for_user",
"(",
"args",
".",
"serial_number",
",",
"session",
",",
"session3",
")",
"if",
"not",
"serial_number",
":",
"print",
"(",
"\"There are no ... | returns the user's token serial number, MFA token code, and an
error code. | [
"returns",
"the",
"user",
"s",
"token",
"serial",
"number",
"MFA",
"token",
"code",
"and",
"an",
"error",
"code",
"."
] | python | train |
d0c-s4vage/pfp | pfp/interp.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2060-L2090 | def _handle_for(self, node, scope, ctxt, stream):
"""Handle For nodes
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._dlog("handling for")
if node.init is not None:
# perform the init
self._hand... | [
"def",
"_handle_for",
"(",
"self",
",",
"node",
",",
"scope",
",",
"ctxt",
",",
"stream",
")",
":",
"self",
".",
"_dlog",
"(",
"\"handling for\"",
")",
"if",
"node",
".",
"init",
"is",
"not",
"None",
":",
"# perform the init",
"self",
".",
"_handle_node"... | Handle For nodes
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO | [
"Handle",
"For",
"nodes"
] | python | train |
ianmiell/shutit | shutit_class.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L552-L562 | def get_shutit_pexpect_sessions(self, note=None):
"""Returns all the shutit_pexpect_session keys for this object.
@return: list of all shutit_pexpect_session keys (pexpect_session_ids)
"""
self.handle_note(note)
sessions = []
for key in self.shutit_pexpect_sessions:
sessions.append(shutit_object.shutit_... | [
"def",
"get_shutit_pexpect_sessions",
"(",
"self",
",",
"note",
"=",
"None",
")",
":",
"self",
".",
"handle_note",
"(",
"note",
")",
"sessions",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"shutit_pexpect_sessions",
":",
"sessions",
".",
"append",
"(",... | Returns all the shutit_pexpect_session keys for this object.
@return: list of all shutit_pexpect_session keys (pexpect_session_ids) | [
"Returns",
"all",
"the",
"shutit_pexpect_session",
"keys",
"for",
"this",
"object",
"."
] | python | train |
lrgar/scope | scope/scope.py | https://github.com/lrgar/scope/blob/f1c5815b0efd6be75ce54370d69e9b7eca854844/scope/scope.py#L112-L116 | def set_children(self, value, defined):
"""Set the children of the object."""
self.children = value
self.children_defined = defined
return self | [
"def",
"set_children",
"(",
"self",
",",
"value",
",",
"defined",
")",
":",
"self",
".",
"children",
"=",
"value",
"self",
".",
"children_defined",
"=",
"defined",
"return",
"self"
] | Set the children of the object. | [
"Set",
"the",
"children",
"of",
"the",
"object",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1969-L1981 | def connect_to_database_odbc_mysql(self,
database: str,
user: str,
password: str,
server: str = "localhost",
port: int = 3306... | [
"def",
"connect_to_database_odbc_mysql",
"(",
"self",
",",
"database",
":",
"str",
",",
"user",
":",
"str",
",",
"password",
":",
"str",
",",
"server",
":",
"str",
"=",
"\"localhost\"",
",",
"port",
":",
"int",
"=",
"3306",
",",
"driver",
":",
"str",
"... | Connects to a MySQL database via ODBC. | [
"Connects",
"to",
"a",
"MySQL",
"database",
"via",
"ODBC",
"."
] | python | train |
schapman1974/tinymongo | tinymongo/tinymongo.py | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L764-L775 | def hasNext(self):
"""
Returns True if the cursor has a next position, False if not
:return:
"""
cursor_pos = self.cursorpos + 1
try:
self.cursordat[cursor_pos]
return True
except IndexError:
return False | [
"def",
"hasNext",
"(",
"self",
")",
":",
"cursor_pos",
"=",
"self",
".",
"cursorpos",
"+",
"1",
"try",
":",
"self",
".",
"cursordat",
"[",
"cursor_pos",
"]",
"return",
"True",
"except",
"IndexError",
":",
"return",
"False"
] | Returns True if the cursor has a next position, False if not
:return: | [
"Returns",
"True",
"if",
"the",
"cursor",
"has",
"a",
"next",
"position",
"False",
"if",
"not",
":",
"return",
":"
] | python | train |
wookayin/gpustat | gpustat/__main__.py | https://github.com/wookayin/gpustat/blob/28299cdcf55dd627fdd9800cf344988b43188ee8/gpustat/__main__.py#L14-L37 | def print_gpustat(json=False, debug=False, **kwargs):
'''
Display the GPU query results into standard output.
'''
try:
gpu_stats = GPUStatCollection.new_query()
except Exception as e:
sys.stderr.write('Error on querying NVIDIA devices.'
' Use --debug flag for... | [
"def",
"print_gpustat",
"(",
"json",
"=",
"False",
",",
"debug",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"gpu_stats",
"=",
"GPUStatCollection",
".",
"new_query",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"sys",
".",
"stderr"... | Display the GPU query results into standard output. | [
"Display",
"the",
"GPU",
"query",
"results",
"into",
"standard",
"output",
"."
] | python | train |
jorisroovers/gitlint | gitlint/lint.py | https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/lint.py#L98-L108 | def print_violations(self, violations):
""" Print a given set of violations to the standard error output """
for v in violations:
line_nr = v.line_nr if v.line_nr else "-"
self.display.e(u"{0}: {1}".format(line_nr, v.rule_id), exact=True)
self.display.ee(u"{0}: {1} {2... | [
"def",
"print_violations",
"(",
"self",
",",
"violations",
")",
":",
"for",
"v",
"in",
"violations",
":",
"line_nr",
"=",
"v",
".",
"line_nr",
"if",
"v",
".",
"line_nr",
"else",
"\"-\"",
"self",
".",
"display",
".",
"e",
"(",
"u\"{0}: {1}\"",
".",
"for... | Print a given set of violations to the standard error output | [
"Print",
"a",
"given",
"set",
"of",
"violations",
"to",
"the",
"standard",
"error",
"output"
] | python | train |
codeinthehole/django-async-messages | async_messages/middleware.py | https://github.com/codeinthehole/django-async-messages/blob/292cb2fc517521dabc67b90e7ca5b1617f59e214/async_messages/middleware.py#L8-L18 | def process_response(self, request, response):
"""
Check for messages for this user and, if it exists,
call the messages API with it
"""
if hasattr(request, "session") and hasattr(request, "user") and request.user.is_authenticated():
msgs = get_messages(request.user)
... | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"\"session\"",
")",
"and",
"hasattr",
"(",
"request",
",",
"\"user\"",
")",
"and",
"request",
".",
"user",
".",
"is_authenticated",
"("... | Check for messages for this user and, if it exists,
call the messages API with it | [
"Check",
"for",
"messages",
"for",
"this",
"user",
"and",
"if",
"it",
"exists",
"call",
"the",
"messages",
"API",
"with",
"it"
] | python | test |
ejeschke/ginga | ginga/misc/Task.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/misc/Task.py#L369-L395 | def make_tasker(func):
"""make_tasker takes a callable (function, method, etc.) and returns
a new factory function for generating tasks. Each factory function is
designed to consume its arguments and return a task that, when executed,
will call the function upon the arguments.
TODO: deprecate this... | [
"def",
"make_tasker",
"(",
"func",
")",
":",
"def",
"anonFunc",
"(",
"*",
"args",
",",
"*",
"*",
"kwdargs",
")",
":",
"class",
"anonTask",
"(",
"Task",
")",
":",
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"... | make_tasker takes a callable (function, method, etc.) and returns
a new factory function for generating tasks. Each factory function is
designed to consume its arguments and return a task that, when executed,
will call the function upon the arguments.
TODO: deprecate this and just use FuncTask, which ... | [
"make_tasker",
"takes",
"a",
"callable",
"(",
"function",
"method",
"etc",
".",
")",
"and",
"returns",
"a",
"new",
"factory",
"function",
"for",
"generating",
"tasks",
".",
"Each",
"factory",
"function",
"is",
"designed",
"to",
"consume",
"its",
"arguments",
... | python | train |
zimeon/iiif | iiif/static.py | https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/static.py#L214-L261 | def generate(self, src=None, identifier=None):
"""Generate static files for one source image."""
self.src = src
self.identifier = identifier
# Get image details and calculate tiles
im = self.manipulator_klass()
im.srcfile = self.src
im.set_max_image_pixels(self.ma... | [
"def",
"generate",
"(",
"self",
",",
"src",
"=",
"None",
",",
"identifier",
"=",
"None",
")",
":",
"self",
".",
"src",
"=",
"src",
"self",
".",
"identifier",
"=",
"identifier",
"# Get image details and calculate tiles",
"im",
"=",
"self",
".",
"manipulator_k... | Generate static files for one source image. | [
"Generate",
"static",
"files",
"for",
"one",
"source",
"image",
"."
] | python | train |
tradenity/python-sdk | tradenity/resources/zip_codes_geo_zone.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/zip_codes_geo_zone.py#L425-L445 | def delete_zip_codes_geo_zone_by_id(cls, zip_codes_geo_zone_id, **kwargs):
"""Delete ZipCodesGeoZone
Delete an instance of ZipCodesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread ... | [
"def",
"delete_zip_codes_geo_zone_by_id",
"(",
"cls",
",",
"zip_codes_geo_zone_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_... | Delete ZipCodesGeoZone
Delete an instance of ZipCodesGeoZone by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_zip_codes_geo_zone_by_id(zip_codes_geo_zone_id, async=True)
>>> r... | [
"Delete",
"ZipCodesGeoZone"
] | python | train |
hydpy-dev/hydpy | hydpy/core/devicetools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/devicetools.py#L520-L575 | def keywords(self) -> Set[str]:
"""A set of all keywords of all handled devices.
In addition to attribute access via device names, |Nodes| and
|Elements| objects allow for attribute access via keywords,
allowing for an efficient search of certain groups of devices.
Let us use th... | [
"def",
"keywords",
"(",
"self",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"return",
"set",
"(",
"keyword",
"for",
"device",
"in",
"self",
"for",
"keyword",
"in",
"device",
".",
"keywords",
"if",
"keyword",
"not",
"in",
"self",
".",
"_shadowed_keywords",
... | A set of all keywords of all handled devices.
In addition to attribute access via device names, |Nodes| and
|Elements| objects allow for attribute access via keywords,
allowing for an efficient search of certain groups of devices.
Let us use the example from above, where the nodes `na` ... | [
"A",
"set",
"of",
"all",
"keywords",
"of",
"all",
"handled",
"devices",
"."
] | python | train |
kata198/AdvancedHTMLParser | AdvancedHTMLParser/Parser.py | https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Parser.py#L826-L837 | def getMiniHTML(self):
'''
getMiniHTML - Gets the HTML representation of this document without any pretty formatting
and disregarding original whitespace beyond the functional.
@return <str> - HTML with only functional whitespace present
'''
from .For... | [
"def",
"getMiniHTML",
"(",
"self",
")",
":",
"from",
".",
"Formatter",
"import",
"AdvancedHTMLMiniFormatter",
"html",
"=",
"self",
".",
"getHTML",
"(",
")",
"formatter",
"=",
"AdvancedHTMLMiniFormatter",
"(",
"None",
")",
"# Do not double-encode",
"formatter",
"."... | getMiniHTML - Gets the HTML representation of this document without any pretty formatting
and disregarding original whitespace beyond the functional.
@return <str> - HTML with only functional whitespace present | [
"getMiniHTML",
"-",
"Gets",
"the",
"HTML",
"representation",
"of",
"this",
"document",
"without",
"any",
"pretty",
"formatting",
"and",
"disregarding",
"original",
"whitespace",
"beyond",
"the",
"functional",
"."
] | python | train |
opennode/waldur-core | waldur_core/cost_tracking/handlers.py | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/handlers.py#L94-L103 | def _create_historical_estimates(resource, configuration):
""" Create consumption details and price estimates for past months.
Usually we need to update historical values on resource import.
"""
today = timezone.now()
month_start = core_utils.month_start(today)
while month_start > resource.... | [
"def",
"_create_historical_estimates",
"(",
"resource",
",",
"configuration",
")",
":",
"today",
"=",
"timezone",
".",
"now",
"(",
")",
"month_start",
"=",
"core_utils",
".",
"month_start",
"(",
"today",
")",
"while",
"month_start",
">",
"resource",
".",
"crea... | Create consumption details and price estimates for past months.
Usually we need to update historical values on resource import. | [
"Create",
"consumption",
"details",
"and",
"price",
"estimates",
"for",
"past",
"months",
"."
] | python | train |
twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/__init__.py#L187-L196 | def daily(self):
"""
Access the daily
:returns: twilio.rest.api.v2010.account.usage.record.daily.DailyList
:rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyList
"""
if self._daily is None:
self._daily = DailyList(self._version, account_sid=self._... | [
"def",
"daily",
"(",
"self",
")",
":",
"if",
"self",
".",
"_daily",
"is",
"None",
":",
"self",
".",
"_daily",
"=",
"DailyList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")",
"ret... | Access the daily
:returns: twilio.rest.api.v2010.account.usage.record.daily.DailyList
:rtype: twilio.rest.api.v2010.account.usage.record.daily.DailyList | [
"Access",
"the",
"daily"
] | python | train |
mbakker7/timml | timml/aquifer.py | https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/aquifer.py#L85-L98 | def findlayer(self, z):
'''
Returns layer-number, layer-type and model-layer-number'''
if z > self.z[0]:
modellayer, ltype = -1, 'above'
layernumber = None
elif z < self.z[-1]:
modellayer, ltype = len(self.layernumber), 'below'
layernumber ... | [
"def",
"findlayer",
"(",
"self",
",",
"z",
")",
":",
"if",
"z",
">",
"self",
".",
"z",
"[",
"0",
"]",
":",
"modellayer",
",",
"ltype",
"=",
"-",
"1",
",",
"'above'",
"layernumber",
"=",
"None",
"elif",
"z",
"<",
"self",
".",
"z",
"[",
"-",
"1... | Returns layer-number, layer-type and model-layer-number | [
"Returns",
"layer",
"-",
"number",
"layer",
"-",
"type",
"and",
"model",
"-",
"layer",
"-",
"number"
] | python | train |
MacHu-GWU/angora-project | angora/filesystem/filesystem.py | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/filesystem/filesystem.py#L561-L569 | def iterpaths(self):
"""Yield all WinFile's absolute path.
"""
try:
for path in self.order:
yield path
except:
for path in self.files:
yield path | [
"def",
"iterpaths",
"(",
"self",
")",
":",
"try",
":",
"for",
"path",
"in",
"self",
".",
"order",
":",
"yield",
"path",
"except",
":",
"for",
"path",
"in",
"self",
".",
"files",
":",
"yield",
"path"
] | Yield all WinFile's absolute path. | [
"Yield",
"all",
"WinFile",
"s",
"absolute",
"path",
"."
] | python | train |
log2timeline/plaso | plaso/engine/processing_status.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/processing_status.py#L265-L306 | def UpdateNumberOfWarnings(
self, number_of_consumed_warnings, number_of_produced_warnings):
"""Updates the number of warnings.
Args:
number_of_consumed_warnings (int): total number of warnings consumed by
the process.
number_of_produced_warnings (int): total number of warnings prod... | [
"def",
"UpdateNumberOfWarnings",
"(",
"self",
",",
"number_of_consumed_warnings",
",",
"number_of_produced_warnings",
")",
":",
"consumed_warnings_delta",
"=",
"0",
"if",
"number_of_consumed_warnings",
"is",
"not",
"None",
":",
"if",
"number_of_consumed_warnings",
"<",
"s... | Updates the number of warnings.
Args:
number_of_consumed_warnings (int): total number of warnings consumed by
the process.
number_of_produced_warnings (int): total number of warnings produced by
the process.
Returns:
bool: True if either number of warnings has increased.
... | [
"Updates",
"the",
"number",
"of",
"warnings",
"."
] | python | train |
sci-bots/pygtkhelpers | pygtkhelpers/ui/views/shapes_canvas_view.py | https://github.com/sci-bots/pygtkhelpers/blob/3a6e6d6340221c686229cd1c951d7537dae81b07/pygtkhelpers/ui/views/shapes_canvas_view.py#L236-L252 | def parse_args(args=None):
"""Parses arguments, returns (options, args)."""
import sys
from argparse import ArgumentParser
from path_helpers import path
if args is None:
args = sys.argv
parser = ArgumentParser(description='Example app for drawing shapes from '
... | [
"def",
"parse_args",
"(",
"args",
"=",
"None",
")",
":",
"import",
"sys",
"from",
"argparse",
"import",
"ArgumentParser",
"from",
"path_helpers",
"import",
"path",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
"argv",
"parser",
"=",
"ArgumentPa... | Parses arguments, returns (options, args). | [
"Parses",
"arguments",
"returns",
"(",
"options",
"args",
")",
"."
] | python | train |
pydata/xarray | xarray/core/common.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/common.py#L361-L382 | def assign_attrs(self, *args, **kwargs):
"""Assign new attrs to this object.
Returns a new object equivalent to self.attrs.update(*args, **kwargs).
Parameters
----------
args : positional arguments passed into ``attrs.update``.
kwargs : keyword arguments passed into ``a... | [
"def",
"assign_attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"self",
".",
"copy",
"(",
"deep",
"=",
"False",
")",
"out",
".",
"attrs",
".",
"update",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"retur... | Assign new attrs to this object.
Returns a new object equivalent to self.attrs.update(*args, **kwargs).
Parameters
----------
args : positional arguments passed into ``attrs.update``.
kwargs : keyword arguments passed into ``attrs.update``.
Returns
-------
... | [
"Assign",
"new",
"attrs",
"to",
"this",
"object",
"."
] | python | train |
spyder-ide/spyder | spyder/app/mainwindow.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/app/mainwindow.py#L2774-L2777 | def add_path_to_sys_path(self):
"""Add Spyder path to sys.path"""
for path in reversed(self.get_spyder_pythonpath()):
sys.path.insert(1, path) | [
"def",
"add_path_to_sys_path",
"(",
"self",
")",
":",
"for",
"path",
"in",
"reversed",
"(",
"self",
".",
"get_spyder_pythonpath",
"(",
")",
")",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"1",
",",
"path",
")"
] | Add Spyder path to sys.path | [
"Add",
"Spyder",
"path",
"to",
"sys",
".",
"path"
] | python | train |
DreamLab/VmShepherd | src/vmshepherd/iaas/abstract.py | https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/iaas/abstract.py#L26-L46 | async def create_vm(self, preset_name: str, image: str, flavor: str, security_groups: List=None,
userdata: Dict=None, key_name: str=None, availability_zone: str=None,
subnets: List=None) -> Any:
"""
Create (boot) a new server.
:arg string preset_n... | [
"async",
"def",
"create_vm",
"(",
"self",
",",
"preset_name",
":",
"str",
",",
"image",
":",
"str",
",",
"flavor",
":",
"str",
",",
"security_groups",
":",
"List",
"=",
"None",
",",
"userdata",
":",
"Dict",
"=",
"None",
",",
"key_name",
":",
"str",
"... | Create (boot) a new server.
:arg string preset_name: Name of vm group where vm is created.
:arg string image: Image name.
:arg string flavor: Flavor (or instance_type in AWS) name.
:arg list security_groups: A list of security group names.
:arg dict userdata: A dict of arbitrary... | [
"Create",
"(",
"boot",
")",
"a",
"new",
"server",
"."
] | python | train |
Fantomas42/django-blog-zinnia | zinnia/templatetags/zinnia.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/templatetags/zinnia.py#L424-L431 | def comment_admin_urlname(action):
"""
Return the admin URLs for the comment app used.
"""
comment = get_comment_model()
return 'admin:%s_%s_%s' % (
comment._meta.app_label, comment._meta.model_name,
action) | [
"def",
"comment_admin_urlname",
"(",
"action",
")",
":",
"comment",
"=",
"get_comment_model",
"(",
")",
"return",
"'admin:%s_%s_%s'",
"%",
"(",
"comment",
".",
"_meta",
".",
"app_label",
",",
"comment",
".",
"_meta",
".",
"model_name",
",",
"action",
")"
] | Return the admin URLs for the comment app used. | [
"Return",
"the",
"admin",
"URLs",
"for",
"the",
"comment",
"app",
"used",
"."
] | python | train |
michaelpb/omnic | omnic/utils/filesystem.py | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/utils/filesystem.py#L38-L47 | def recursive_hardlink_dirs(source_d, destination_d):
'''
Same as above, except creating hardlinks for all files
'''
func = os.link
if os.name == 'nt':
func = shutil.copy
if os.path.exists(destination_d):
os.rmdir(destination_d)
shutil.copytree(source_d, destination_d, copy_f... | [
"def",
"recursive_hardlink_dirs",
"(",
"source_d",
",",
"destination_d",
")",
":",
"func",
"=",
"os",
".",
"link",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"func",
"=",
"shutil",
".",
"copy",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"destination... | Same as above, except creating hardlinks for all files | [
"Same",
"as",
"above",
"except",
"creating",
"hardlinks",
"for",
"all",
"files"
] | python | train |
ludeeus/pycfdns | pycfdns/__init__.py | https://github.com/ludeeus/pycfdns/blob/0fd027be49d67250f85f2398d006a9409a7dae28/pycfdns/__init__.py#L26-L31 | def get_zoneID(self, headers, zone):
"""Get the zone id for the zone."""
zoneIDurl = self.BASE_URL + '?name=' + zone
zoneIDrequest = requests.get(zoneIDurl, headers=headers)
zoneID = zoneIDrequest.json()['result'][0]['id']
return zoneID | [
"def",
"get_zoneID",
"(",
"self",
",",
"headers",
",",
"zone",
")",
":",
"zoneIDurl",
"=",
"self",
".",
"BASE_URL",
"+",
"'?name='",
"+",
"zone",
"zoneIDrequest",
"=",
"requests",
".",
"get",
"(",
"zoneIDurl",
",",
"headers",
"=",
"headers",
")",
"zoneID... | Get the zone id for the zone. | [
"Get",
"the",
"zone",
"id",
"for",
"the",
"zone",
"."
] | python | train |
CalebBell/thermo | thermo/safety.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/safety.py#L968-L1019 | def UFL_mixture(ys=None, UFLs=None, CASRNs=None, AvailableMethods=False,
Method=None): # pragma: no cover
'''Inert gases are ignored.
This API is considered experimental, and is expected to be removed in a
future release in favor of a more complete object-oriented interface.
>>> UFL_m... | [
"def",
"UFL_mixture",
"(",
"ys",
"=",
"None",
",",
"UFLs",
"=",
"None",
",",
"CASRNs",
"=",
"None",
",",
"AvailableMethods",
"=",
"False",
",",
"Method",
"=",
"None",
")",
":",
"# pragma: no cover",
"def",
"list_methods",
"(",
")",
":",
"methods",
"=",
... | Inert gases are ignored.
This API is considered experimental, and is expected to be removed in a
future release in favor of a more complete object-oriented interface.
>>> UFL_mixture(ys=normalize([0.0024, 0.0061, 0.0015]), UFLs=[.075, .15, .32])
0.12927551844869378
>>> LFL_mixture(LFLs=[None, None... | [
"Inert",
"gases",
"are",
"ignored",
"."
] | python | valid |
flashingpumpkin/django-socialregistration | socialregistration/clients/oauth.py | https://github.com/flashingpumpkin/django-socialregistration/blob/9da9fb83c9bf79997ff81fe1378ab5ca3074b32b/socialregistration/clients/oauth.py#L241-L254 | def get_redirect_url(self, state='', **kwargs):
"""
Assemble the URL to where we'll be redirecting the user to to request
permissions.
"""
params = {
'response_type': 'code',
'client_id': self.client_id,
'redirect_uri': self.get_callback_url(**... | [
"def",
"get_redirect_url",
"(",
"self",
",",
"state",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'response_type'",
":",
"'code'",
",",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'redirect_uri'",
":",
"self",
".",
"get_cal... | Assemble the URL to where we'll be redirecting the user to to request
permissions. | [
"Assemble",
"the",
"URL",
"to",
"where",
"we",
"ll",
"be",
"redirecting",
"the",
"user",
"to",
"to",
"request",
"permissions",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/allen_brain.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L192-L260 | def _generator(tmp_dir, training, size=_BASE_EXAMPLE_IMAGE_SIZE,
training_fraction=0.95):
"""Base problem example generator for Allen Brain Atlas problems.
Args:
tmp_dir: str, a directory where raw example input data has been stored.
training: bool, whether the mode of operation is training... | [
"def",
"_generator",
"(",
"tmp_dir",
",",
"training",
",",
"size",
"=",
"_BASE_EXAMPLE_IMAGE_SIZE",
",",
"training_fraction",
"=",
"0.95",
")",
":",
"maybe_download_image_dataset",
"(",
"_IMAGE_IDS",
",",
"tmp_dir",
")",
"image_files",
"=",
"_get_case_file_paths",
"... | Base problem example generator for Allen Brain Atlas problems.
Args:
tmp_dir: str, a directory where raw example input data has been stored.
training: bool, whether the mode of operation is training (or,
alternatively, evaluation), determining whether examples in tmp_dir
prefixed with train or d... | [
"Base",
"problem",
"example",
"generator",
"for",
"Allen",
"Brain",
"Atlas",
"problems",
"."
] | python | train |
coumbole/mailscanner | mailscanner/reader.py | https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/reader.py#L35-L57 | def get_body(self, msg):
""" Extracts and returns the decoded body from an EmailMessage object"""
body = ""
charset = ""
if msg.is_multipart():
for part in msg.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition... | [
"def",
"get_body",
"(",
"self",
",",
"msg",
")",
":",
"body",
"=",
"\"\"",
"charset",
"=",
"\"\"",
"if",
"msg",
".",
"is_multipart",
"(",
")",
":",
"for",
"part",
"in",
"msg",
".",
"walk",
"(",
")",
":",
"ctype",
"=",
"part",
".",
"get_content_type... | Extracts and returns the decoded body from an EmailMessage object | [
"Extracts",
"and",
"returns",
"the",
"decoded",
"body",
"from",
"an",
"EmailMessage",
"object"
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/boore_atkinson_2011.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2011.py#L67-L81 | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# get mean and std using the superclass
mean, stddevs = super... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# get mean and std using the superclass",
"mean",
",",
"stddevs",
"=",
"super",
"(",
")",
".",
"get_mean_and_stddevs",
"(",
"sites",
... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | [
"See",
":",
"meth",
":",
"superclass",
"method",
"<",
".",
"base",
".",
"GroundShakingIntensityModel",
".",
"get_mean_and_stddevs",
">",
"for",
"spec",
"of",
"input",
"and",
"result",
"values",
"."
] | python | train |
seomoz/shovel | shovel/tasks.py | https://github.com/seomoz/shovel/blob/fc29232b2b8be33972f8fb498a91a67e334f057f/shovel/tasks.py#L165-L170 | def make(cls, obj):
'''Given a callable object, return a new callable object'''
try:
cls._cache.append(Task(obj))
except Exception:
logger.exception('Unable to make task for %s' % repr(obj)) | [
"def",
"make",
"(",
"cls",
",",
"obj",
")",
":",
"try",
":",
"cls",
".",
"_cache",
".",
"append",
"(",
"Task",
"(",
"obj",
")",
")",
"except",
"Exception",
":",
"logger",
".",
"exception",
"(",
"'Unable to make task for %s'",
"%",
"repr",
"(",
"obj",
... | Given a callable object, return a new callable object | [
"Given",
"a",
"callable",
"object",
"return",
"a",
"new",
"callable",
"object"
] | python | train |
Qiskit/qiskit-terra | qiskit/providers/basicaer/unitary_simulator.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/unitary_simulator.py#L144-L155 | def _validate_initial_unitary(self):
"""Validate an initial unitary matrix"""
# If initial unitary isn't set we don't need to validate
if self._initial_unitary is None:
return
# Check unitary is correct length for number of qubits
shape = np.shape(self._initial_unitar... | [
"def",
"_validate_initial_unitary",
"(",
"self",
")",
":",
"# If initial unitary isn't set we don't need to validate",
"if",
"self",
".",
"_initial_unitary",
"is",
"None",
":",
"return",
"# Check unitary is correct length for number of qubits",
"shape",
"=",
"np",
".",
"shape... | Validate an initial unitary matrix | [
"Validate",
"an",
"initial",
"unitary",
"matrix"
] | python | test |
inveniosoftware/invenio-files-rest | invenio_files_rest/models.py | https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/models.py#L832-L844 | def copy_contents(self, fileinstance, progress_callback=None,
chunk_size=None, **kwargs):
"""Copy this file instance into another file instance."""
if not fileinstance.readable:
raise ValueError('Source file instance is not readable.')
if not self.size == 0:
... | [
"def",
"copy_contents",
"(",
"self",
",",
"fileinstance",
",",
"progress_callback",
"=",
"None",
",",
"chunk_size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"fileinstance",
".",
"readable",
":",
"raise",
"ValueError",
"(",
"'Source file i... | Copy this file instance into another file instance. | [
"Copy",
"this",
"file",
"instance",
"into",
"another",
"file",
"instance",
"."
] | python | train |
numenta/htmresearch | htmresearch/frameworks/thalamus/thalamus.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/thalamus/thalamus.py#L282-L292 | def relayIndextoCoord(self, i):
"""
Map 1D cell index to a 2D coordinate
:param i: integer 1D cell index
:return: (x, y), a 2D coordinate
"""
x = i % self.relayWidth
y = i / self.relayWidth
return x, y | [
"def",
"relayIndextoCoord",
"(",
"self",
",",
"i",
")",
":",
"x",
"=",
"i",
"%",
"self",
".",
"relayWidth",
"y",
"=",
"i",
"/",
"self",
".",
"relayWidth",
"return",
"x",
",",
"y"
] | Map 1D cell index to a 2D coordinate
:param i: integer 1D cell index
:return: (x, y), a 2D coordinate | [
"Map",
"1D",
"cell",
"index",
"to",
"a",
"2D",
"coordinate"
] | python | train |
google/grumpy | third_party/stdlib/base64.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/base64.py#L293-L305 | def encode(input, output):
"""Encode a file."""
while True:
s = input.read(MAXBINSIZE)
if not s:
break
while len(s) < MAXBINSIZE:
ns = input.read(MAXBINSIZE-len(s))
if not ns:
break
s += ns
line = binascii.b2a_base64... | [
"def",
"encode",
"(",
"input",
",",
"output",
")",
":",
"while",
"True",
":",
"s",
"=",
"input",
".",
"read",
"(",
"MAXBINSIZE",
")",
"if",
"not",
"s",
":",
"break",
"while",
"len",
"(",
"s",
")",
"<",
"MAXBINSIZE",
":",
"ns",
"=",
"input",
".",
... | Encode a file. | [
"Encode",
"a",
"file",
"."
] | python | valid |
bgyori/pykqml | kqml/kqml_list.py | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L74-L97 | def gets(self, keyword):
"""Return the element of the list after the given keyword as string.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is ad... | [
"def",
"gets",
"(",
"self",
",",
"keyword",
")",
":",
"param",
"=",
"self",
".",
"get",
"(",
"keyword",
")",
"if",
"param",
"is",
"not",
"None",
":",
"return",
"safe_decode",
"(",
"param",
".",
"string_value",
"(",
")",
")",
"return",
"None"
] | Return the element of the list after the given keyword as string.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" wi... | [
"Return",
"the",
"element",
"of",
"the",
"list",
"after",
"the",
"given",
"keyword",
"as",
"string",
"."
] | python | train |
dnanexus/dx-toolkit | src/python/dxpy/bindings/dxproject.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/bindings/dxproject.py#L401-L417 | def decrease_perms(self, member, level, **kwargs):
"""
:param member: Username (of the form "user-USERNAME") of the project member whose permissions will be decreased.
:type member: string
:param level: Permissions level that the member will have after this operation (None, "VIEW", "UPLO... | [
"def",
"decrease_perms",
"(",
"self",
",",
"member",
",",
"level",
",",
"*",
"*",
"kwargs",
")",
":",
"input_hash",
"=",
"{",
"}",
"input_hash",
"[",
"member",
"]",
"=",
"level",
"return",
"dxpy",
".",
"api",
".",
"project_decrease_permissions",
"(",
"se... | :param member: Username (of the form "user-USERNAME") of the project member whose permissions will be decreased.
:type member: string
:param level: Permissions level that the member will have after this operation (None, "VIEW", "UPLOAD", or "CONTRIBUTE")
:type level: string or None
Decr... | [
":",
"param",
"member",
":",
"Username",
"(",
"of",
"the",
"form",
"user",
"-",
"USERNAME",
")",
"of",
"the",
"project",
"member",
"whose",
"permissions",
"will",
"be",
"decreased",
".",
":",
"type",
"member",
":",
"string",
":",
"param",
"level",
":",
... | python | train |
happyleavesaoc/python-snapcast | snapcast/client/__init__.py | https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/client/__init__.py#L71-L77 | def _read_socket(self):
""" Process incoming messages from socket. """
while True:
base_bytes = self._socket.recv(BASE_SIZE)
base = basemessage.parse(base_bytes)
payload_bytes = self._socket.recv(base.payload_length)
self._handle_message(packet.parse(base_... | [
"def",
"_read_socket",
"(",
"self",
")",
":",
"while",
"True",
":",
"base_bytes",
"=",
"self",
".",
"_socket",
".",
"recv",
"(",
"BASE_SIZE",
")",
"base",
"=",
"basemessage",
".",
"parse",
"(",
"base_bytes",
")",
"payload_bytes",
"=",
"self",
".",
"_sock... | Process incoming messages from socket. | [
"Process",
"incoming",
"messages",
"from",
"socket",
"."
] | python | train |
alfred82santa/dirty-models | dirty_models/model_types.py | https://github.com/alfred82santa/dirty-models/blob/354becdb751b21f673515eae928c256c7e923c50/dirty_models/model_types.py#L300-L314 | def export_original_data(self):
"""
Retrieves the original_data
"""
def export_field(value):
"""
Export item
"""
try:
return value.export_original_data()
except AttributeError:
return value
... | [
"def",
"export_original_data",
"(",
"self",
")",
":",
"def",
"export_field",
"(",
"value",
")",
":",
"\"\"\"\n Export item\n \"\"\"",
"try",
":",
"return",
"value",
".",
"export_original_data",
"(",
")",
"except",
"AttributeError",
":",
"return",... | Retrieves the original_data | [
"Retrieves",
"the",
"original_data"
] | python | train |
gwastro/pycbc | pycbc/workflow/jobsetup.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/jobsetup.py#L955-L996 | def create_nodata_node(self, valid_seg, tags=None):
""" A simplified version of create_node that creates a node that does not
need to read in data.
Parameters
-----------
valid_seg : glue.segment
The segment over which to declare the node valid. Usually this
... | [
"def",
"create_nodata_node",
"(",
"self",
",",
"valid_seg",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"node",
"=",
"Node",
"(",
"self",
")",
"# Set the output file",
"# Add the PSD file if needed",
"if",
"s... | A simplified version of create_node that creates a node that does not
need to read in data.
Parameters
-----------
valid_seg : glue.segment
The segment over which to declare the node valid. Usually this
would be the duration of the analysis.
Returns
... | [
"A",
"simplified",
"version",
"of",
"create_node",
"that",
"creates",
"a",
"node",
"that",
"does",
"not",
"need",
"to",
"read",
"in",
"data",
"."
] | python | train |
pytroll/satpy | satpy/demo/__init__.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/demo/__init__.py#L71-L98 | def get_us_midlatitude_cyclone_abi(base_dir='.', method=None, force=False):
"""Get GOES-16 ABI (CONUS sector) data from 2019-03-14 00:00Z.
Args:
base_dir (str): Base directory for downloaded files.
method (str): Force download method for the data if not already cached.
Allowed optio... | [
"def",
"get_us_midlatitude_cyclone_abi",
"(",
"base_dir",
"=",
"'.'",
",",
"method",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"method",
"is",
"None",
":",
"method",
"=",
"'gcsfs'",
"if",
"method",
"not",
"in",
"[",
"'gcsfs'",
"]",
":",
... | Get GOES-16 ABI (CONUS sector) data from 2019-03-14 00:00Z.
Args:
base_dir (str): Base directory for downloaded files.
method (str): Force download method for the data if not already cached.
Allowed options are: 'gcsfs'. Default of ``None`` will
choose the best method based ... | [
"Get",
"GOES",
"-",
"16",
"ABI",
"(",
"CONUS",
"sector",
")",
"data",
"from",
"2019",
"-",
"03",
"-",
"14",
"00",
":",
"00Z",
"."
] | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/textio.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/textio.py#L1009-L1015 | def bk_default(cls):
"Make the current background color the default."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
#wAttributes |= win32.BACKGROUND_BLACK
wAttributes &= ~win32.BACKGROUND_INTENSITY
cls._set_text_attributes(wAttributes) | [
"def",
"bk_default",
"(",
"cls",
")",
":",
"wAttributes",
"=",
"cls",
".",
"_get_text_attributes",
"(",
")",
"wAttributes",
"&=",
"~",
"win32",
".",
"BACKGROUND_MASK",
"#wAttributes |= win32.BACKGROUND_BLACK",
"wAttributes",
"&=",
"~",
"win32",
".",
"BACKGROUND_INTE... | Make the current background color the default. | [
"Make",
"the",
"current",
"background",
"color",
"the",
"default",
"."
] | python | train |
linkhub-sdk/popbill.py | popbill/statementService.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/statementService.py#L523-L541 | def getFiles(self, CorpNum, ItemCode, MgtKey):
""" 첨부파일 목록 확인
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
MgtKey : 파트너 문서관리... | [
"def",
"getFiles",
"(",
"self",
",",
"CorpNum",
",",
"ItemCode",
",",
"MgtKey",
")",
":",
"if",
"MgtKey",
"==",
"None",
"or",
"MgtKey",
"==",
"\"\"",
":",
"raise",
"PopbillException",
"(",
"-",
"99999999",
",",
"\"관리번호가 입력되지 않았습니다.\")\r",
"",
"if",
"ItemCo... | 첨부파일 목록 확인
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
MgtKey : 파트너 문서관리번호
return
첨부파일 목록 as List
... | [
"첨부파일",
"목록",
"확인",
"args",
"CorpNum",
":",
"팝빌회원",
"사업자번호",
"ItemCode",
":",
"명세서",
"종류",
"코드",
"[",
"121",
"-",
"거래명세서",
"]",
"[",
"122",
"-",
"청구서",
"]",
"[",
"123",
"-",
"견적서",
"]",
"[",
"124",
"-",
"발주서",
"]",
"[",
"125",
"-",
"입금표",
"]"... | python | train |
dancsalo/TensorBase | tensorbase/base.py | https://github.com/dancsalo/TensorBase/blob/3d42a326452bd03427034916ff2fb90730020204/tensorbase/base.py#L218-L230 | def load_config_yaml(self, flags, config_dict):
""" Load config dict and yaml dict and then override both with flags dict. """
if config_dict is None:
print('Config File not specified. Using only input flags.')
return flags
try:
config_yaml_dict = self.cfg_fro... | [
"def",
"load_config_yaml",
"(",
"self",
",",
"flags",
",",
"config_dict",
")",
":",
"if",
"config_dict",
"is",
"None",
":",
"print",
"(",
"'Config File not specified. Using only input flags.'",
")",
"return",
"flags",
"try",
":",
"config_yaml_dict",
"=",
"self",
"... | Load config dict and yaml dict and then override both with flags dict. | [
"Load",
"config",
"dict",
"and",
"yaml",
"dict",
"and",
"then",
"override",
"both",
"with",
"flags",
"dict",
"."
] | python | train |
inasafe/inasafe | safe/impact_function/multi_exposure_wrapper.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/impact_function/multi_exposure_wrapper.py#L388-L395 | def add_exposure(self, layer):
"""Add an exposure layer in the analysis.
:param layer: An exposure layer to be used for the analysis.
:type layer: QgsMapLayer
"""
self._exposures.append(layer)
self._is_ready = False | [
"def",
"add_exposure",
"(",
"self",
",",
"layer",
")",
":",
"self",
".",
"_exposures",
".",
"append",
"(",
"layer",
")",
"self",
".",
"_is_ready",
"=",
"False"
] | Add an exposure layer in the analysis.
:param layer: An exposure layer to be used for the analysis.
:type layer: QgsMapLayer | [
"Add",
"an",
"exposure",
"layer",
"in",
"the",
"analysis",
"."
] | python | train |
ray-project/ray | python/ray/services.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L424-L435 | def _autodetect_num_gpus():
"""Attempt to detect the number of GPUs on this machine.
TODO(rkn): This currently assumes Nvidia GPUs and Linux.
Returns:
The number of GPUs if any were detected, otherwise 0.
"""
proc_gpus_path = "/proc/driver/nvidia/gpus"
if os.path.isdir(proc_gpus_path):... | [
"def",
"_autodetect_num_gpus",
"(",
")",
":",
"proc_gpus_path",
"=",
"\"/proc/driver/nvidia/gpus\"",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"proc_gpus_path",
")",
":",
"return",
"len",
"(",
"os",
".",
"listdir",
"(",
"proc_gpus_path",
")",
")",
"return",
... | Attempt to detect the number of GPUs on this machine.
TODO(rkn): This currently assumes Nvidia GPUs and Linux.
Returns:
The number of GPUs if any were detected, otherwise 0. | [
"Attempt",
"to",
"detect",
"the",
"number",
"of",
"GPUs",
"on",
"this",
"machine",
"."
] | python | train |
allenai/allennlp | allennlp/tools/drop_eval.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/tools/drop_eval.py#L167-L226 | def evaluate_json(annotations: Dict[str, Any], predicted_answers: Dict[str, Any]) -> Tuple[float, float]:
"""
Takes gold annotations and predicted answers and evaluates the predictions for each question
in the gold annotations. Both JSON dictionaries must have query_id keys, which are used to
match pr... | [
"def",
"evaluate_json",
"(",
"annotations",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"predicted_answers",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"instance_exact_match",
"=",
"[",
"]",
... | Takes gold annotations and predicted answers and evaluates the predictions for each question
in the gold annotations. Both JSON dictionaries must have query_id keys, which are used to
match predictions to gold annotations (note that these are somewhat deep in the JSON for the
gold annotations, but must be... | [
"Takes",
"gold",
"annotations",
"and",
"predicted",
"answers",
"and",
"evaluates",
"the",
"predictions",
"for",
"each",
"question",
"in",
"the",
"gold",
"annotations",
".",
"Both",
"JSON",
"dictionaries",
"must",
"have",
"query_id",
"keys",
"which",
"are",
"used... | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/dir2.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/dir2.py#L34-L73 | def dir2(obj):
"""dir2(obj) -> list of strings
Extended version of the Python builtin dir(), which does a few extra
checks, and supports common objects with unusual internals that confuse
dir(), such as Traits and PyCrust.
This version is guaranteed to return only a list of true strings, whereas
... | [
"def",
"dir2",
"(",
"obj",
")",
":",
"# Start building the attribute list via dir(), and then complete it",
"# with a few extra special-purpose calls.",
"words",
"=",
"set",
"(",
"dir",
"(",
"obj",
")",
")",
"if",
"hasattr",
"(",
"obj",
",",
"'__class__'",
")",
":",
... | dir2(obj) -> list of strings
Extended version of the Python builtin dir(), which does a few extra
checks, and supports common objects with unusual internals that confuse
dir(), such as Traits and PyCrust.
This version is guaranteed to return only a list of true strings, whereas
dir() returns anyth... | [
"dir2",
"(",
"obj",
")",
"-",
">",
"list",
"of",
"strings"
] | python | test |
volafiled/python-volapi | volapi/volapi.py | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/volapi.py#L74-L89 | def connect(self, username, checksum, password=None, key=None):
"""Connect to websocket through asyncio http interface"""
ws_url = (
f"{BASE_WS_URL}?room={self.room.room_id}&cs={checksum}&nick={username}"
f"&rn={random_id(6)}&t={int(time.time() * 1000)}&transport=websocket&EIO=3... | [
"def",
"connect",
"(",
"self",
",",
"username",
",",
"checksum",
",",
"password",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"ws_url",
"=",
"(",
"f\"{BASE_WS_URL}?room={self.room.room_id}&cs={checksum}&nick={username}\"",
"f\"&rn={random_id(6)}&t={int(time.time() * 1... | Connect to websocket through asyncio http interface | [
"Connect",
"to",
"websocket",
"through",
"asyncio",
"http",
"interface"
] | python | train |
brmscheiner/ideogram | ideogram/polarfract/polarfract.py | https://github.com/brmscheiner/ideogram/blob/422bf566c51fd56f7bbb6e75b16d18d52b4c7568/ideogram/polarfract/polarfract.py#L23-L32 | def calcPosition(self,parent_circle):
''' Position the circle tangent to the parent circle with the line connecting the centers of the two circles meeting the x axis at angle theta. '''
if r not in self:
raise AttributeError("radius must be calculated before position.")
if theta not ... | [
"def",
"calcPosition",
"(",
"self",
",",
"parent_circle",
")",
":",
"if",
"r",
"not",
"in",
"self",
":",
"raise",
"AttributeError",
"(",
"\"radius must be calculated before position.\"",
")",
"if",
"theta",
"not",
"in",
"self",
":",
"raise",
"AttributeError",
"(... | Position the circle tangent to the parent circle with the line connecting the centers of the two circles meeting the x axis at angle theta. | [
"Position",
"the",
"circle",
"tangent",
"to",
"the",
"parent",
"circle",
"with",
"the",
"line",
"connecting",
"the",
"centers",
"of",
"the",
"two",
"circles",
"meeting",
"the",
"x",
"axis",
"at",
"angle",
"theta",
"."
] | python | train |
combust/mleap | python/mleap/sklearn/preprocessing/data.py | https://github.com/combust/mleap/blob/dc6b79db03ec27a0ba08b289842551e73d517ab3/python/mleap/sklearn/preprocessing/data.py#L395-L415 | def transform(self, y):
"""Transform labels to normalized encoding.
Parameters
----------
y : array-like of shape [n_samples]
Target values.
Returns
-------
y : array-like of shape [n_samples]
"""
check_is_fitted(self, 'classes_')
... | [
"def",
"transform",
"(",
"self",
",",
"y",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"'classes_'",
")",
"y",
"=",
"column_or_1d",
"(",
"y",
",",
"warn",
"=",
"True",
")",
"classes",
"=",
"np",
".",
"unique",
"(",
"y",
")",
"_check_numpy_unicode_bu... | Transform labels to normalized encoding.
Parameters
----------
y : array-like of shape [n_samples]
Target values.
Returns
-------
y : array-like of shape [n_samples] | [
"Transform",
"labels",
"to",
"normalized",
"encoding",
"."
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/streambase.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L239-L249 | def event(self, event): # pylint: disable-msg=R0201
"""Handle a stream event.
Called when connection state is changed.
Should not be called with self.lock acquired!
"""
event.stream = self
logger.debug(u"Stream event: {0}".format(event))
self.settings["event_que... | [
"def",
"event",
"(",
"self",
",",
"event",
")",
":",
"# pylint: disable-msg=R0201",
"event",
".",
"stream",
"=",
"self",
"logger",
".",
"debug",
"(",
"u\"Stream event: {0}\"",
".",
"format",
"(",
"event",
")",
")",
"self",
".",
"settings",
"[",
"\"event_queu... | Handle a stream event.
Called when connection state is changed.
Should not be called with self.lock acquired! | [
"Handle",
"a",
"stream",
"event",
"."
] | python | valid |
manns/pyspread | pyspread/src/gui/_grid.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_grid.py#L422-L435 | def ForceRefresh(self, *args, **kwargs):
"""Refresh hook"""
wx.grid.Grid.ForceRefresh(self, *args, **kwargs)
for video_cell_key in self.grid_renderer.video_cells:
if video_cell_key[2] == self.current_table:
video_cell = self.grid_renderer.video_cells[video_cell_key]... | [
"def",
"ForceRefresh",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"wx",
".",
"grid",
".",
"Grid",
".",
"ForceRefresh",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"video_cell_key",
"in",
"self",
".",
... | Refresh hook | [
"Refresh",
"hook"
] | python | train |
aiogram/aiogram | aiogram/utils/auth_widget.py | https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/auth_widget.py#L12-L24 | def generate_hash(data: dict, token: str) -> str:
"""
Generate secret hash
:param data:
:param token:
:return:
"""
secret = hashlib.sha256()
secret.update(token.encode('utf-8'))
sorted_params = collections.OrderedDict(sorted(data.items()))
msg = '\n'.join("{}={}".format(k, v) fo... | [
"def",
"generate_hash",
"(",
"data",
":",
"dict",
",",
"token",
":",
"str",
")",
"->",
"str",
":",
"secret",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"secret",
".",
"update",
"(",
"token",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"sorted_params",
"="... | Generate secret hash
:param data:
:param token:
:return: | [
"Generate",
"secret",
"hash"
] | python | train |
numba/llvmlite | llvmlite/binding/value.py | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/value.py#L256-L266 | def arguments(self):
"""
Return an iterator over this function's arguments.
The iterator will yield a ValueRef for each argument.
"""
if not self.is_function:
raise ValueError('expected function value, got %s' % (self._kind,))
it = ffi.lib.LLVMPY_FunctionArgum... | [
"def",
"arguments",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_function",
":",
"raise",
"ValueError",
"(",
"'expected function value, got %s'",
"%",
"(",
"self",
".",
"_kind",
",",
")",
")",
"it",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_FunctionArgu... | Return an iterator over this function's arguments.
The iterator will yield a ValueRef for each argument. | [
"Return",
"an",
"iterator",
"over",
"this",
"function",
"s",
"arguments",
".",
"The",
"iterator",
"will",
"yield",
"a",
"ValueRef",
"for",
"each",
"argument",
"."
] | python | train |
funilrys/PyFunceble | PyFunceble/database.py | https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/database.py#L816-L844 | def get_expiration_date(self):
"""
Get the expiration date from the database.
:return: The expiration date from the database.
:rtype: str|None
"""
if self._authorization() and self.is_in_database() and not self.is_time_older():
# * We are authorized to work.... | [
"def",
"get_expiration_date",
"(",
"self",
")",
":",
"if",
"self",
".",
"_authorization",
"(",
")",
"and",
"self",
".",
"is_in_database",
"(",
")",
"and",
"not",
"self",
".",
"is_time_older",
"(",
")",
":",
"# * We are authorized to work.",
"# and",
"# * The e... | Get the expiration date from the database.
:return: The expiration date from the database.
:rtype: str|None | [
"Get",
"the",
"expiration",
"date",
"from",
"the",
"database",
"."
] | python | test |
wonambi-python/wonambi | wonambi/widgets/analysis.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/analysis.py#L1911-L1982 | def report_fooof(self, x, y, suffix):
"""Create FOOOF (fitting oscillations and 1/f) report.
Parameters
----------
x : ndarray
vector with frequencies
y : ndarray
vector with amplitudes
"""
filename = splitext(self.filename)[0] + '_' + suf... | [
"def",
"report_fooof",
"(",
"self",
",",
"x",
",",
"y",
",",
"suffix",
")",
":",
"filename",
"=",
"splitext",
"(",
"self",
".",
"filename",
")",
"[",
"0",
"]",
"+",
"'_'",
"+",
"suffix",
"+",
"'_fooof.csv'",
"freq",
"=",
"self",
".",
"frequency",
"... | Create FOOOF (fitting oscillations and 1/f) report.
Parameters
----------
x : ndarray
vector with frequencies
y : ndarray
vector with amplitudes | [
"Create",
"FOOOF",
"(",
"fitting",
"oscillations",
"and",
"1",
"/",
"f",
")",
"report",
"."
] | python | train |
cfhamlet/os-docid | src/os_docid/x.py | https://github.com/cfhamlet/os-docid/blob/d3730aa118182f903b540ea738cd47c83f6b5e89/src/os_docid/x.py#L172-L229 | def docid(url, encoding='ascii'):
"""Get DocID from URL.
DocID generation depends on bytes of the URL string.
So, if non-ascii charactors in the URL, encoding should
be considered properly.
Args:
url (str or bytes): Pre-encoded bytes or string will be encoded with the
'encoding... | [
"def",
"docid",
"(",
"url",
",",
"encoding",
"=",
"'ascii'",
")",
":",
"if",
"not",
"isinstance",
"(",
"url",
",",
"bytes",
")",
":",
"url",
"=",
"url",
".",
"encode",
"(",
"encoding",
")",
"parser",
"=",
"_URL_PARSER",
"idx",
"=",
"0",
"for",
"_c"... | Get DocID from URL.
DocID generation depends on bytes of the URL string.
So, if non-ascii charactors in the URL, encoding should
be considered properly.
Args:
url (str or bytes): Pre-encoded bytes or string will be encoded with the
'encoding' argument.
encoding (str, option... | [
"Get",
"DocID",
"from",
"URL",
"."
] | python | train |
Fizzadar/pyinfra | pyinfra/modules/apt.py | https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/apt.py#L188-L213 | def update(state, host, cache_time=None, touch_periodic=False):
'''
Updates apt repos.
+ cache_time: cache updates for this many seconds
+ touch_periodic: touch ``/var/lib/apt/periodic/update-success-stamp`` after update
'''
# If cache_time check when apt was last updated, prevent updates if w... | [
"def",
"update",
"(",
"state",
",",
"host",
",",
"cache_time",
"=",
"None",
",",
"touch_periodic",
"=",
"False",
")",
":",
"# If cache_time check when apt was last updated, prevent updates if within time",
"if",
"cache_time",
":",
"# Ubuntu provides this handy file",
"cache... | Updates apt repos.
+ cache_time: cache updates for this many seconds
+ touch_periodic: touch ``/var/lib/apt/periodic/update-success-stamp`` after update | [
"Updates",
"apt",
"repos",
"."
] | python | train |
jspricke/python-icstask | icstask.py | https://github.com/jspricke/python-icstask/blob/0802233cca569c2174bd96aed0682d04a2a63790/icstask.py#L191-L267 | def to_task(self, vtodo, project=None, uuid=None):
"""Add or modify a task from vTodo to Taskwarrior
vtodo -- the vTodo to add
project -- the project to add (see get_filesnames() as well)
uuid -- the UID of the task in Taskwarrior
"""
task = {}
if project and pro... | [
"def",
"to_task",
"(",
"self",
",",
"vtodo",
",",
"project",
"=",
"None",
",",
"uuid",
"=",
"None",
")",
":",
"task",
"=",
"{",
"}",
"if",
"project",
"and",
"project",
"!=",
"'all_projects'",
"and",
"project",
"!=",
"'unaffiliated'",
":",
"task",
"[",
... | Add or modify a task from vTodo to Taskwarrior
vtodo -- the vTodo to add
project -- the project to add (see get_filesnames() as well)
uuid -- the UID of the task in Taskwarrior | [
"Add",
"or",
"modify",
"a",
"task",
"from",
"vTodo",
"to",
"Taskwarrior",
"vtodo",
"--",
"the",
"vTodo",
"to",
"add",
"project",
"--",
"the",
"project",
"to",
"add",
"(",
"see",
"get_filesnames",
"()",
"as",
"well",
")",
"uuid",
"--",
"the",
"UID",
"of... | python | train |
hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L1789-L1806 | def get_diff_text(old, new, filename):
"""Return text of unified diff between old and new."""
newline = '\n'
diff = difflib.unified_diff(
old, new,
'original/' + filename,
'fixed/' + filename,
lineterm=newline)
text = ''
for line in diff:
text += line
... | [
"def",
"get_diff_text",
"(",
"old",
",",
"new",
",",
"filename",
")",
":",
"newline",
"=",
"'\\n'",
"diff",
"=",
"difflib",
".",
"unified_diff",
"(",
"old",
",",
"new",
",",
"'original/'",
"+",
"filename",
",",
"'fixed/'",
"+",
"filename",
",",
"lineterm... | Return text of unified diff between old and new. | [
"Return",
"text",
"of",
"unified",
"diff",
"between",
"old",
"and",
"new",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_zone.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_zone.py#L41-L52 | def zoning_defined_configuration_zone_zone_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
zoning = ET.SubElement(config, "zoning", xmlns="urn:brocade.com:mgmt:brocade-zone")
defined_configuration = ET.SubElement(zoning, "defined-configuration")
... | [
"def",
"zoning_defined_configuration_zone_zone_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"zoning",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"zoning\"",
",",
"xmlns",
"=",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
aio-libs/aiohttp | aiohttp/cookiejar.py | https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/cookiejar.py#L113-L186 | def update_cookies(self,
cookies: LooseCookies,
response_url: URL=URL()) -> None:
"""Update cookies."""
hostname = response_url.raw_host
if not self._unsafe and is_ip_address(hostname):
# Don't accept cookies from IPs
return
... | [
"def",
"update_cookies",
"(",
"self",
",",
"cookies",
":",
"LooseCookies",
",",
"response_url",
":",
"URL",
"=",
"URL",
"(",
")",
")",
"->",
"None",
":",
"hostname",
"=",
"response_url",
".",
"raw_host",
"if",
"not",
"self",
".",
"_unsafe",
"and",
"is_ip... | Update cookies. | [
"Update",
"cookies",
"."
] | python | train |
bachya/pyairvisual | pyairvisual/api.py | https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/api.py#L40-L45 | async def nearest_city(
self,
latitude: Union[float, str] = None,
longitude: Union[float, str] = None) -> dict:
"""Return data from nearest city (IP or coordinates)."""
return await self._nearest('city', latitude, longitude) | [
"async",
"def",
"nearest_city",
"(",
"self",
",",
"latitude",
":",
"Union",
"[",
"float",
",",
"str",
"]",
"=",
"None",
",",
"longitude",
":",
"Union",
"[",
"float",
",",
"str",
"]",
"=",
"None",
")",
"->",
"dict",
":",
"return",
"await",
"self",
"... | Return data from nearest city (IP or coordinates). | [
"Return",
"data",
"from",
"nearest",
"city",
"(",
"IP",
"or",
"coordinates",
")",
"."
] | python | train |
SBRG/ssbio | ssbio/protein/sequence/utils/blast.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/utils/blast.py#L135-L177 | def print_run_bidirectional_blast(reference, other_genome, dbtype, outdir):
"""Write torque submission files for running bidirectional blast on a server and print execution command.
Args:
reference (str): Path to "reference" genome, aka your "base strain"
other_genome (str): Path to other genom... | [
"def",
"print_run_bidirectional_blast",
"(",
"reference",
",",
"other_genome",
",",
"dbtype",
",",
"outdir",
")",
":",
"# TODO: add force_rerun option",
"if",
"dbtype",
"==",
"'nucl'",
":",
"command",
"=",
"'blastn'",
"elif",
"dbtype",
"==",
"'prot'",
":",
"comman... | Write torque submission files for running bidirectional blast on a server and print execution command.
Args:
reference (str): Path to "reference" genome, aka your "base strain"
other_genome (str): Path to other genome which will be BLASTed to the reference
dbtype (str): "nucl" or "prot" - w... | [
"Write",
"torque",
"submission",
"files",
"for",
"running",
"bidirectional",
"blast",
"on",
"a",
"server",
"and",
"print",
"execution",
"command",
"."
] | python | train |
SatelliteQE/nailgun | nailgun/entities.py | https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entities.py#L7427-L7461 | def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
This method contains a workaround for `Bugzilla #1202917`_.
Most entities are uniquely identified by an ID. ``System`` is a bit
different: it has both an ID and a UUID, and the UUID is used to
uniquely... | [
"def",
"path",
"(",
"self",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"==",
"'subscriptions'",
":",
"return",
"'{0}/{1}/{2}'",
".",
"format",
"(",
"super",
"(",
"System",
",",
"self",
")",
".",
"path",
"(",
"'base'",
")",
",",
"self",
".",
... | Extend ``nailgun.entity_mixins.Entity.path``.
This method contains a workaround for `Bugzilla #1202917`_.
Most entities are uniquely identified by an ID. ``System`` is a bit
different: it has both an ID and a UUID, and the UUID is used to
uniquely identify a ``System``.
Return... | [
"Extend",
"nailgun",
".",
"entity_mixins",
".",
"Entity",
".",
"path",
"."
] | python | train |
econ-ark/HARK | HARK/utilities.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/utilities.py#L524-L552 | def approxMeanOneLognormal(N, sigma=1.0, **kwargs):
'''
Calculate a discrete approximation to a mean one lognormal distribution.
Based on function approxLognormal; see that function's documentation for
further notes.
Parameters
----------
N : int
Size of discrete space vector to be ... | [
"def",
"approxMeanOneLognormal",
"(",
"N",
",",
"sigma",
"=",
"1.0",
",",
"*",
"*",
"kwargs",
")",
":",
"mu_adj",
"=",
"-",
"0.5",
"*",
"sigma",
"**",
"2",
"pmf",
",",
"X",
"=",
"approxLognormal",
"(",
"N",
"=",
"N",
",",
"mu",
"=",
"mu_adj",
","... | Calculate a discrete approximation to a mean one lognormal distribution.
Based on function approxLognormal; see that function's documentation for
further notes.
Parameters
----------
N : int
Size of discrete space vector to be returned.
sigma : float
standard deviation associate... | [
"Calculate",
"a",
"discrete",
"approximation",
"to",
"a",
"mean",
"one",
"lognormal",
"distribution",
".",
"Based",
"on",
"function",
"approxLognormal",
";",
"see",
"that",
"function",
"s",
"documentation",
"for",
"further",
"notes",
"."
] | python | train |
pudo/googlesheets | googlesheets/sheet.py | https://github.com/pudo/googlesheets/blob/c38725d79bfe048c0519a674019ba313dfc5bfb0/googlesheets/sheet.py#L61-L70 | def headers(self):
""" Return the name of all headers currently defined for the
table. """
if self._headers is None:
query = CellQuery()
query.max_row = '1'
feed = self._service.GetCellsFeed(self._ss.id, self.id,
q... | [
"def",
"headers",
"(",
"self",
")",
":",
"if",
"self",
".",
"_headers",
"is",
"None",
":",
"query",
"=",
"CellQuery",
"(",
")",
"query",
".",
"max_row",
"=",
"'1'",
"feed",
"=",
"self",
".",
"_service",
".",
"GetCellsFeed",
"(",
"self",
".",
"_ss",
... | Return the name of all headers currently defined for the
table. | [
"Return",
"the",
"name",
"of",
"all",
"headers",
"currently",
"defined",
"for",
"the",
"table",
"."
] | python | train |
tanghaibao/goatools | goatools/obo_parser.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L461-L474 | def query_term(self, term, verbose=False):
"""Given a GO ID, return GO object."""
if term not in self:
sys.stderr.write("Term %s not found!\n" % term)
return
rec = self[term]
if verbose:
print(rec)
sys.stderr.write("all parents: {}\n".form... | [
"def",
"query_term",
"(",
"self",
",",
"term",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"term",
"not",
"in",
"self",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Term %s not found!\\n\"",
"%",
"term",
")",
"return",
"rec",
"=",
"self",
"[",
... | Given a GO ID, return GO object. | [
"Given",
"a",
"GO",
"ID",
"return",
"GO",
"object",
"."
] | python | train |
LordSputnik/mutagen | mutagen/ogg.py | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/ogg.py#L454-L469 | def load(self, filename):
"""Load file information from a filename."""
self.filename = filename
fileobj = open(filename, "rb")
try:
try:
self.info = self._Info(fileobj)
self.tags = self._Tags(fileobj, self.info)
self.info._post... | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"filename",
"=",
"filename",
"fileobj",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"try",
":",
"try",
":",
"self",
".",
"info",
"=",
"self",
".",
"_Info",
"(",
"fileobj",
")... | Load file information from a filename. | [
"Load",
"file",
"information",
"from",
"a",
"filename",
"."
] | python | test |
konstantint/matplotlib-venn | matplotlib_venn/_arc.py | https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_arc.py#L134-L151 | def segment_area(self):
'''Returns the area of the corresponding arc segment.
>>> Arc((0,0), 2, 0, 360, True).segment_area()
12.566...
>>> Arc((0,0), 2, 0, 180, True).segment_area()
6.283...
>>> Arc((0,0), 2, 0, 90, True).segment_area()
1.14159...
... | [
"def",
"segment_area",
"(",
"self",
")",
":",
"theta",
"=",
"self",
".",
"length_radians",
"(",
")",
"return",
"self",
".",
"radius",
"**",
"2",
"/",
"2",
"*",
"(",
"theta",
"-",
"np",
".",
"sin",
"(",
"theta",
")",
")"
] | Returns the area of the corresponding arc segment.
>>> Arc((0,0), 2, 0, 360, True).segment_area()
12.566...
>>> Arc((0,0), 2, 0, 180, True).segment_area()
6.283...
>>> Arc((0,0), 2, 0, 90, True).segment_area()
1.14159...
>>> Arc((0,0), 2, 0, 90, False).se... | [
"Returns",
"the",
"area",
"of",
"the",
"corresponding",
"arc",
"segment",
".",
">>>",
"Arc",
"((",
"0",
"0",
")",
"2",
"0",
"360",
"True",
")",
".",
"segment_area",
"()",
"12",
".",
"566",
"...",
">>>",
"Arc",
"((",
"0",
"0",
")",
"2",
"0",
"180"... | python | train |
ellmetha/django-machina | machina/apps/forum_conversation/managers.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/managers.py#L13-L17 | def get_queryset(self):
""" Returns all the approved topics or posts. """
qs = super().get_queryset()
qs = qs.filter(approved=True)
return qs | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"super",
"(",
")",
".",
"get_queryset",
"(",
")",
"qs",
"=",
"qs",
".",
"filter",
"(",
"approved",
"=",
"True",
")",
"return",
"qs"
] | Returns all the approved topics or posts. | [
"Returns",
"all",
"the",
"approved",
"topics",
"or",
"posts",
"."
] | python | train |
brian-rose/climlab | climlab/radiation/rrtm/utils.py | https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/radiation/rrtm/utils.py#L54-L85 | def _climlab_to_rrtm(field):
'''Prepare field with proper dimension order.
RRTM code expects arrays with (ncol, nlay)
and with pressure decreasing from surface at element 0
climlab grid dimensions are any of:
- (num_lev,) --> (1, num_lev)
- (num_lat, num_lev) --> (num_lat, num_lev)
... | [
"def",
"_climlab_to_rrtm",
"(",
"field",
")",
":",
"# Make this work just with 1D (KM,) arrays",
"# (KM,) --> (1, nlay)",
"try",
":",
"# Flip along the last axis to reverse the pressure order",
"field",
"=",
"field",
"[",
"...",
",",
":",
":",
"-",
"1",
"]",
"except",... | Prepare field with proper dimension order.
RRTM code expects arrays with (ncol, nlay)
and with pressure decreasing from surface at element 0
climlab grid dimensions are any of:
- (num_lev,) --> (1, num_lev)
- (num_lat, num_lev) --> (num_lat, num_lev)
- (num_lat, num_lon, num_lev) ... | [
"Prepare",
"field",
"with",
"proper",
"dimension",
"order",
".",
"RRTM",
"code",
"expects",
"arrays",
"with",
"(",
"ncol",
"nlay",
")",
"and",
"with",
"pressure",
"decreasing",
"from",
"surface",
"at",
"element",
"0"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.