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
gagneurlab/concise
concise/hyopt.py
https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/hyopt.py#L166-L172
def count_by_state_unsynced(self, arg): """Extends the original object in order to inject checking for stalled jobs and killing them if they are running for too long """ if self.kill_timeout is not None: self.delete_running(self.kill_timeout) return super(CMongoTrials...
[ "def", "count_by_state_unsynced", "(", "self", ",", "arg", ")", ":", "if", "self", ".", "kill_timeout", "is", "not", "None", ":", "self", ".", "delete_running", "(", "self", ".", "kill_timeout", ")", "return", "super", "(", "CMongoTrials", ",", "self", ")"...
Extends the original object in order to inject checking for stalled jobs and killing them if they are running for too long
[ "Extends", "the", "original", "object", "in", "order", "to", "inject", "checking", "for", "stalled", "jobs", "and", "killing", "them", "if", "they", "are", "running", "for", "too", "long" ]
python
train
materialsproject/pymatgen
pymatgen/io/feff/outputs.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/feff/outputs.py#L378-L386
def material_formula(self): """ Returns chemical formula of material from feff.inp file """ try: form = self.header.formula except IndexError: form = 'No formula provided' return "".join(map(str, form))
[ "def", "material_formula", "(", "self", ")", ":", "try", ":", "form", "=", "self", ".", "header", ".", "formula", "except", "IndexError", ":", "form", "=", "'No formula provided'", "return", "\"\"", ".", "join", "(", "map", "(", "str", ",", "form", ")", ...
Returns chemical formula of material from feff.inp file
[ "Returns", "chemical", "formula", "of", "material", "from", "feff", ".", "inp", "file" ]
python
train
StagPython/StagPy
stagpy/processing.py
https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/processing.py#L241-L255
def energy_prof(step): """Energy flux. This computation takes sphericity into account if necessary. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tuple of :class:`numpy.array`: the energy flux and the radial position at wh...
[ "def", "energy_prof", "(", "step", ")", ":", "diff", ",", "rad", "=", "diffs_prof", "(", "step", ")", "adv", ",", "_", "=", "advts_prof", "(", "step", ")", "return", "(", "diff", "+", "np", ".", "append", "(", "adv", ",", "0", ")", ")", ",", "r...
Energy flux. This computation takes sphericity into account if necessary. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tuple of :class:`numpy.array`: the energy flux and the radial position at which it is evaluated.
[ "Energy", "flux", "." ]
python
train
pinax/pinax-messages
pinax/messages/models.py
https://github.com/pinax/pinax-messages/blob/8403bf95ee9b36cbe8ea0bb712e5ef75ba898746/pinax/messages/models.py#L98-L111
def new_message(cls, from_user, to_users, subject, content): """ Create a new Message and Thread. Mark thread as unread for all recipients, and mark thread as read and deleted from inbox by creator. """ thread = Thread.objects.create(subject=subject) for user in ...
[ "def", "new_message", "(", "cls", ",", "from_user", ",", "to_users", ",", "subject", ",", "content", ")", ":", "thread", "=", "Thread", ".", "objects", ".", "create", "(", "subject", "=", "subject", ")", "for", "user", "in", "to_users", ":", "thread", ...
Create a new Message and Thread. Mark thread as unread for all recipients, and mark thread as read and deleted from inbox by creator.
[ "Create", "a", "new", "Message", "and", "Thread", "." ]
python
train
gamechanger/schemer
schemer/validators.py
https://github.com/gamechanger/schemer/blob/1d1dd7da433d3b84ce5a80ded5a84ab4a65825ee/schemer/validators.py#L108-L129
def is_email(): """ Validates that a fields value is a valid email address. """ email = ( ur'(?!^\.)' # No dot at start ur'(?!.*\.@)' # No dot before at sign ur'(?!.*@\.)' # No dot after at sign ur'(?!.*\.$)' # No dot at the end ur'(?!.*\.\.)' # No dou...
[ "def", "is_email", "(", ")", ":", "email", "=", "(", "ur'(?!^\\.)'", "# No dot at start", "ur'(?!.*\\.@)'", "# No dot before at sign", "ur'(?!.*@\\.)'", "# No dot after at sign", "ur'(?!.*\\.$)'", "# No dot at the end", "ur'(?!.*\\.\\.)'", "# No double dots anywhere", "ur'^\\S+'"...
Validates that a fields value is a valid email address.
[ "Validates", "that", "a", "fields", "value", "is", "a", "valid", "email", "address", "." ]
python
train
ubccr/pinky
pinky/canonicalization/traverse.py
https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/canonicalization/traverse.py#L122-L163
def draw(molecule, TraversalType=SmilesTraversal): """(molecule)->canonical representation of a molecule Well, it's only canonical if the atom symorders are canonical, otherwise it's arbitrary. atoms must have a symorder attribute bonds must have a equiv_class attribute""" result = [] atoms...
[ "def", "draw", "(", "molecule", ",", "TraversalType", "=", "SmilesTraversal", ")", ":", "result", "=", "[", "]", "atoms", "=", "allAtoms", "=", "molecule", ".", "atoms", "visitedAtoms", "=", "{", "}", "#", "# Traverse all components of the graph to form", "# the...
(molecule)->canonical representation of a molecule Well, it's only canonical if the atom symorders are canonical, otherwise it's arbitrary. atoms must have a symorder attribute bonds must have a equiv_class attribute
[ "(", "molecule", ")", "-", ">", "canonical", "representation", "of", "a", "molecule", "Well", "it", "s", "only", "canonical", "if", "the", "atom", "symorders", "are", "canonical", "otherwise", "it", "s", "arbitrary", "." ]
python
train
cga-harvard/Hypermap-Registry
hypermap/aggregator/views.py
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/views.py#L45-L58
def serialize_checks(check_set): """ Serialize a check_set for raphael """ check_set_list = [] for check in check_set.all()[:25]: check_set_list.append( { 'datetime': check.checked_datetime.isoformat(), 'value': check.response_time, ...
[ "def", "serialize_checks", "(", "check_set", ")", ":", "check_set_list", "=", "[", "]", "for", "check", "in", "check_set", ".", "all", "(", ")", "[", ":", "25", "]", ":", "check_set_list", ".", "append", "(", "{", "'datetime'", ":", "check", ".", "chec...
Serialize a check_set for raphael
[ "Serialize", "a", "check_set", "for", "raphael" ]
python
train
draios/python-sdc-client
sdcclient/_secure.py
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_secure.py#L428-L462
def get_policy_events_id_range(self, id, from_sec, to_sec, sampling=None, aggregations=None, scope_filter=None, event_filter=None): '''**Description** Fetch all policy events with id that occurred in the time range [from_sec:to_sec]. This method is used in conjunction with :func:`~sdccli...
[ "def", "get_policy_events_id_range", "(", "self", ",", "id", ",", "from_sec", ",", "to_sec", ",", "sampling", "=", "None", ",", "aggregations", "=", "None", ",", "scope_filter", "=", "None", ",", "event_filter", "=", "None", ")", ":", "options", "=", "{", ...
**Description** Fetch all policy events with id that occurred in the time range [from_sec:to_sec]. This method is used in conjunction with :func:`~sdcclient.SdSecureClient.get_more_policy_events` to provide paginated access to policy events. **Arguments** - id: the id of the...
[ "**", "Description", "**", "Fetch", "all", "policy", "events", "with", "id", "that", "occurred", "in", "the", "time", "range", "[", "from_sec", ":", "to_sec", "]", ".", "This", "method", "is", "used", "in", "conjunction", "with", ":", "func", ":", "~sdcc...
python
test
sergiocorreia/panflute
panflute/autofilter.py
https://github.com/sergiocorreia/panflute/blob/65c2d570c26a190deb600cab5e2ad8a828a3302e/panflute/autofilter.py#L39-L112
def stdio(filters=None, search_dirs=None, data_dir=True, sys_path=True, panfl_=False, input_stream=None, output_stream=None): """ Reads JSON from stdin and second CLI argument: ``sys.argv[1]``. Dumps JSON doc to the stdout. :param filters: Union[List[str], None] if None then read from metadata ...
[ "def", "stdio", "(", "filters", "=", "None", ",", "search_dirs", "=", "None", ",", "data_dir", "=", "True", ",", "sys_path", "=", "True", ",", "panfl_", "=", "False", ",", "input_stream", "=", "None", ",", "output_stream", "=", "None", ")", ":", "doc",...
Reads JSON from stdin and second CLI argument: ``sys.argv[1]``. Dumps JSON doc to the stdout. :param filters: Union[List[str], None] if None then read from metadata :param search_dirs: Union[List[str], None] if None then read from metadata :param data_dir: bool :param sys_path: bool...
[ "Reads", "JSON", "from", "stdin", "and", "second", "CLI", "argument", ":", "sys", ".", "argv", "[", "1", "]", ".", "Dumps", "JSON", "doc", "to", "the", "stdout", "." ]
python
train
mseclab/PyJFuzz
pyjfuzz/core/pjf_mutators.py
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_mutators.py#L259-L267
def safe_unicode(self, buf): """ Safely return an unicode encoded string """ tmp = "" buf = "".join(b for b in buf) for character in buf: tmp += character return tmp
[ "def", "safe_unicode", "(", "self", ",", "buf", ")", ":", "tmp", "=", "\"\"", "buf", "=", "\"\"", ".", "join", "(", "b", "for", "b", "in", "buf", ")", "for", "character", "in", "buf", ":", "tmp", "+=", "character", "return", "tmp" ]
Safely return an unicode encoded string
[ "Safely", "return", "an", "unicode", "encoded", "string" ]
python
test
xapple/plumbing
plumbing/ec2.py
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/ec2.py#L70-L75
def rename(self, name): """Set the name of the machine.""" self.ec2.create_tags(Resources = [self.instance_id], Tags = [{'Key': 'Name', 'Value': name}]) self.refresh_info()
[ "def", "rename", "(", "self", ",", "name", ")", ":", "self", ".", "ec2", ".", "create_tags", "(", "Resources", "=", "[", "self", ".", "instance_id", "]", ",", "Tags", "=", "[", "{", "'Key'", ":", "'Name'", ",", "'Value'", ":", "name", "}", "]", "...
Set the name of the machine.
[ "Set", "the", "name", "of", "the", "machine", "." ]
python
train
acutesoftware/AIKIF
scripts/examples/game_of_life_console.py
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/scripts/examples/game_of_life_console.py#L79-L86
def print_there(x, y, text): """" allows display of a game of life on a console via resetting cursor position to a set point - looks 'ok' for testing but not production quality. """ sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text)) sys.stdout.flush()
[ "def", "print_there", "(", "x", ",", "y", ",", "text", ")", ":", "sys", ".", "stdout", ".", "write", "(", "\"\\x1b7\\x1b[%d;%df%s\\x1b8\"", "%", "(", "x", ",", "y", ",", "text", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
allows display of a game of life on a console via resetting cursor position to a set point - looks 'ok' for testing but not production quality.
[ "allows", "display", "of", "a", "game", "of", "life", "on", "a", "console", "via", "resetting", "cursor", "position", "to", "a", "set", "point", "-", "looks", "ok", "for", "testing", "but", "not", "production", "quality", "." ]
python
train
postlund/pyatv
pyatv/dmap/__init__.py
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/__init__.py#L116-L125
async def left(self): """Press key left.""" await self._send_commands( self._move('Down', 0, 75, 100), self._move('Move', 1, 70, 100), self._move('Move', 3, 65, 100), self._move('Move', 4, 60, 100), self._move('Move', 5, 55, 100), s...
[ "async", "def", "left", "(", "self", ")", ":", "await", "self", ".", "_send_commands", "(", "self", ".", "_move", "(", "'Down'", ",", "0", ",", "75", ",", "100", ")", ",", "self", ".", "_move", "(", "'Move'", ",", "1", ",", "70", ",", "100", ")...
Press key left.
[ "Press", "key", "left", "." ]
python
train
MatterMiners/cobald
cobald/monitor/format_line.py
https://github.com/MatterMiners/cobald/blob/264138de4382d1c9b53fabcbc6660e10b33a914d/cobald/monitor/format_line.py#L8-L26
def line_protocol(name, tags: dict = None, fields: dict = None, timestamp: float = None) -> str: """ Format a report as per InfluxDB line protocol :param name: name of the report :param tags: tags identifying the specific report :param fields: measurements of the report :param timestamp: when t...
[ "def", "line_protocol", "(", "name", ",", "tags", ":", "dict", "=", "None", ",", "fields", ":", "dict", "=", "None", ",", "timestamp", ":", "float", "=", "None", ")", "->", "str", ":", "output_str", "=", "name", "if", "tags", ":", "output_str", "+=",...
Format a report as per InfluxDB line protocol :param name: name of the report :param tags: tags identifying the specific report :param fields: measurements of the report :param timestamp: when the measurement was taken, in **seconds** since the epoch
[ "Format", "a", "report", "as", "per", "InfluxDB", "line", "protocol" ]
python
train
joytunes/JTLocalize
localization_flow/jtlocalize/core/add_genstrings_comments_to_file.py
https://github.com/joytunes/JTLocalize/blob/87864dc60114e0e61c768d057c6eddfadff3f40a/localization_flow/jtlocalize/core/add_genstrings_comments_to_file.py#L26-L57
def add_genstrings_comments_to_file(localization_file, genstrings_err): """ Adds the comments produced by the genstrings script for duplicate keys. Args: localization_file (str): The path to the strings file. """ errors_to_log = [line for line in genstrings_err.splitlines() if "used with mult...
[ "def", "add_genstrings_comments_to_file", "(", "localization_file", ",", "genstrings_err", ")", ":", "errors_to_log", "=", "[", "line", "for", "line", "in", "genstrings_err", ".", "splitlines", "(", ")", "if", "\"used with multiple comments\"", "not", "in", "line", ...
Adds the comments produced by the genstrings script for duplicate keys. Args: localization_file (str): The path to the strings file.
[ "Adds", "the", "comments", "produced", "by", "the", "genstrings", "script", "for", "duplicate", "keys", "." ]
python
train
horazont/aioxmpp
aioxmpp/security_layer.py
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/security_layer.py#L1224-L1253
def security_layer(tls_provider, sasl_providers): """ .. deprecated:: 0.6 Replaced by :class:`SecurityLayer`. Return a configured :class:`SecurityLayer`. `tls_provider` must be a :class:`STARTTLSProvider`. The return value can be passed to the constructor of :class:`~.node.Client`. ...
[ "def", "security_layer", "(", "tls_provider", ",", "sasl_providers", ")", ":", "sasl_providers", "=", "tuple", "(", "sasl_providers", ")", "if", "not", "sasl_providers", ":", "raise", "ValueError", "(", "\"At least one SASL provider must be given.\"", ")", "for", "sas...
.. deprecated:: 0.6 Replaced by :class:`SecurityLayer`. Return a configured :class:`SecurityLayer`. `tls_provider` must be a :class:`STARTTLSProvider`. The return value can be passed to the constructor of :class:`~.node.Client`. Some very basic checking on the input is also performed.
[ "..", "deprecated", "::", "0", ".", "6" ]
python
train
vbwagner/ctypescrypto
ctypescrypto/digest.py
https://github.com/vbwagner/ctypescrypto/blob/33c32904cf5e04901f87f90e2499634b8feecd3e/ctypescrypto/digest.py#L64-L69
def name(self): """ Returns name of the digest """ if not hasattr(self, 'digest_name'): self.digest_name = Oid(libcrypto.EVP_MD_type(self.digest) ).longname() return self.digest_name
[ "def", "name", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'digest_name'", ")", ":", "self", ".", "digest_name", "=", "Oid", "(", "libcrypto", ".", "EVP_MD_type", "(", "self", ".", "digest", ")", ")", ".", "longname", "(", ")", ...
Returns name of the digest
[ "Returns", "name", "of", "the", "digest" ]
python
train
romanz/trezor-agent
libagent/gpg/protocol.py
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L68-L71
def subpackets(*items): """Serialize several GPG subpackets.""" prefixed = [subpacket_prefix_len(item) for item in items] return util.prefix_len('>H', b''.join(prefixed))
[ "def", "subpackets", "(", "*", "items", ")", ":", "prefixed", "=", "[", "subpacket_prefix_len", "(", "item", ")", "for", "item", "in", "items", "]", "return", "util", ".", "prefix_len", "(", "'>H'", ",", "b''", ".", "join", "(", "prefixed", ")", ")" ]
Serialize several GPG subpackets.
[ "Serialize", "several", "GPG", "subpackets", "." ]
python
train
data61/clkhash
clkhash/cli.py
https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/cli.py#L182-L202
def create(server, name, project, apikey, output, threshold, verbose): """Create a new run on an entity matching server. See entity matching service documentation for details on threshold. Returns details for the created run. """ if verbose: log("Entity Matching Server: {}".format(server))...
[ "def", "create", "(", "server", ",", "name", ",", "project", ",", "apikey", ",", "output", ",", "threshold", ",", "verbose", ")", ":", "if", "verbose", ":", "log", "(", "\"Entity Matching Server: {}\"", ".", "format", "(", "server", ")", ")", "if", "thre...
Create a new run on an entity matching server. See entity matching service documentation for details on threshold. Returns details for the created run.
[ "Create", "a", "new", "run", "on", "an", "entity", "matching", "server", "." ]
python
train
tgsmith61591/pmdarima
pmdarima/preprocessing/exog/fourier.py
https://github.com/tgsmith61591/pmdarima/blob/a133de78ba5bd68da9785b061f519ba28cd514cc/pmdarima/preprocessing/exog/fourier.py#L120-L173
def transform(self, y, exogenous=None, n_periods=0, **_): """Create Fourier term features When an ARIMA is fit with an exogenous array, it must be forecasted with one also. Since at ``predict`` time in a pipeline we won't have ``y`` (and we may not yet have an ``exog`` array), we have t...
[ "def", "transform", "(", "self", ",", "y", ",", "exogenous", "=", "None", ",", "n_periods", "=", "0", ",", "*", "*", "_", ")", ":", "check_is_fitted", "(", "self", ",", "\"p_\"", ")", "_", ",", "exog", "=", "self", ".", "_check_y_exog", "(", "y", ...
Create Fourier term features When an ARIMA is fit with an exogenous array, it must be forecasted with one also. Since at ``predict`` time in a pipeline we won't have ``y`` (and we may not yet have an ``exog`` array), we have to know how far into the future for which to compute Fourier t...
[ "Create", "Fourier", "term", "features" ]
python
train
google/grr
grr/server/grr_response_server/keyword_index.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/keyword_index.py#L83-L92
def AddKeywordsForName(self, name, keywords): """Associates keywords with name. Records that keywords are associated with name. Args: name: A name which should be associated with some keywords. keywords: A collection of keywords to associate with name. """ data_store.DB.IndexAddKeyword...
[ "def", "AddKeywordsForName", "(", "self", ",", "name", ",", "keywords", ")", ":", "data_store", ".", "DB", ".", "IndexAddKeywordsForName", "(", "self", ".", "urn", ",", "name", ",", "keywords", ")" ]
Associates keywords with name. Records that keywords are associated with name. Args: name: A name which should be associated with some keywords. keywords: A collection of keywords to associate with name.
[ "Associates", "keywords", "with", "name", "." ]
python
train
zeromake/aiko
aiko/application.py
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/application.py#L199-L250
def _middleware_call( self, middlewares: Iterator[MIDDLEWARE_TYPE], ctx: Context, next_call: NEXT_CALL_TYPE, ) -> TypeGenerator[Any, None, None]: """ 从迭代器中取出一个中间件,执行 """ middleware = None try: middleware = next(middl...
[ "def", "_middleware_call", "(", "self", ",", "middlewares", ":", "Iterator", "[", "MIDDLEWARE_TYPE", "]", ",", "ctx", ":", "Context", ",", "next_call", ":", "NEXT_CALL_TYPE", ",", ")", "->", "TypeGenerator", "[", "Any", ",", "None", ",", "None", "]", ":", ...
从迭代器中取出一个中间件,执行
[ "从迭代器中取出一个中间件,执行" ]
python
train
RiotGames/cloud-inquisitor
plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-auditor-iam/cinq_auditor_iam/__init__.py#L368-L394
def get_roles(client): """Returns a list of all the roles for an account. Returns a list containing all the roles for the account. Args: client (:obj:`boto3.session.Session`): A boto3 Session object Returns: :obj:`list` of `dict` """ done = False ...
[ "def", "get_roles", "(", "client", ")", ":", "done", "=", "False", "marker", "=", "None", "roles", "=", "[", "]", "while", "not", "done", ":", "if", "marker", ":", "response", "=", "client", ".", "list_roles", "(", "Marker", "=", "marker", ")", "else...
Returns a list of all the roles for an account. Returns a list containing all the roles for the account. Args: client (:obj:`boto3.session.Session`): A boto3 Session object Returns: :obj:`list` of `dict`
[ "Returns", "a", "list", "of", "all", "the", "roles", "for", "an", "account", ".", "Returns", "a", "list", "containing", "all", "the", "roles", "for", "the", "account", "." ]
python
train
wummel/linkchecker
linkcheck/checker/urlbase.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/checker/urlbase.py#L526-L535
def add_size_info (self): """Set size of URL content (if any).. Should be overridden in subclasses.""" maxbytes = self.aggregate.config["maxfilesizedownload"] if self.size > maxbytes: self.add_warning( _("Content size %(size)s is larger than %(maxbytes)s.") % ...
[ "def", "add_size_info", "(", "self", ")", ":", "maxbytes", "=", "self", ".", "aggregate", ".", "config", "[", "\"maxfilesizedownload\"", "]", "if", "self", ".", "size", ">", "maxbytes", ":", "self", ".", "add_warning", "(", "_", "(", "\"Content size %(size)s...
Set size of URL content (if any).. Should be overridden in subclasses.
[ "Set", "size", "of", "URL", "content", "(", "if", "any", ")", "..", "Should", "be", "overridden", "in", "subclasses", "." ]
python
train
gc3-uzh-ch/elasticluster
elasticluster/providers/gce.py
https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/gce.py#L180-L199
def _connect(self): """Connects to the cloud web services. If this is the first authentication, a web browser will be started to authenticate against google and provide access to elasticluster. :return: A Resource object with methods for interacting with the service. ...
[ "def", "_connect", "(", "self", ")", ":", "# ensure only one thread runs the authentication process, if needed", "with", "GoogleCloudProvider", ".", "__gce_lock", ":", "# check for existing connection", "if", "not", "self", ".", "_gce", ":", "version", "=", "pkg_resources",...
Connects to the cloud web services. If this is the first authentication, a web browser will be started to authenticate against google and provide access to elasticluster. :return: A Resource object with methods for interacting with the service.
[ "Connects", "to", "the", "cloud", "web", "services", ".", "If", "this", "is", "the", "first", "authentication", "a", "web", "browser", "will", "be", "started", "to", "authenticate", "against", "google", "and", "provide", "access", "to", "elasticluster", "." ]
python
train
dustin/twitty-twister
twittytwister/twitter.py
https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L1168-L1186
def _state_error(self, reason): """ The connection attempt resulted in an error. Attempt a reconnect with a back-off algorithm. """ log.err(reason) def matchException(failure): for errorState, backOff in self.backOffs.iteritems(): if 'errorTy...
[ "def", "_state_error", "(", "self", ",", "reason", ")", ":", "log", ".", "err", "(", "reason", ")", "def", "matchException", "(", "failure", ")", ":", "for", "errorState", ",", "backOff", "in", "self", ".", "backOffs", ".", "iteritems", "(", ")", ":", ...
The connection attempt resulted in an error. Attempt a reconnect with a back-off algorithm.
[ "The", "connection", "attempt", "resulted", "in", "an", "error", "." ]
python
train
SpikeInterface/spiketoolkit
spiketoolkit/sorters/launcher.py
https://github.com/SpikeInterface/spiketoolkit/blob/f7c054383d1ebca640966b057c087fa187955d13/spiketoolkit/sorters/launcher.py#L181-L206
def collect_results(working_folder): """ Collect results in a working_folder. The output is nested dict[rec_name][sorter_name] of SortingExtrator. """ results = {} working_folder = Path(working_folder) output_folders = working_folder/'output_folders' for rec_name in os.listdir(output...
[ "def", "collect_results", "(", "working_folder", ")", ":", "results", "=", "{", "}", "working_folder", "=", "Path", "(", "working_folder", ")", "output_folders", "=", "working_folder", "/", "'output_folders'", "for", "rec_name", "in", "os", ".", "listdir", "(", ...
Collect results in a working_folder. The output is nested dict[rec_name][sorter_name] of SortingExtrator.
[ "Collect", "results", "in", "a", "working_folder", "." ]
python
train
blockstack/blockstack-files
blockstack_file/blockstack_file.py
https://github.com/blockstack/blockstack-files/blob/8d88cc48bdf8ed57f17d4bba860e972bde321921/blockstack_file/blockstack_file.py#L652-L866
def main(): """ Entry point for the CLI interface """ argparser = argparse.ArgumentParser( description='Blockstack-file version {}'.format(__version__)) subparsers = argparser.add_subparsers( dest='action', help='The file command to take [get/put/delete]') parser = ...
[ "def", "main", "(", ")", ":", "argparser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Blockstack-file version {}'", ".", "format", "(", "__version__", ")", ")", "subparsers", "=", "argparser", ".", "add_subparsers", "(", "dest", "=", "'...
Entry point for the CLI interface
[ "Entry", "point", "for", "the", "CLI", "interface" ]
python
train
rameshg87/pyremotevbox
pyremotevbox/ZSI/TCtimes.py
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/TCtimes.py#L79-L135
def _dict_to_tuple(d): '''Convert a dictionary to a time tuple. Depends on key values in the regexp pattern! ''' # TODO: Adding a ms field to struct_time tuples is problematic # since they don't have this field. Should use datetime # which has a microseconds field, else no ms.. When mapp...
[ "def", "_dict_to_tuple", "(", "d", ")", ":", "# TODO: Adding a ms field to struct_time tuples is problematic ", "# since they don't have this field. Should use datetime", "# which has a microseconds field, else no ms.. When mapping struct_time ", "# to gDateTime the last 3 fields are irrelevant,...
Convert a dictionary to a time tuple. Depends on key values in the regexp pattern!
[ "Convert", "a", "dictionary", "to", "a", "time", "tuple", ".", "Depends", "on", "key", "values", "in", "the", "regexp", "pattern!" ]
python
train
scanny/python-pptx
pptx/oxml/chart/chart.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/oxml/chart/chart.py#L220-L229
def next_order(self): """ Return the next available `c:ser/c:order` value within the scope of this chart, the maximum order value found on existing series, incremented by one. """ order_vals = [s.order.val for s in self.sers] if not order_vals: return ...
[ "def", "next_order", "(", "self", ")", ":", "order_vals", "=", "[", "s", ".", "order", ".", "val", "for", "s", "in", "self", ".", "sers", "]", "if", "not", "order_vals", ":", "return", "0", "return", "max", "(", "order_vals", ")", "+", "1" ]
Return the next available `c:ser/c:order` value within the scope of this chart, the maximum order value found on existing series, incremented by one.
[ "Return", "the", "next", "available", "c", ":", "ser", "/", "c", ":", "order", "value", "within", "the", "scope", "of", "this", "chart", "the", "maximum", "order", "value", "found", "on", "existing", "series", "incremented", "by", "one", "." ]
python
train
MagicStack/asyncpg
asyncpg/cursor.py
https://github.com/MagicStack/asyncpg/blob/92c2d81256a1efd8cab12c0118d74ccd1c18131b/asyncpg/cursor.py#L241-L260
async def forward(self, n, *, timeout=None) -> int: r"""Skip over the next *n* rows. :param float timeout: Optional timeout value in seconds. :return: A number of rows actually skipped over (<= *n*). """ self._check_ready() if n <= 0: raise exceptions.Interf...
[ "async", "def", "forward", "(", "self", ",", "n", ",", "*", ",", "timeout", "=", "None", ")", "->", "int", ":", "self", ".", "_check_ready", "(", ")", "if", "n", "<=", "0", ":", "raise", "exceptions", ".", "InterfaceError", "(", "'n must be greater tha...
r"""Skip over the next *n* rows. :param float timeout: Optional timeout value in seconds. :return: A number of rows actually skipped over (<= *n*).
[ "r", "Skip", "over", "the", "next", "*", "n", "*", "rows", "." ]
python
train
jfilter/deep-plots
deep_plots/wrangle.py
https://github.com/jfilter/deep-plots/blob/8b0af5c1e44336068c2f8c883ffa158bbb34ba5e/deep_plots/wrangle.py#L27-L37
def from_keras_log(csv_path, output_dir_path, **kwargs): """Plot accuracy and loss from a Keras CSV log. Args: csv_path: The path to the CSV log with the actual data. output_dir_path: The path to the directory where the resultings plots should end up. """ # automatically get...
[ "def", "from_keras_log", "(", "csv_path", ",", "output_dir_path", ",", "*", "*", "kwargs", ")", ":", "# automatically get seperator by using Python's CSV parser", "data", "=", "pd", ".", "read_csv", "(", "csv_path", ",", "sep", "=", "None", ",", "engine", "=", "...
Plot accuracy and loss from a Keras CSV log. Args: csv_path: The path to the CSV log with the actual data. output_dir_path: The path to the directory where the resultings plots should end up.
[ "Plot", "accuracy", "and", "loss", "from", "a", "Keras", "CSV", "log", "." ]
python
train
slightlynybbled/tk_tools
tk_tools/canvas.py
https://github.com/slightlynybbled/tk_tools/blob/7c1792cad42890251a34f0617ce9b4b3e7abcf50/tk_tools/canvas.py#L597-L615
def to_yellow(self, on: bool=False): """ Change the LED to yellow (on or off) :param on: True or False :return: None """ self._on = on if on: self._load_new(led_yellow_on) if self._toggle_on_click: self._canvas.bind('<Butto...
[ "def", "to_yellow", "(", "self", ",", "on", ":", "bool", "=", "False", ")", ":", "self", ".", "_on", "=", "on", "if", "on", ":", "self", ".", "_load_new", "(", "led_yellow_on", ")", "if", "self", ".", "_toggle_on_click", ":", "self", ".", "_canvas", ...
Change the LED to yellow (on or off) :param on: True or False :return: None
[ "Change", "the", "LED", "to", "yellow", "(", "on", "or", "off", ")", ":", "param", "on", ":", "True", "or", "False", ":", "return", ":", "None" ]
python
train
cltl/KafNafParserPy
KafNafParserPy/feature_extractor/constituency.py
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L137-L173
def get_path_from_to(self,from_tid, to_tid): """ This function returns the path (in terms of phrase types) from one term to another @type from_tid: string @param from_tid: one term id @type to_tid: string @param to_tid: another term id @rtype: list @return...
[ "def", "get_path_from_to", "(", "self", ",", "from_tid", ",", "to_tid", ")", ":", "shortest_subsumer", "=", "self", ".", "get_least_common_subsumer", "(", "from_tid", ",", "to_tid", ")", "#print 'From:',self.naf.get_term(from_tid).get_lemma()", "#print 'To:',self.naf.get_te...
This function returns the path (in terms of phrase types) from one term to another @type from_tid: string @param from_tid: one term id @type to_tid: string @param to_tid: another term id @rtype: list @return: the path, list of phrase types
[ "This", "function", "returns", "the", "path", "(", "in", "terms", "of", "phrase", "types", ")", "from", "one", "term", "to", "another" ]
python
train
OLC-Bioinformatics/sipprverse
genesippr_validation.py
https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/genesippr_validation.py#L47-L89
def sequence_prep(self): """ Create metadata objects for all PacBio assembly FASTA files in the sequencepath. Create individual subdirectories for each sample. Relative symlink the original FASTA file to the appropriate subdirectory """ # Create a sorted list of all the...
[ "def", "sequence_prep", "(", "self", ")", ":", "# Create a sorted list of all the FASTA files in the sequence path", "strains", "=", "sorted", "(", "glob", "(", "os", ".", "path", ".", "join", "(", "self", ".", "fastapath", ",", "'*.fa*'", ".", "format", "(", "s...
Create metadata objects for all PacBio assembly FASTA files in the sequencepath. Create individual subdirectories for each sample. Relative symlink the original FASTA file to the appropriate subdirectory
[ "Create", "metadata", "objects", "for", "all", "PacBio", "assembly", "FASTA", "files", "in", "the", "sequencepath", ".", "Create", "individual", "subdirectories", "for", "each", "sample", ".", "Relative", "symlink", "the", "original", "FASTA", "file", "to", "the...
python
train
lalinsky/python-phoenixdb
phoenixdb/connection.py
https://github.com/lalinsky/python-phoenixdb/blob/1bb34488dd530ca65f91b29ef16aa7b71f26b806/phoenixdb/connection.py#L75-L91
def close(self): """Closes the connection. No further operations are allowed, either on the connection or any of its cursors, once the connection is closed. If the connection is used in a ``with`` statement, this method will be automatically called at the end of the ``with`` blo...
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "raise", "ProgrammingError", "(", "'the connection is already closed'", ")", "for", "cursor_ref", "in", "self", ".", "_cursors", ":", "cursor", "=", "cursor_ref", "(", ")", "if", "curs...
Closes the connection. No further operations are allowed, either on the connection or any of its cursors, once the connection is closed. If the connection is used in a ``with`` statement, this method will be automatically called at the end of the ``with`` block.
[ "Closes", "the", "connection", ".", "No", "further", "operations", "are", "allowed", "either", "on", "the", "connection", "or", "any", "of", "its", "cursors", "once", "the", "connection", "is", "closed", "." ]
python
train
ajyoon/blur
blur/markov/graph.py
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/markov/graph.py#L400-L521
def from_string(cls, source, distance_weights=None, merge_same_words=False, group_marker_opening='<<', group_marker_closing='>>'): """ Read a string and derive of ``Graph`` from it. Words and pun...
[ "def", "from_string", "(", "cls", ",", "source", ",", "distance_weights", "=", "None", ",", "merge_same_words", "=", "False", ",", "group_marker_opening", "=", "'<<'", ",", "group_marker_closing", "=", "'>>'", ")", ":", "if", "distance_weights", "is", "None", ...
Read a string and derive of ``Graph`` from it. Words and punctuation marks are made into nodes. Punctuation marks are split into separate nodes unless they fall between other non-punctuation marks. ``'hello, world'`` is split into ``'hello'``, ``','``, and ``'world'``, while ``'who's t...
[ "Read", "a", "string", "and", "derive", "of", "Graph", "from", "it", "." ]
python
train
celiao/tmdbsimple
tmdbsimple/search.py
https://github.com/celiao/tmdbsimple/blob/ff17893110c99771d6398a62c35d36dd9735f4b9/tmdbsimple/search.py#L149-L164
def keyword(self, **kwargs): """ Search for keywords by name. Args: query: CGI escpaed string. page: (optional) Minimum value of 1. Expected value is an integer. Returns: A dict respresentation of the JSON returned from the API. """ p...
[ "def", "keyword", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_path", "(", "'keyword'", ")", "response", "=", "self", ".", "_GET", "(", "path", ",", "kwargs", ")", "self", ".", "_set_attrs_to_values", "(", "response",...
Search for keywords by name. Args: query: CGI escpaed string. page: (optional) Minimum value of 1. Expected value is an integer. Returns: A dict respresentation of the JSON returned from the API.
[ "Search", "for", "keywords", "by", "name", "." ]
python
test
PonteIneptique/flask-github-proxy
flask_github_proxy/__init__.py
https://github.com/PonteIneptique/flask-github-proxy/blob/f0a60639342f7c0834360dc12a099bfc3a06d939/flask_github_proxy/__init__.py#L210-L240
def put(self, file): """ Create a new file on github :param file: File to create :return: File or self.ProxyError """ input_ = { "message": file.logs, "author": file.author.dict(), "content": file.base64, "branch": file.branch ...
[ "def", "put", "(", "self", ",", "file", ")", ":", "input_", "=", "{", "\"message\"", ":", "file", ".", "logs", ",", "\"author\"", ":", "file", ".", "author", ".", "dict", "(", ")", ",", "\"content\"", ":", "file", ".", "base64", ",", "\"branch\"", ...
Create a new file on github :param file: File to create :return: File or self.ProxyError
[ "Create", "a", "new", "file", "on", "github" ]
python
train
feliphebueno/Rinzler
rinzler/core/route_mapping.py
https://github.com/feliphebueno/Rinzler/blob/7f6d5445b5662cba2e8938bb82c7f3ef94e5ded8/rinzler/core/route_mapping.py#L16-L22
def get(self, route: str(), callback: object()): """ Binds a GET route with the given callback :rtype: object """ self.__set_route('get', {route: callback}) return RouteMapping
[ "def", "get", "(", "self", ",", "route", ":", "str", "(", ")", ",", "callback", ":", "object", "(", ")", ")", ":", "self", ".", "__set_route", "(", "'get'", ",", "{", "route", ":", "callback", "}", ")", "return", "RouteMapping" ]
Binds a GET route with the given callback :rtype: object
[ "Binds", "a", "GET", "route", "with", "the", "given", "callback", ":", "rtype", ":", "object" ]
python
train
projecthamster/hamster
src/hamster/lib/graphics.py
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L2024-L2037
def all_mouse_sprites(self): """Returns flat list of the sprite tree for simplified iteration""" def all_recursive(sprites): if not sprites: return for sprite in sprites: if sprite.visible: yield sprite for...
[ "def", "all_mouse_sprites", "(", "self", ")", ":", "def", "all_recursive", "(", "sprites", ")", ":", "if", "not", "sprites", ":", "return", "for", "sprite", "in", "sprites", ":", "if", "sprite", ".", "visible", ":", "yield", "sprite", "for", "child", "in...
Returns flat list of the sprite tree for simplified iteration
[ "Returns", "flat", "list", "of", "the", "sprite", "tree", "for", "simplified", "iteration" ]
python
train
sorgerlab/indra
indra/sources/biopax/pathway_commons_client.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/pathway_commons_client.py#L123-L153
def owl_to_model(fname): """Return a BioPAX model object from an OWL file. Parameters ---------- fname : str The name of the OWL file containing the model. Returns ------- biopax_model : org.biopax.paxtools.model.Model A BioPAX model object (java object). """ io_cla...
[ "def", "owl_to_model", "(", "fname", ")", ":", "io_class", "=", "autoclass", "(", "'org.biopax.paxtools.io.SimpleIOHandler'", ")", "io", "=", "io_class", "(", "autoclass", "(", "'org.biopax.paxtools.model.BioPAXLevel'", ")", ".", "L3", ")", "try", ":", "file_is", ...
Return a BioPAX model object from an OWL file. Parameters ---------- fname : str The name of the OWL file containing the model. Returns ------- biopax_model : org.biopax.paxtools.model.Model A BioPAX model object (java object).
[ "Return", "a", "BioPAX", "model", "object", "from", "an", "OWL", "file", "." ]
python
train
oscarbranson/latools
latools/D_obj.py
https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/D_obj.py#L653-L702
def filter_gradient_threshold(self, analyte, win, threshold, recalc=True): """ Apply gradient threshold filter. Generates threshold filters for the given analytes above and below the specified threshold. Two filters are created with prefixes '_above' and '_below'. '...
[ "def", "filter_gradient_threshold", "(", "self", ",", "analyte", ",", "win", ",", "threshold", ",", "recalc", "=", "True", ")", ":", "params", "=", "locals", "(", ")", "del", "(", "params", "[", "'self'", "]", ")", "# calculate absolute gradient", "if", "r...
Apply gradient threshold filter. Generates threshold filters for the given analytes above and below the specified threshold. Two filters are created with prefixes '_above' and '_below'. '_above' keeps all the data above the threshold. '_below' keeps all the data below t...
[ "Apply", "gradient", "threshold", "filter", "." ]
python
test
ejeschke/ginga
ginga/ImageView.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L1263-L1296
def redraw_now(self, whence=0): """Redraw the displayed image. Parameters ---------- whence See :meth:`get_rgb_object`. """ try: time_start = time.time() self.redraw_data(whence=whence) # finally update the window drawabl...
[ "def", "redraw_now", "(", "self", ",", "whence", "=", "0", ")", ":", "try", ":", "time_start", "=", "time", ".", "time", "(", ")", "self", ".", "redraw_data", "(", "whence", "=", "whence", ")", "# finally update the window drawable from the offscreen surface", ...
Redraw the displayed image. Parameters ---------- whence See :meth:`get_rgb_object`.
[ "Redraw", "the", "displayed", "image", "." ]
python
train
sdispater/orator
orator/schema/grammars/grammar.py
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/grammars/grammar.py#L18-L41
def compile_rename_column(self, blueprint, command, connection): """ Compile a rename column command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :param connection: The connection :type co...
[ "def", "compile_rename_column", "(", "self", ",", "blueprint", ",", "command", ",", "connection", ")", ":", "schema", "=", "connection", ".", "get_schema_manager", "(", ")", "table", "=", "self", ".", "get_table_prefix", "(", ")", "+", "blueprint", ".", "get...
Compile a rename column command. :param blueprint: The blueprint :type blueprint: Blueprint :param command: The command :type command: Fluent :param connection: The connection :type connection: orator.connections.Connection :rtype: list
[ "Compile", "a", "rename", "column", "command", "." ]
python
train
odlgroup/odl
odl/operator/oputils.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/oputils.py#L24-L121
def matrix_representation(op): """Return a matrix representation of a linear operator. Parameters ---------- op : `Operator` The linear operator of which one wants a matrix representation. If the domain or range is a `ProductSpace`, it must be a power-space. Returns ------- ...
[ "def", "matrix_representation", "(", "op", ")", ":", "if", "not", "op", ".", "is_linear", ":", "raise", "ValueError", "(", "'the operator is not linear'", ")", "if", "not", "(", "isinstance", "(", "op", ".", "domain", ",", "TensorSpace", ")", "or", "(", "i...
Return a matrix representation of a linear operator. Parameters ---------- op : `Operator` The linear operator of which one wants a matrix representation. If the domain or range is a `ProductSpace`, it must be a power-space. Returns ------- matrix : `numpy.ndarray` The ...
[ "Return", "a", "matrix", "representation", "of", "a", "linear", "operator", "." ]
python
train
Qiskit/qiskit-terra
qiskit/qasm/node/idlist.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/idlist.py#L27-L30
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" return ",".join([self.children[j].qasm(prec) for j in range(self.size())])
[ "def", "qasm", "(", "self", ",", "prec", "=", "15", ")", ":", "return", "\",\"", ".", "join", "(", "[", "self", ".", "children", "[", "j", "]", ".", "qasm", "(", "prec", ")", "for", "j", "in", "range", "(", "self", ".", "size", "(", ")", ")",...
Return the corresponding OPENQASM string.
[ "Return", "the", "corresponding", "OPENQASM", "string", "." ]
python
test
portfors-lab/sparkle
sparkle/gui/stim/stimulusview.py
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/stimulusview.py#L178-L193
def visualRectRC(self, row, column): """The rectangle for the bounds of the item at *row*, *column* :param row: row of the item :type row: int :param column: column of the item :type column: int :returns: :qtdoc:`QRect` -- rectangle of the borders of the item """...
[ "def", "visualRectRC", "(", "self", ",", "row", ",", "column", ")", ":", "rect", "=", "self", ".", "_rects", "[", "row", "]", "[", "column", "]", "if", "rect", ".", "isValid", "(", ")", ":", "return", "QtCore", ".", "QRect", "(", "rect", ".", "x"...
The rectangle for the bounds of the item at *row*, *column* :param row: row of the item :type row: int :param column: column of the item :type column: int :returns: :qtdoc:`QRect` -- rectangle of the borders of the item
[ "The", "rectangle", "for", "the", "bounds", "of", "the", "item", "at", "*", "row", "*", "*", "column", "*" ]
python
train
bububa/pyTOP
pyTOP/packages/requests/sessions.py
https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/packages/requests/sessions.py#L229-L237
def post(self, url, data=None, **kwargs): """Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`. :param **kwargs: Optional arguments that ``r...
[ "def", "post", "(", "self", ",", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "request", "(", "'post'", ",", "url", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`. :param **kwargs: Optional arguments that ``request`` takes.
[ "Sends", "a", "POST", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
python
train
Britefury/batchup
batchup/data_source.py
https://github.com/Britefury/batchup/blob/3fc2304e629f813c05f9e7a85a18acef3581a536/batchup/data_source.py#L1800-L1849
def coerce_data_source(x): """ Helper function to coerce an object into a data source, selecting the appropriate data source class for the given object. If `x` is already a data source it is returned as is. Parameters ---------- x: any The object to coerce. If `x` is a data source, ...
[ "def", "coerce_data_source", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "AbstractDataSource", ")", ":", "return", "x", "elif", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "# Sequence of array-likes", "items", "=", "...
Helper function to coerce an object into a data source, selecting the appropriate data source class for the given object. If `x` is already a data source it is returned as is. Parameters ---------- x: any The object to coerce. If `x` is a data source, it is returned as is. If it is ...
[ "Helper", "function", "to", "coerce", "an", "object", "into", "a", "data", "source", "selecting", "the", "appropriate", "data", "source", "class", "for", "the", "given", "object", ".", "If", "x", "is", "already", "a", "data", "source", "it", "is", "returne...
python
train
ssato/python-anyconfig
src/anyconfig/backend/base.py
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L555-L574
def load_with_fn(load_fn, content_or_strm, container, allow_primitives=False, **options): """ Load data from given string or stream 'content_or_strm'. :param load_fn: Callable to load data :param content_or_strm: data content or stream provides it :param container: callble to make ...
[ "def", "load_with_fn", "(", "load_fn", ",", "content_or_strm", ",", "container", ",", "allow_primitives", "=", "False", ",", "*", "*", "options", ")", ":", "ret", "=", "load_fn", "(", "content_or_strm", ",", "*", "*", "options", ")", "if", "anyconfig", "."...
Load data from given string or stream 'content_or_strm'. :param load_fn: Callable to load data :param content_or_strm: data content or stream provides it :param container: callble to make a container object :param allow_primitives: True if the parser.load* may return objects of primitive data t...
[ "Load", "data", "from", "given", "string", "or", "stream", "content_or_strm", "." ]
python
train
rene-aguirre/pywinusb
pywinusb/hid/wnd_hook_mixin.py
https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/wnd_hook_mixin.py#L73-L78
def hook_wnd_proc(self): """Attach to OS Window message handler""" self.__local_wnd_proc_wrapped = WndProcType(self.local_wnd_proc) self.__old_wnd_proc = SetWindowLong(self.__local_win_handle, GWL_WNDPROC, self....
[ "def", "hook_wnd_proc", "(", "self", ")", ":", "self", ".", "__local_wnd_proc_wrapped", "=", "WndProcType", "(", "self", ".", "local_wnd_proc", ")", "self", ".", "__old_wnd_proc", "=", "SetWindowLong", "(", "self", ".", "__local_win_handle", ",", "GWL_WNDPROC", ...
Attach to OS Window message handler
[ "Attach", "to", "OS", "Window", "message", "handler" ]
python
train
bokeh/bokeh
bokeh/server/callbacks.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/callbacks.py#L171-L173
def _copy_with_changed_callback(self, new_callback): ''' Dev API used to wrap the callback with decorators. ''' return TimeoutCallback(self._document, new_callback, self._timeout, self._id)
[ "def", "_copy_with_changed_callback", "(", "self", ",", "new_callback", ")", ":", "return", "TimeoutCallback", "(", "self", ".", "_document", ",", "new_callback", ",", "self", ".", "_timeout", ",", "self", ".", "_id", ")" ]
Dev API used to wrap the callback with decorators.
[ "Dev", "API", "used", "to", "wrap", "the", "callback", "with", "decorators", "." ]
python
train
log2timeline/dfvfs
dfvfs/file_io/tsk_partition_file_io.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/file_io/tsk_partition_file_io.py#L29-L78
def _Open(self, path_spec=None, mode='rb'): """Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file-like...
[ "def", "_Open", "(", "self", ",", "path_spec", "=", "None", ",", "mode", "=", "'rb'", ")", ":", "if", "not", "path_spec", ":", "raise", "ValueError", "(", "'Missing path specification.'", ")", "if", "not", "path_spec", ".", "HasParent", "(", ")", ":", "r...
Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file-like object could not be opened. OSError: if the ...
[ "Opens", "the", "file", "-", "like", "object", "defined", "by", "path", "specification", "." ]
python
train
CalebBell/fluids
fluids/two_phase.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase.py#L1935-L2080
def Kim_Mudawar(m, x, rhol, rhog, mul, mug, sigma, D, L=1): r'''Calculates two-phase pressure drop with the Kim and Mudawar (2012) correlation as in [1]_, also presented in [2]_. .. math:: \Delta P = \Delta P_{l} \phi_{l}^2 .. math:: \phi_l^2 = 1 + \frac{C}{X} + \frac{1}{X^2} .. m...
[ "def", "Kim_Mudawar", "(", "m", ",", "x", ",", "rhol", ",", "rhog", ",", "mul", ",", "mug", ",", "sigma", ",", "D", ",", "L", "=", "1", ")", ":", "def", "friction_factor", "(", "Re", ")", ":", "if", "Re", "<", "2000", ":", "return", "64.", "/...
r'''Calculates two-phase pressure drop with the Kim and Mudawar (2012) correlation as in [1]_, also presented in [2]_. .. math:: \Delta P = \Delta P_{l} \phi_{l}^2 .. math:: \phi_l^2 = 1 + \frac{C}{X} + \frac{1}{X^2} .. math:: X^2 = \frac{\Delta P_l}{\Delta P_g} For turbu...
[ "r", "Calculates", "two", "-", "phase", "pressure", "drop", "with", "the", "Kim", "and", "Mudawar", "(", "2012", ")", "correlation", "as", "in", "[", "1", "]", "_", "also", "presented", "in", "[", "2", "]", "_", "." ]
python
train
bspaans/python-mingus
mingus/midi/midi_track.py
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_track.py#L203-L210
def set_deltatime(self, delta_time): """Set the delta_time. Can be an integer or a variable length byte. """ if type(delta_time) == int: delta_time = self.int_to_varbyte(delta_time) self.delta_time = delta_time
[ "def", "set_deltatime", "(", "self", ",", "delta_time", ")", ":", "if", "type", "(", "delta_time", ")", "==", "int", ":", "delta_time", "=", "self", ".", "int_to_varbyte", "(", "delta_time", ")", "self", ".", "delta_time", "=", "delta_time" ]
Set the delta_time. Can be an integer or a variable length byte.
[ "Set", "the", "delta_time", "." ]
python
train
cloud-custodian/cloud-custodian
tools/c7n_gcp/c7n_gcp/actions/cscc.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_gcp/c7n_gcp/actions/cscc.py#L137-L140
def get_name(self, r): """Given an arbitrary resource attempt to resolve back to a qualified name.""" namer = ResourceNameAdapters[self.manager.resource_type.service] return namer(r)
[ "def", "get_name", "(", "self", ",", "r", ")", ":", "namer", "=", "ResourceNameAdapters", "[", "self", ".", "manager", ".", "resource_type", ".", "service", "]", "return", "namer", "(", "r", ")" ]
Given an arbitrary resource attempt to resolve back to a qualified name.
[ "Given", "an", "arbitrary", "resource", "attempt", "to", "resolve", "back", "to", "a", "qualified", "name", "." ]
python
train
PmagPy/PmagPy
pmagpy/contribution_builder.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/contribution_builder.py#L2229-L2249
def get_singular_and_plural_dtype(self, dtype): """ Parameters ---------- dtype : str MagIC table type (specimens, samples, contribution, etc.) Returns --------- name : str singular name for MagIC table ('specimen' for specimens table, etc....
[ "def", "get_singular_and_plural_dtype", "(", "self", ",", "dtype", ")", ":", "dtype", "=", "dtype", ".", "strip", "(", ")", "if", "dtype", ".", "endswith", "(", "'s'", ")", ":", "return", "dtype", "[", ":", "-", "1", "]", ",", "dtype", "elif", "dtype...
Parameters ---------- dtype : str MagIC table type (specimens, samples, contribution, etc.) Returns --------- name : str singular name for MagIC table ('specimen' for specimens table, etc.) dtype : str plural dtype for MagIC table ('spec...
[ "Parameters", "----------", "dtype", ":", "str", "MagIC", "table", "type", "(", "specimens", "samples", "contribution", "etc", ".", ")" ]
python
train
indietyp/django-automated-logging
automated_logging/signals/__init__.py
https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/__init__.py#L23-L33
def validate_instance(instance): """Validating if the instance should be logged, or is excluded""" excludes = settings.AUTOMATED_LOGGING['exclude']['model'] for excluded in excludes: if (excluded in [instance._meta.app_label.lower(), instance.__class__.__name__.lower()] or ...
[ "def", "validate_instance", "(", "instance", ")", ":", "excludes", "=", "settings", ".", "AUTOMATED_LOGGING", "[", "'exclude'", "]", "[", "'model'", "]", "for", "excluded", "in", "excludes", ":", "if", "(", "excluded", "in", "[", "instance", ".", "_meta", ...
Validating if the instance should be logged, or is excluded
[ "Validating", "if", "the", "instance", "should", "be", "logged", "or", "is", "excluded" ]
python
train
operasoftware/twisted-apns
apns/listenable.py
https://github.com/operasoftware/twisted-apns/blob/c7bd460100067e0c96c440ac0f5516485ac7313f/apns/listenable.py#L35-L43
def dispatchEvent(self, event, *args): """ Fire all callbacks assigned to a particular event. To be called by derivative classes. :param *args: Additional arguments to be passed to the callback function. """ for callback in self.listeners[event]: yield...
[ "def", "dispatchEvent", "(", "self", ",", "event", ",", "*", "args", ")", ":", "for", "callback", "in", "self", ".", "listeners", "[", "event", "]", ":", "yield", "callback", "(", "event", ",", "self", ",", "*", "args", ")" ]
Fire all callbacks assigned to a particular event. To be called by derivative classes. :param *args: Additional arguments to be passed to the callback function.
[ "Fire", "all", "callbacks", "assigned", "to", "a", "particular", "event", ".", "To", "be", "called", "by", "derivative", "classes", ".", ":", "param", "*", "args", ":", "Additional", "arguments", "to", "be", "passed", "to", "the", "callback", "function", "...
python
train
arne-cl/discoursegraphs
src/discoursegraphs/readwrite/generic.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/generic.py#L69-L86
def layerset2list(discoursegraph): """ typecasts all `layers` sets to lists to make the graph exportable (e.g. into the `geoff` format). Parameters ---------- discoursegraph : DiscourseDocumentGraph """ for node_id in discoursegraph: discoursegraph.node[node_id]['layers'] = \ ...
[ "def", "layerset2list", "(", "discoursegraph", ")", ":", "for", "node_id", "in", "discoursegraph", ":", "discoursegraph", ".", "node", "[", "node_id", "]", "[", "'layers'", "]", "=", "list", "(", "discoursegraph", ".", "node", "[", "node_id", "]", "[", "'l...
typecasts all `layers` sets to lists to make the graph exportable (e.g. into the `geoff` format). Parameters ---------- discoursegraph : DiscourseDocumentGraph
[ "typecasts", "all", "layers", "sets", "to", "lists", "to", "make", "the", "graph", "exportable", "(", "e", ".", "g", ".", "into", "the", "geoff", "format", ")", "." ]
python
train
marcinmiklitz/pywindow
pywindow/molecular.py
https://github.com/marcinmiklitz/pywindow/blob/e5264812157224f22a691741ca2e0aefdc9bd2eb/pywindow/molecular.py#L963-L1009
def decipher_atom_keys(self, forcefield='DLF', dict_key='atom_ids'): """ Decipher force field atom ids. This takes all values in :attr:`MolecularSystem.system['atom_ids']` that match force field type criteria and creates :attr:`MolecularSystem.system['elements']` with the corres...
[ "def", "decipher_atom_keys", "(", "self", ",", "forcefield", "=", "'DLF'", ",", "dict_key", "=", "'atom_ids'", ")", ":", "# In case there is no 'atom_ids' key we try 'elements'. This is for", "# XYZ and MOL files mostly. But, we keep the dict_key keyword for", "# someone who would wa...
Decipher force field atom ids. This takes all values in :attr:`MolecularSystem.system['atom_ids']` that match force field type criteria and creates :attr:`MolecularSystem.system['elements']` with the corresponding periodic table of elements equivalents. If a forcefield is not s...
[ "Decipher", "force", "field", "atom", "ids", "." ]
python
train
ArchiveTeam/wpull
wpull/protocol/http/web.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/web.py#L114-L131
def download(self, file: Optional[IO[bytes]]=None, duration_timeout: Optional[float]=None): '''Download content. Args: file: An optional file object for the document contents. duration_timeout: Maximum time in seconds of which the entire file mus...
[ "def", "download", "(", "self", ",", "file", ":", "Optional", "[", "IO", "[", "bytes", "]", "]", "=", "None", ",", "duration_timeout", ":", "Optional", "[", "float", "]", "=", "None", ")", ":", "yield", "from", "self", ".", "_current_session", ".", "...
Download content. Args: file: An optional file object for the document contents. duration_timeout: Maximum time in seconds of which the entire file must be read. Returns: Response: An instance of :class:`.http.request.Response`. See :meth:`W...
[ "Download", "content", "." ]
python
train
mlperf/training
translation/tensorflow/transformer/data_download.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/data_download.py#L210-L214
def txt_line_iterator(path): """Iterate through lines of file.""" with tf.gfile.Open(path) as f: for line in f: yield line.strip()
[ "def", "txt_line_iterator", "(", "path", ")", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "path", ")", "as", "f", ":", "for", "line", "in", "f", ":", "yield", "line", ".", "strip", "(", ")" ]
Iterate through lines of file.
[ "Iterate", "through", "lines", "of", "file", "." ]
python
train
wummel/linkchecker
linkcheck/parser/__init__.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/parser/__init__.py#L60-L64
def parse_chromium (url_data): """Parse a Chromium or Google Chrome bookmark file.""" from ..bookmarks.chromium import parse_bookmark_data for url, name in parse_bookmark_data(url_data.get_content()): url_data.add_url(url, name=name)
[ "def", "parse_chromium", "(", "url_data", ")", ":", "from", ".", ".", "bookmarks", ".", "chromium", "import", "parse_bookmark_data", "for", "url", ",", "name", "in", "parse_bookmark_data", "(", "url_data", ".", "get_content", "(", ")", ")", ":", "url_data", ...
Parse a Chromium or Google Chrome bookmark file.
[ "Parse", "a", "Chromium", "or", "Google", "Chrome", "bookmark", "file", "." ]
python
train
h2non/paco
paco/observer.py
https://github.com/h2non/paco/blob/1e5ef4df317e7cbbcefdf67d8dee28ce90538f3d/paco/observer.py#L23-L42
def observe(self, event, fn): """ Arguments: event (str): event to subscribe. fn (function|coroutinefunction): function to trigger. Raises: TypeError: if fn argument is not valid """ iscoroutine = asyncio.iscoroutinefunction(fn) if not...
[ "def", "observe", "(", "self", ",", "event", ",", "fn", ")", ":", "iscoroutine", "=", "asyncio", ".", "iscoroutinefunction", "(", "fn", ")", "if", "not", "iscoroutine", "and", "not", "isfunction", "(", "fn", ")", ":", "raise", "TypeError", "(", "'paco: f...
Arguments: event (str): event to subscribe. fn (function|coroutinefunction): function to trigger. Raises: TypeError: if fn argument is not valid
[ "Arguments", ":", "event", "(", "str", ")", ":", "event", "to", "subscribe", ".", "fn", "(", "function|coroutinefunction", ")", ":", "function", "to", "trigger", "." ]
python
train
django-extensions/django-extensions
django_extensions/management/commands/sqldsn.py
https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/management/commands/sqldsn.py#L100-L141
def _postgresql(self, dbhost, dbport, dbname, dbuser, dbpass, dsn_style=None): # noqa """PostgreSQL psycopg2 driver accepts two syntaxes Plus a string for .pgpass file """ dsn = [] if dsn_style is None or dsn_style == 'all' or dsn_style == 'keyvalue': dsnstr = "ho...
[ "def", "_postgresql", "(", "self", ",", "dbhost", ",", "dbport", ",", "dbname", ",", "dbuser", ",", "dbpass", ",", "dsn_style", "=", "None", ")", ":", "# noqa", "dsn", "=", "[", "]", "if", "dsn_style", "is", "None", "or", "dsn_style", "==", "'all'", ...
PostgreSQL psycopg2 driver accepts two syntaxes Plus a string for .pgpass file
[ "PostgreSQL", "psycopg2", "driver", "accepts", "two", "syntaxes" ]
python
train
portfors-lab/sparkle
sparkle/gui/controlwindow.py
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/controlwindow.py#L399-L415
def closeEvent(self, event): """Closes listening threads and saves GUI data for later use. Re-implemented from :qtdoc:`QWidget` """ self.acqmodel.stop_listening() # close listener threads self.saveInputs(self.inputsFilename) # save GUI size settings = QtCore.QSe...
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "self", ".", "acqmodel", ".", "stop_listening", "(", ")", "# close listener threads", "self", ".", "saveInputs", "(", "self", ".", "inputsFilename", ")", "# save GUI size", "settings", "=", "QtCore", "....
Closes listening threads and saves GUI data for later use. Re-implemented from :qtdoc:`QWidget`
[ "Closes", "listening", "threads", "and", "saves", "GUI", "data", "for", "later", "use", "." ]
python
train
pyviz/holoviews
holoviews/core/util.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/util.py#L1299-L1314
def is_cyclic(graph): """ Return True if the directed graph g has a cycle. The directed graph should be represented as a dictionary mapping of edges for each node. """ path = set() def visit(vertex): path.add(vertex) for neighbour in graph.get(vertex, ()): if neighbo...
[ "def", "is_cyclic", "(", "graph", ")", ":", "path", "=", "set", "(", ")", "def", "visit", "(", "vertex", ")", ":", "path", ".", "add", "(", "vertex", ")", "for", "neighbour", "in", "graph", ".", "get", "(", "vertex", ",", "(", ")", ")", ":", "i...
Return True if the directed graph g has a cycle. The directed graph should be represented as a dictionary mapping of edges for each node.
[ "Return", "True", "if", "the", "directed", "graph", "g", "has", "a", "cycle", ".", "The", "directed", "graph", "should", "be", "represented", "as", "a", "dictionary", "mapping", "of", "edges", "for", "each", "node", "." ]
python
train
slarse/pdfebc-core
pdfebc_core/email_utils.py
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/email_utils.py#L53-L65
def _attach_files(filepaths, email_): """Take a list of filepaths and attach the files to a MIMEMultipart. Args: filepaths (list(str)): A list of filepaths. email_ (email.MIMEMultipart): A MIMEMultipart email_. """ for filepath in filepaths: base = os.path.basename(filepath) ...
[ "def", "_attach_files", "(", "filepaths", ",", "email_", ")", ":", "for", "filepath", "in", "filepaths", ":", "base", "=", "os", ".", "path", ".", "basename", "(", "filepath", ")", "with", "open", "(", "filepath", ",", "\"rb\"", ")", "as", "file", ":",...
Take a list of filepaths and attach the files to a MIMEMultipart. Args: filepaths (list(str)): A list of filepaths. email_ (email.MIMEMultipart): A MIMEMultipart email_.
[ "Take", "a", "list", "of", "filepaths", "and", "attach", "the", "files", "to", "a", "MIMEMultipart", "." ]
python
train
saltstack/salt
salt/state.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1346-L1353
def verify_chunks(self, chunks): ''' Verify the chunks in a list of low data structures ''' err = [] for chunk in chunks: err.extend(self.verify_data(chunk)) return err
[ "def", "verify_chunks", "(", "self", ",", "chunks", ")", ":", "err", "=", "[", "]", "for", "chunk", "in", "chunks", ":", "err", ".", "extend", "(", "self", ".", "verify_data", "(", "chunk", ")", ")", "return", "err" ]
Verify the chunks in a list of low data structures
[ "Verify", "the", "chunks", "in", "a", "list", "of", "low", "data", "structures" ]
python
train
auth0/auth0-python
auth0/v3/authentication/social.py
https://github.com/auth0/auth0-python/blob/34adad3f342226aaaa6071387fa405ab840e5c02/auth0/v3/authentication/social.py#L12-L40
def login(self, client_id, access_token, connection, scope='openid'): """Login using a social provider's access token Given the social provider's access_token and the connection specified, it will do the authentication on the provider and return a dict with the access_token and id_token...
[ "def", "login", "(", "self", ",", "client_id", ",", "access_token", ",", "connection", ",", "scope", "=", "'openid'", ")", ":", "return", "self", ".", "post", "(", "'https://{}/oauth/access_token'", ".", "format", "(", "self", ".", "domain", ")", ",", "dat...
Login using a social provider's access token Given the social provider's access_token and the connection specified, it will do the authentication on the provider and return a dict with the access_token and id_token. Currently, this endpoint only works for Facebook, Google, Twitter and W...
[ "Login", "using", "a", "social", "provider", "s", "access", "token" ]
python
train
google/dotty
efilter/transforms/normalize.py
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/transforms/normalize.py#L80-L112
def normalize(expr): """Pass through n-ary expressions, and eliminate empty branches. Variadic and binary expressions recursively visit all their children. If all children are eliminated then the parent expression is also eliminated: (& [removed] [removed]) => [removed] If only one child is ...
[ "def", "normalize", "(", "expr", ")", ":", "children", "=", "[", "]", "for", "child", "in", "expr", ".", "children", ":", "branch", "=", "normalize", "(", "child", ")", "if", "branch", "is", "None", ":", "continue", "if", "type", "(", "branch", ")", ...
Pass through n-ary expressions, and eliminate empty branches. Variadic and binary expressions recursively visit all their children. If all children are eliminated then the parent expression is also eliminated: (& [removed] [removed]) => [removed] If only one child is left, it is promoted to repl...
[ "Pass", "through", "n", "-", "ary", "expressions", "and", "eliminate", "empty", "branches", "." ]
python
train
juju/charm-helpers
charmhelpers/contrib/openstack/ip.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ip.py#L64-L79
def canonical_url(configs, endpoint_type=PUBLIC): """Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :param configs: OSTemplateRenderer config templating object to inspect for a complete https context. :param endpo...
[ "def", "canonical_url", "(", "configs", ",", "endpoint_type", "=", "PUBLIC", ")", ":", "scheme", "=", "_get_scheme", "(", "configs", ")", "address", "=", "resolve_address", "(", "endpoint_type", ")", "if", "is_ipv6", "(", "address", ")", ":", "address", "=",...
Returns the correct HTTP URL to this host given the state of HTTPS configuration, hacluster and charm configuration. :param configs: OSTemplateRenderer config templating object to inspect for a complete https context. :param endpoint_type: str endpoint type to resolve. :param return...
[ "Returns", "the", "correct", "HTTP", "URL", "to", "this", "host", "given", "the", "state", "of", "HTTPS", "configuration", "hacluster", "and", "charm", "configuration", "." ]
python
train
postlund/pyatv
pyatv/dmap/__init__.py
https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/dmap/__init__.py#L70-L73
def controlprompt_cmd(self, cmd): """Perform a "controlpromptentry" command.""" data = tags.string_tag('cmbe', cmd) + tags.uint8_tag('cmcc', 0) return self.daap.post(_CTRL_PROMPT_CMD, data=data)
[ "def", "controlprompt_cmd", "(", "self", ",", "cmd", ")", ":", "data", "=", "tags", ".", "string_tag", "(", "'cmbe'", ",", "cmd", ")", "+", "tags", ".", "uint8_tag", "(", "'cmcc'", ",", "0", ")", "return", "self", ".", "daap", ".", "post", "(", "_C...
Perform a "controlpromptentry" command.
[ "Perform", "a", "controlpromptentry", "command", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/core/library_manager.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/library_manager.py#L213-L310
def get_os_path_to_library(self, library_path, library_name, allow_user_interaction=True): """Find library_os_path of library This function retrieves the file system library_os_path of a library specified by a library_path and a library_name. In case the library does not exist any more at its ...
[ "def", "get_os_path_to_library", "(", "self", ",", "library_path", ",", "library_name", ",", "allow_user_interaction", "=", "True", ")", ":", "original_path_and_name", "=", "os", ".", "path", ".", "join", "(", "library_path", ",", "library_name", ")", "library_pat...
Find library_os_path of library This function retrieves the file system library_os_path of a library specified by a library_path and a library_name. In case the library does not exist any more at its original location, the user has to specify an alternative location. :param str libra...
[ "Find", "library_os_path", "of", "library" ]
python
train
minhhoit/yacms
yacms/pages/templatetags/pages_tags.py
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/templatetags/pages_tags.py#L170-L203
def set_page_permissions(context, token): """ Assigns a permissions dict to the given page instance, combining Django's permission for the page's model and a permission check against the instance itself calling the page's ``can_add``, ``can_change`` and ``can_delete`` custom methods. Used withi...
[ "def", "set_page_permissions", "(", "context", ",", "token", ")", ":", "page", "=", "context", "[", "token", ".", "split_contents", "(", ")", "[", "1", "]", "]", "model", "=", "page", ".", "get_content_model", "(", ")", "try", ":", "opts", "=", "model"...
Assigns a permissions dict to the given page instance, combining Django's permission for the page's model and a permission check against the instance itself calling the page's ``can_add``, ``can_change`` and ``can_delete`` custom methods. Used within the change list for pages, to implement permission ...
[ "Assigns", "a", "permissions", "dict", "to", "the", "given", "page", "instance", "combining", "Django", "s", "permission", "for", "the", "page", "s", "model", "and", "a", "permission", "check", "against", "the", "instance", "itself", "calling", "the", "page", ...
python
train
pyslackers/slack-sansio
slack/sansio.py
https://github.com/pyslackers/slack-sansio/blob/068ddd6480c6d2f9bf14fa4db498c9fe1017f4ab/slack/sansio.py#L203-L219
def decode_response(status: int, headers: MutableMapping, body: bytes) -> dict: """ Decode incoming response Args: status: Response status headers: Response headers body: Response body Returns: Response data """ data = decode_body(headers, body) raise_for_st...
[ "def", "decode_response", "(", "status", ":", "int", ",", "headers", ":", "MutableMapping", ",", "body", ":", "bytes", ")", "->", "dict", ":", "data", "=", "decode_body", "(", "headers", ",", "body", ")", "raise_for_status", "(", "status", ",", "headers", ...
Decode incoming response Args: status: Response status headers: Response headers body: Response body Returns: Response data
[ "Decode", "incoming", "response" ]
python
train
kimvais/ike
ike/util/external.py
https://github.com/kimvais/ike/blob/4a5622c878a43a3d3cc19c54aa7cc7be29318eae/ike/util/external.py#L13-L25
def run_setkey(input): """ Runs a script through the 'setkey' command that is a user space insterface for PFKEY. :param input: setkey configuration file contents. """ SETKEY_BINARY = '/usr/sbin/setkey' fd, filename = tempfile.mkstemp('w') f = os.fdopen(fd, 'w') f.write(input) f.close...
[ "def", "run_setkey", "(", "input", ")", ":", "SETKEY_BINARY", "=", "'/usr/sbin/setkey'", "fd", ",", "filename", "=", "tempfile", ".", "mkstemp", "(", "'w'", ")", "f", "=", "os", ".", "fdopen", "(", "fd", ",", "'w'", ")", "f", ".", "write", "(", "inpu...
Runs a script through the 'setkey' command that is a user space insterface for PFKEY. :param input: setkey configuration file contents.
[ "Runs", "a", "script", "through", "the", "setkey", "command", "that", "is", "a", "user", "space", "insterface", "for", "PFKEY", ".", ":", "param", "input", ":", "setkey", "configuration", "file", "contents", "." ]
python
train
proycon/pynlpl
pynlpl/formats/folia.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L4521-L4539
def append(self, child, *args, **kwargs): """See :meth:`AbstractElement.append`""" #if no set is associated with the layer yet, we learn it from span annotation elements that are added if self.set is False or self.set is None: if inspect.isclass(child): if issubclass(...
[ "def", "append", "(", "self", ",", "child", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#if no set is associated with the layer yet, we learn it from span annotation elements that are added", "if", "self", ".", "set", "is", "False", "or", "self", ".", "set...
See :meth:`AbstractElement.append`
[ "See", ":", "meth", ":", "AbstractElement", ".", "append" ]
python
train
ArduPilot/MAVProxy
MAVProxy/modules/lib/MacOS/backend_wx.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/backend_wx.py#L816-L825
def draw(self, drawDC=None): """ Render the figure using RendererWx instance renderer, or using a previously defined renderer if none is specified. """ DEBUG_MSG("draw()", 1, self) self.renderer = RendererWx(self.bitmap, self.figure.dpi) self.figure.draw(self.rend...
[ "def", "draw", "(", "self", ",", "drawDC", "=", "None", ")", ":", "DEBUG_MSG", "(", "\"draw()\"", ",", "1", ",", "self", ")", "self", ".", "renderer", "=", "RendererWx", "(", "self", ".", "bitmap", ",", "self", ".", "figure", ".", "dpi", ")", "self...
Render the figure using RendererWx instance renderer, or using a previously defined renderer if none is specified.
[ "Render", "the", "figure", "using", "RendererWx", "instance", "renderer", "or", "using", "a", "previously", "defined", "renderer", "if", "none", "is", "specified", "." ]
python
train
tensorlayer/tensorlayer
tensorlayer/prepro.py
https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/prepro.py#L2230-L2253
def find_contours(x, level=0.8, fully_connected='low', positive_orientation='low'): """Find iso-valued contours in a 2D array for a given level value, returns list of (n, 2)-ndarrays see `skimage.measure.find_contours <http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.find_contours>`__. ...
[ "def", "find_contours", "(", "x", ",", "level", "=", "0.8", ",", "fully_connected", "=", "'low'", ",", "positive_orientation", "=", "'low'", ")", ":", "return", "skimage", ".", "measure", ".", "find_contours", "(", "x", ",", "level", ",", "fully_connected", ...
Find iso-valued contours in a 2D array for a given level value, returns list of (n, 2)-ndarrays see `skimage.measure.find_contours <http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.find_contours>`__. Parameters ------------ x : 2D ndarray of double. Input data in which ...
[ "Find", "iso", "-", "valued", "contours", "in", "a", "2D", "array", "for", "a", "given", "level", "value", "returns", "list", "of", "(", "n", "2", ")", "-", "ndarrays", "see", "skimage", ".", "measure", ".", "find_contours", "<http", ":", "//", "scikit...
python
valid
syndbg/demonoid-api
demonoid/parser.py
https://github.com/syndbg/demonoid-api/blob/518aa389ac91b5243b92fc19923103f31041a61e/demonoid/parser.py#L124-L151
def parse_second_row(row, url): """ Static method that parses a given table row element by using helper methods `Parser.parse_category_subcategory_and_or_quality`, `Parser.parse_torrent_link` and scrapping torrent's category, subcategory, quality, language, user, user url, torrent link, size, ...
[ "def", "parse_second_row", "(", "row", ",", "url", ")", ":", "tags", "=", "row", ".", "findall", "(", "'./td'", ")", "category", ",", "subcategory", ",", "quality", ",", "language", "=", "Parser", ".", "parse_torrent_properties", "(", "tags", "[", "0", "...
Static method that parses a given table row element by using helper methods `Parser.parse_category_subcategory_and_or_quality`, `Parser.parse_torrent_link` and scrapping torrent's category, subcategory, quality, language, user, user url, torrent link, size, comments, times completed, seeders and leecher...
[ "Static", "method", "that", "parses", "a", "given", "table", "row", "element", "by", "using", "helper", "methods", "Parser", ".", "parse_category_subcategory_and_or_quality", "Parser", ".", "parse_torrent_link", "and", "scrapping", "torrent", "s", "category", "subcate...
python
train
PythonCharmers/python-future
docs/3rd-party-py3k-compat-code/pandas_py3k.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/docs/3rd-party-py3k-compat-code/pandas_py3k.py#L505-L515
def most_common(self, n=None): '''List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abracadabra').most_common(3) [('a', 5), ('r', 2), ('b', 2)] ''' if n is None: retu...
[ "def", "most_common", "(", "self", ",", "n", "=", "None", ")", ":", "if", "n", "is", "None", ":", "return", "sorted", "(", "iteritems", "(", "self", ")", ",", "key", "=", "itemgetter", "(", "1", ")", ",", "reverse", "=", "True", ")", "return", "n...
List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter('abracadabra').most_common(3) [('a', 5), ('r', 2), ('b', 2)]
[ "List", "the", "n", "most", "common", "elements", "and", "their", "counts", "from", "the", "most", "common", "to", "the", "least", ".", "If", "n", "is", "None", "then", "list", "all", "element", "counts", "." ]
python
train
jepegit/cellpy
cellpy/parameters/prmreader.py
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/parameters/prmreader.py#L56-L72
def _pack_prms(): """if you introduce new 'save-able' parameter dictionaries, then you have to include them here""" config_dict = { "Paths": prms.Paths.to_dict(), "FileNames": prms.FileNames.to_dict(), "Db": prms.Db.to_dict(), "DbCols": prms.DbCols.to_dict(), "DataSe...
[ "def", "_pack_prms", "(", ")", ":", "config_dict", "=", "{", "\"Paths\"", ":", "prms", ".", "Paths", ".", "to_dict", "(", ")", ",", "\"FileNames\"", ":", "prms", ".", "FileNames", ".", "to_dict", "(", ")", ",", "\"Db\"", ":", "prms", ".", "Db", ".", ...
if you introduce new 'save-able' parameter dictionaries, then you have to include them here
[ "if", "you", "introduce", "new", "save", "-", "able", "parameter", "dictionaries", "then", "you", "have", "to", "include", "them", "here" ]
python
train
SmartTeleMax/iktomi
iktomi/web/url.py
https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/url.py#L181-L190
def qs_add(self, *args, **kwargs): '''Add value to QuerySet MultiDict''' query = self.query.copy() if args: mdict = MultiDict(args[0]) for k, v in mdict.items(): query.add(k, v) for k, v in kwargs.items(): query.add(k, v) return...
[ "def", "qs_add", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "query", ".", "copy", "(", ")", "if", "args", ":", "mdict", "=", "MultiDict", "(", "args", "[", "0", "]", ")", "for", "k", ",", "v",...
Add value to QuerySet MultiDict
[ "Add", "value", "to", "QuerySet", "MultiDict" ]
python
train
KelSolaar/Umbra
umbra/managers/actions_manager.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/managers/actions_manager.py#L134-L145
def root_namespace(self, value): """ Setter for **self.__root_namespace** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( ...
[ "def", "root_namespace", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "unicode", ",", "\"'{0}' attribute: '{1}' type is not 'unicode'!\"", ".", "format", "(", "\"root_namespace\"", ",", ...
Setter for **self.__root_namespace** attribute. :param value: Attribute value. :type value: unicode
[ "Setter", "for", "**", "self", ".", "__root_namespace", "**", "attribute", "." ]
python
train
python-security/pyt
pyt/cfg/stmt_visitor_helper.py
https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/cfg/stmt_visitor_helper.py#L61-L73
def connect_nodes(nodes): """Connect the nodes in a list linearly.""" for n, next_node in zip(nodes, nodes[1:]): if isinstance(n, ControlFlowNode): _connect_control_flow_node(n, next_node) elif isinstance(next_node, ControlFlowNode): n.connect(next_node.test) elif...
[ "def", "connect_nodes", "(", "nodes", ")", ":", "for", "n", ",", "next_node", "in", "zip", "(", "nodes", ",", "nodes", "[", "1", ":", "]", ")", ":", "if", "isinstance", "(", "n", ",", "ControlFlowNode", ")", ":", "_connect_control_flow_node", "(", "n",...
Connect the nodes in a list linearly.
[ "Connect", "the", "nodes", "in", "a", "list", "linearly", "." ]
python
train
calston/tensor
tensor/utils.py
https://github.com/calston/tensor/blob/7c0c99708b5dbff97f3895f705e11996b608549d/tensor/utils.py#L329-L342
def expire(self, age): """Expire any items in the cache older than `age` seconds""" now = time.time() cache = self._acquire_cache() expired = [k for k, v in cache.items() if (now - v[0]) > age] for k in expired: if k in cache: del cache[k] ...
[ "def", "expire", "(", "self", ",", "age", ")", ":", "now", "=", "time", ".", "time", "(", ")", "cache", "=", "self", ".", "_acquire_cache", "(", ")", "expired", "=", "[", "k", "for", "k", ",", "v", "in", "cache", ".", "items", "(", ")", "if", ...
Expire any items in the cache older than `age` seconds
[ "Expire", "any", "items", "in", "the", "cache", "older", "than", "age", "seconds" ]
python
test
alejandroautalan/pygubu
pygubudesigner/main.py
https://github.com/alejandroautalan/pygubu/blob/41c8fb37ef973736ec5d68cbe1cd4ecb78712e40/pygubudesigner/main.py#L514-L520
def load_file(self, filename): """Load xml into treeview""" self.tree_editor.load_file(filename) self.project_name.configure(text=filename) self.currentfile = filename self.is_changed = False
[ "def", "load_file", "(", "self", ",", "filename", ")", ":", "self", ".", "tree_editor", ".", "load_file", "(", "filename", ")", "self", ".", "project_name", ".", "configure", "(", "text", "=", "filename", ")", "self", ".", "currentfile", "=", "filename", ...
Load xml into treeview
[ "Load", "xml", "into", "treeview" ]
python
train
Autodesk/cryptorito
cryptorito/__init__.py
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L282-L289
def fingerprint_from_file(filename): """Extract a fingerprint from a GPG public key file""" cmd = flatten([gnupg_bin(), gnupg_home(), filename]) outp = stderr_output(cmd).split('\n') if not outp[0].startswith('pub'): raise CryptoritoError('probably an invalid gpg key') return outp[1].strip(...
[ "def", "fingerprint_from_file", "(", "filename", ")", ":", "cmd", "=", "flatten", "(", "[", "gnupg_bin", "(", ")", ",", "gnupg_home", "(", ")", ",", "filename", "]", ")", "outp", "=", "stderr_output", "(", "cmd", ")", ".", "split", "(", "'\\n'", ")", ...
Extract a fingerprint from a GPG public key file
[ "Extract", "a", "fingerprint", "from", "a", "GPG", "public", "key", "file" ]
python
train
dls-controls/annotypes
annotypes/_fake_typing.py
https://github.com/dls-controls/annotypes/blob/31ab68a0367bb70ebd9898e8b9fa9405423465bd/annotypes/_fake_typing.py#L143-L154
def _next_in_mro(cls): """Helper for Generic.__new__. Returns the class after the last occurrence of Generic or Generic[...] in cls.__mro__. """ next_in_mro = object # Look for the last occurrence of Generic or Generic[...]. for i, c in enumerate(cls.__mro__[:-1]): if isinstance(c, ...
[ "def", "_next_in_mro", "(", "cls", ")", ":", "next_in_mro", "=", "object", "# Look for the last occurrence of Generic or Generic[...].", "for", "i", ",", "c", "in", "enumerate", "(", "cls", ".", "__mro__", "[", ":", "-", "1", "]", ")", ":", "if", "isinstance",...
Helper for Generic.__new__. Returns the class after the last occurrence of Generic or Generic[...] in cls.__mro__.
[ "Helper", "for", "Generic", ".", "__new__", "." ]
python
train
wonambi-python/wonambi
wonambi/ioeeg/fieldtrip.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/fieldtrip.py#L31-L86
def return_hdr(self): """Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str ...
[ "def", "return_hdr", "(", "self", ")", ":", "# fieldtrip does not have this information", "orig", "=", "dict", "(", ")", "subj_id", "=", "str", "(", ")", "start_time", "=", "datetime", ".", "fromordinal", "(", "1", ")", "# fake", "try", ":", "ft_data", "=", ...
Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str list of all the channels...
[ "Return", "the", "header", "for", "further", "use", "." ]
python
train
rocky/python-uncompyle6
uncompyle6/verify.py
https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/verify.py#L150-L362
def cmp_code_objects(version, is_pypy, code_obj1, code_obj2, verify, name=''): """ Compare two code-objects. This is the main part of this module. """ # print code_obj1, type(code_obj2) assert iscode(code_obj1), \ "cmp_code_object first object type is %s, not code" % ...
[ "def", "cmp_code_objects", "(", "version", ",", "is_pypy", ",", "code_obj1", ",", "code_obj2", ",", "verify", ",", "name", "=", "''", ")", ":", "# print code_obj1, type(code_obj2)", "assert", "iscode", "(", "code_obj1", ")", ",", "\"cmp_code_object first object type...
Compare two code-objects. This is the main part of this module.
[ "Compare", "two", "code", "-", "objects", "." ]
python
train
AguaClara/aguaclara
aguaclara/core/physchem.py
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/physchem.py#L414-L420
def num_orifices(FlowPlant, RatioVCOrifice, HeadLossOrifice, DiamOrifice): """Return the number of orifices.""" #Inputs do not need to be checked here because they are checked by #functions this function calls. return np.ceil(area_orifice(HeadLossOrifice, RatioVCOrifice, ...
[ "def", "num_orifices", "(", "FlowPlant", ",", "RatioVCOrifice", ",", "HeadLossOrifice", ",", "DiamOrifice", ")", ":", "#Inputs do not need to be checked here because they are checked by", "#functions this function calls.", "return", "np", ".", "ceil", "(", "area_orifice", "("...
Return the number of orifices.
[ "Return", "the", "number", "of", "orifices", "." ]
python
train
ronaldguillen/wave
wave/fields.py
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L1511-L1522
def to_internal_value(self, data): """ Dicts of native values <- Dicts of primitive datatypes. """ if html.is_html_input(data): data = html.parse_html_dict(data) if not isinstance(data, dict): self.fail('not_a_dict', input_type=type(data).__name__) ...
[ "def", "to_internal_value", "(", "self", ",", "data", ")", ":", "if", "html", ".", "is_html_input", "(", "data", ")", ":", "data", "=", "html", ".", "parse_html_dict", "(", "data", ")", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "...
Dicts of native values <- Dicts of primitive datatypes.
[ "Dicts", "of", "native", "values", "<", "-", "Dicts", "of", "primitive", "datatypes", "." ]
python
train
databio/pypiper
pypiper/utils.py
https://github.com/databio/pypiper/blob/00e6c2b94033c4187d47ff14c5580bbfc2ff097f/pypiper/utils.py#L149-L193
def checkpoint_filepath(checkpoint, pm): """ Create filepath for indicated checkpoint. :param str | pypiper.Stage checkpoint: Pipeline phase/stage or one's name :param pypiper.PipelineManager | pypiper.Pipeline pm: manager of a pipeline instance, relevant for output folder path. :return str...
[ "def", "checkpoint_filepath", "(", "checkpoint", ",", "pm", ")", ":", "# Handle case in which checkpoint is given not just as a string, but", "# as a checkpoint-like filename. Don't worry about absolute path status", "# of a potential filename input, or whether it's in the pipeline's", "# outp...
Create filepath for indicated checkpoint. :param str | pypiper.Stage checkpoint: Pipeline phase/stage or one's name :param pypiper.PipelineManager | pypiper.Pipeline pm: manager of a pipeline instance, relevant for output folder path. :return str: standardized checkpoint name for file, plus extensi...
[ "Create", "filepath", "for", "indicated", "checkpoint", "." ]
python
train
aws/aws-iot-device-sdk-python
AWSIoTPythonSDK/core/protocol/paho/client.py
https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1399-L1411
def loop_stop(self, force=False): """This is part of the threaded client interface. Call this once to stop the network thread previously created with loop_start(). This call will block until the network thread finishes. The force parameter is currently ignored. """ if se...
[ "def", "loop_stop", "(", "self", ",", "force", "=", "False", ")", ":", "if", "self", ".", "_thread", "is", "None", ":", "return", "MQTT_ERR_INVAL", "self", ".", "_thread_terminate", "=", "True", "self", ".", "_thread", ".", "join", "(", ")", "self", "....
This is part of the threaded client interface. Call this once to stop the network thread previously created with loop_start(). This call will block until the network thread finishes. The force parameter is currently ignored.
[ "This", "is", "part", "of", "the", "threaded", "client", "interface", ".", "Call", "this", "once", "to", "stop", "the", "network", "thread", "previously", "created", "with", "loop_start", "()", ".", "This", "call", "will", "block", "until", "the", "network",...
python
train
wmayner/pyphi
pyphi/convert.py
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/convert.py#L176-L190
def to_multidimensional(tpm): """Reshape a state-by-node TPM to the multidimensional form. See documentation for the |Network| object for more information on TPM formats. """ # Cast to np.array. tpm = np.array(tpm) # Get the number of nodes. N = tpm.shape[-1] # Reshape. We use Fortr...
[ "def", "to_multidimensional", "(", "tpm", ")", ":", "# Cast to np.array.", "tpm", "=", "np", ".", "array", "(", "tpm", ")", "# Get the number of nodes.", "N", "=", "tpm", ".", "shape", "[", "-", "1", "]", "# Reshape. We use Fortran ordering here so that the rows use...
Reshape a state-by-node TPM to the multidimensional form. See documentation for the |Network| object for more information on TPM formats.
[ "Reshape", "a", "state", "-", "by", "-", "node", "TPM", "to", "the", "multidimensional", "form", "." ]
python
train
hobson/pug-invest
pug/invest/sandbox/sim.py
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L678-L701
def clipping_params(ts, capacity=100): """Start and end index that clips the price/value of a time series the most Assumes that the integrated maximum includes the peak (instantaneous maximum). Arguments: ts (TimeSeries): Time series to attempt to clip to as low a max value as possible capacit...
[ "def", "clipping_params", "(", "ts", ",", "capacity", "=", "100", ")", ":", "ts_sorted", "=", "ts", ".", "order", "(", "ascending", "=", "False", ")", "i", ",", "t0", ",", "t1", ",", "integral", "=", "1", ",", "None", ",", "None", ",", "0", "whil...
Start and end index that clips the price/value of a time series the most Assumes that the integrated maximum includes the peak (instantaneous maximum). Arguments: ts (TimeSeries): Time series to attempt to clip to as low a max value as possible capacity (float): Total "funds" or "energy" available...
[ "Start", "and", "end", "index", "that", "clips", "the", "price", "/", "value", "of", "a", "time", "series", "the", "most" ]
python
train