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
fhamborg/news-please
newsplease/crawler/simple_crawler.py
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/crawler/simple_crawler.py#L21-L36
def _fetch_url(url, is_threaded, timeout=None): """ Crawls the html content of the parameter url and saves the html in _results :param url: :param is_threaded: If True, results will be stored for later processing by the fetch_urls method. Else not. :param timeout: in seconds, if ...
[ "def", "_fetch_url", "(", "url", ",", "is_threaded", ",", "timeout", "=", "None", ")", ":", "headers", "=", "{", "'User-Agent'", ":", "'Mozilla/5.0'", "}", "req", "=", "urllib", ".", "request", ".", "Request", "(", "url", ",", "None", ",", "headers", "...
Crawls the html content of the parameter url and saves the html in _results :param url: :param is_threaded: If True, results will be stored for later processing by the fetch_urls method. Else not. :param timeout: in seconds, if None, the urllib default is used :return: html of the url
[ "Crawls", "the", "html", "content", "of", "the", "parameter", "url", "and", "saves", "the", "html", "in", "_results", ":", "param", "url", ":", ":", "param", "is_threaded", ":", "If", "True", "results", "will", "be", "stored", "for", "later", "processing",...
python
train
bmuller/toquen-python
toquen/client.py
https://github.com/bmuller/toquen-python/blob/bfe4073a91b03b06b934aa20a174d96f7b7660e5/toquen/client.py#L67-L76
def ips_with_roles(self, roles, env=None, match_all=False): """ Returns a function that, when called, gets servers with the given roles. If env is given, then the environment must match as well. If match_all is True, then only return servers who have all of the given roles. Otherwise, ...
[ "def", "ips_with_roles", "(", "self", ",", "roles", ",", "env", "=", "None", ",", "match_all", "=", "False", ")", ":", "def", "func", "(", ")", ":", "return", "[", "s", "[", "'external_ip'", "]", "for", "s", "in", "self", ".", "servers_with_roles", "...
Returns a function that, when called, gets servers with the given roles. If env is given, then the environment must match as well. If match_all is True, then only return servers who have all of the given roles. Otherwise, return servers that have one or more of the given roles.
[ "Returns", "a", "function", "that", "when", "called", "gets", "servers", "with", "the", "given", "roles", ".", "If", "env", "is", "given", "then", "the", "environment", "must", "match", "as", "well", ".", "If", "match_all", "is", "True", "then", "only", ...
python
train
FaradayRF/faradayio-cli
faradayio_cli/faradayio_cli.py
https://github.com/FaradayRF/faradayio-cli/blob/5acac033f3e44da7e89d97725eed9d336cf16f74/faradayio_cli/faradayio_cli.py#L15-L38
def setupArgparse(): """Sets up argparse module to create command line options and parse them. Uses the argparse module to add arguments to the command line for faradayio-cli. Once the arguments are added and parsed the arguments are returned Returns: argparse.Namespace: Populated namespac...
[ "def", "setupArgparse", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "# Required arguments", "parser", ".", "add_argument", "(", "\"callsign\"", ",", "help", "=", "\"Callsign of radio\"", ")", "parser", ".", "add_argument", "(", "\"...
Sets up argparse module to create command line options and parse them. Uses the argparse module to add arguments to the command line for faradayio-cli. Once the arguments are added and parsed the arguments are returned Returns: argparse.Namespace: Populated namespace of arguments
[ "Sets", "up", "argparse", "module", "to", "create", "command", "line", "options", "and", "parse", "them", "." ]
python
train
clalancette/pycdlib
pycdlib/rockridge.py
https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/rockridge.py#L2001-L2016
def record(self): # type: () -> bytes ''' Generate a string representing the Rock Ridge Platform Dependent record. Parameters: None. Returns: String containing the Rock Ridge record. ''' if not self._initialized: raise pycdli...
[ "def", "record", "(", "self", ")", ":", "# type: () -> bytes", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'PD record not yet initialized!'", ")", "return", "b'PD'", "+", "struct", ".", "pack", "("...
Generate a string representing the Rock Ridge Platform Dependent record. Parameters: None. Returns: String containing the Rock Ridge record.
[ "Generate", "a", "string", "representing", "the", "Rock", "Ridge", "Platform", "Dependent", "record", "." ]
python
train
philgyford/django-spectator
spectator/events/templatetags/spectator_events.py
https://github.com/philgyford/django-spectator/blob/f3c72004f9caa1fde0f5a3b2f0d2bf285fc01ada/spectator/events/templatetags/spectator_events.py#L179-L191
def most_seen_creators_card(event_kind=None, num=10): """ Displays a card showing the Creators that are associated with the most Events. """ object_list = most_seen_creators(event_kind=event_kind, num=num) object_list = chartify(object_list, 'num_events', cutoff=1) return { 'card_title...
[ "def", "most_seen_creators_card", "(", "event_kind", "=", "None", ",", "num", "=", "10", ")", ":", "object_list", "=", "most_seen_creators", "(", "event_kind", "=", "event_kind", ",", "num", "=", "num", ")", "object_list", "=", "chartify", "(", "object_list", ...
Displays a card showing the Creators that are associated with the most Events.
[ "Displays", "a", "card", "showing", "the", "Creators", "that", "are", "associated", "with", "the", "most", "Events", "." ]
python
train
Iotic-Labs/py-IoticAgent
src/IoticAgent/third/amqp/connection.py
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/third/amqp/connection.py#L304-L331
def drain_events(self, timeout=None): """Wait for an event on a channel.""" chanmap = self.channels chanid, method_sig, args, content = self._wait_multiple( chanmap, None, timeout=timeout, ) channel = chanmap[chanid] if (content and channel.a...
[ "def", "drain_events", "(", "self", ",", "timeout", "=", "None", ")", ":", "chanmap", "=", "self", ".", "channels", "chanid", ",", "method_sig", ",", "args", ",", "content", "=", "self", ".", "_wait_multiple", "(", "chanmap", ",", "None", ",", "timeout",...
Wait for an event on a channel.
[ "Wait", "for", "an", "event", "on", "a", "channel", "." ]
python
train
esterhui/pypu
pypu/service_flickr.py
https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L122-L141
def _update_config(self,directory,filename): """Manages FLICKR config files""" basefilename=os.path.splitext(filename)[0] ext=os.path.splitext(filename)[1].lower() if filename==LOCATION_FILE: print("%s - Updating geotag information"%(LOCATION_FILE)) return self._u...
[ "def", "_update_config", "(", "self", ",", "directory", ",", "filename", ")", ":", "basefilename", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "["...
Manages FLICKR config files
[ "Manages", "FLICKR", "config", "files" ]
python
train
Erotemic/utool
utool/util_ubuntu.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_ubuntu.py#L426-L446
def sorted_window_ids(order='mru'): """ Returns window ids orderd by criteria default is mru (most recently used) CommandLine: xprop -root | grep "^_NET_CLIENT_LIST_STACKING" | tr "," " " python -m utool.util_ubuntu XCtrl.sorted_window_ids """ imp...
[ "def", "sorted_window_ids", "(", "order", "=", "'mru'", ")", ":", "import", "utool", "as", "ut", "if", "order", "in", "[", "'mru'", ",", "'lru'", "]", ":", "cmdkw", "=", "dict", "(", "verbose", "=", "False", ",", "quiet", "=", "True", ",", "silence",...
Returns window ids orderd by criteria default is mru (most recently used) CommandLine: xprop -root | grep "^_NET_CLIENT_LIST_STACKING" | tr "," " " python -m utool.util_ubuntu XCtrl.sorted_window_ids
[ "Returns", "window", "ids", "orderd", "by", "criteria", "default", "is", "mru", "(", "most", "recently", "used", ")" ]
python
train
Nic30/hwt
hwt/simulator/types/simBits.py
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/types/simBits.py#L12-L22
def simBitsT(width: int, signed: Union[bool, None]): """ Construct SimBitsT with cache """ k = (width, signed) try: return __simBitsTCache[k] except KeyError: t = SimBitsT(width, signed) __simBitsTCache[k] = t return t
[ "def", "simBitsT", "(", "width", ":", "int", ",", "signed", ":", "Union", "[", "bool", ",", "None", "]", ")", ":", "k", "=", "(", "width", ",", "signed", ")", "try", ":", "return", "__simBitsTCache", "[", "k", "]", "except", "KeyError", ":", "t", ...
Construct SimBitsT with cache
[ "Construct", "SimBitsT", "with", "cache" ]
python
test
jmgilman/Neolib
neolib/pyamf/util/imports.py
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/imports.py#L107-L114
def _run_hooks(self, name, module): """ Run all hooks for a module. """ hooks = self.post_load_hooks.pop(name, []) for hook in hooks: hook(module)
[ "def", "_run_hooks", "(", "self", ",", "name", ",", "module", ")", ":", "hooks", "=", "self", ".", "post_load_hooks", ".", "pop", "(", "name", ",", "[", "]", ")", "for", "hook", "in", "hooks", ":", "hook", "(", "module", ")" ]
Run all hooks for a module.
[ "Run", "all", "hooks", "for", "a", "module", "." ]
python
train
pandas-dev/pandas
pandas/core/groupby/base.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/base.py#L96-L157
def whitelist_method_generator(base, klass, whitelist): """ Yields all GroupBy member defs for DataFrame/Series names in whitelist. Parameters ---------- base : class base class klass : class class where members are defined. Should be Series or DataFrame whitelist : ...
[ "def", "whitelist_method_generator", "(", "base", ",", "klass", ",", "whitelist", ")", ":", "method_wrapper_template", "=", "\"\"\"def %(name)s(%(sig)s) :\n \\\"\"\"\n %(doc)s\n \\\"\"\"\n f = %(self)s.__getattr__('%(name)s')\n return f(%(args)s)\"\"\"", "property_wrapper_te...
Yields all GroupBy member defs for DataFrame/Series names in whitelist. Parameters ---------- base : class base class klass : class class where members are defined. Should be Series or DataFrame whitelist : list list of names of klass methods to be constructed R...
[ "Yields", "all", "GroupBy", "member", "defs", "for", "DataFrame", "/", "Series", "names", "in", "whitelist", "." ]
python
train
jessamynsmith/paragres
paragres/command.py
https://github.com/jessamynsmith/paragres/blob/4e068cbfcafbe8f1b010741d38fb65d40de2c6aa/paragres/command.py#L57-L60
def error(self, message, code=1): """ Prints the error, and exits with the given code. """ sys.stderr.write(message) sys.exit(code)
[ "def", "error", "(", "self", ",", "message", ",", "code", "=", "1", ")", ":", "sys", ".", "stderr", ".", "write", "(", "message", ")", "sys", ".", "exit", "(", "code", ")" ]
Prints the error, and exits with the given code.
[ "Prints", "the", "error", "and", "exits", "with", "the", "given", "code", "." ]
python
train
SwissDataScienceCenter/renku-python
renku/cli/_exc.py
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/_exc.py#L133-L155
def _handle_github(self): """Handle exception and submit it as GitHub issue.""" value = click.prompt( _BUG + click.style( '1. Open an issue by typing "open";\n', fg='green', ) + click.style( '2. Print human-readable information by t...
[ "def", "_handle_github", "(", "self", ")", ":", "value", "=", "click", ".", "prompt", "(", "_BUG", "+", "click", ".", "style", "(", "'1. Open an issue by typing \"open\";\\n'", ",", "fg", "=", "'green'", ",", ")", "+", "click", ".", "style", "(", "'2. Prin...
Handle exception and submit it as GitHub issue.
[ "Handle", "exception", "and", "submit", "it", "as", "GitHub", "issue", "." ]
python
train
zhmcclient/python-zhmcclient
zhmcclient_mock/_urihandler.py
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_urihandler.py#L865-L875
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): """Operation: Create Password Rule.""" assert wait_for_completion is True # synchronous operation try: console = hmc.consoles.lookup_by_oid(None) except KeyError: raise...
[ "def", "post", "(", "method", ",", "hmc", ",", "uri", ",", "uri_parms", ",", "body", ",", "logon_required", ",", "wait_for_completion", ")", ":", "assert", "wait_for_completion", "is", "True", "# synchronous operation", "try", ":", "console", "=", "hmc", ".", ...
Operation: Create Password Rule.
[ "Operation", ":", "Create", "Password", "Rule", "." ]
python
train
thespacedoctor/qubits
qubits/datagenerator.py
https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/datagenerator.py#L245-L270
def plot_filter_transmissions(log, filterList): """ *Plot the filters on a single plot* **Key Arguments:** - ``log`` -- logger - ``filterList`` -- list of absolute paths to plain text files containing filter transmission profiles **Return:** - None """ ################ ...
[ "def", "plot_filter_transmissions", "(", "log", ",", "filterList", ")", ":", "################ > IMPORTS ################", "## STANDARD LIB ##", "## THIRD PARTY ##", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "numpy", "as", "np", "## LOCAL APPLICATION ##...
*Plot the filters on a single plot* **Key Arguments:** - ``log`` -- logger - ``filterList`` -- list of absolute paths to plain text files containing filter transmission profiles **Return:** - None
[ "*", "Plot", "the", "filters", "on", "a", "single", "plot", "*" ]
python
train
numenta/nupic
src/nupic/frameworks/opf/experiment_runner.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/experiment_runner.py#L686-L751
def run(self): """Runs a single experiment task""" self.__logger.debug("run(): Starting task <%s>", self.__task['taskLabel']) # Set up the task # Create our main loop-control iterator if self.__cmdOptions.privateOptions['testMode']: numIters = 10 else: numIters = self.__task['itera...
[ "def", "run", "(", "self", ")", ":", "self", ".", "__logger", ".", "debug", "(", "\"run(): Starting task <%s>\"", ",", "self", ".", "__task", "[", "'taskLabel'", "]", ")", "# Set up the task", "# Create our main loop-control iterator", "if", "self", ".", "__cmdOpt...
Runs a single experiment task
[ "Runs", "a", "single", "experiment", "task" ]
python
valid
cloudmesh/cloudmesh-common
cloudmesh/common/Shell.py
https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/Shell.py#L584-L595
def remove_line_with(cls, lines, what): """ returns all lines that do not contain what :param lines: :param what: :return: """ result = [] for line in lines: if what not in line: result = result + [line] return result
[ "def", "remove_line_with", "(", "cls", ",", "lines", ",", "what", ")", ":", "result", "=", "[", "]", "for", "line", "in", "lines", ":", "if", "what", "not", "in", "line", ":", "result", "=", "result", "+", "[", "line", "]", "return", "result" ]
returns all lines that do not contain what :param lines: :param what: :return:
[ "returns", "all", "lines", "that", "do", "not", "contain", "what", ":", "param", "lines", ":", ":", "param", "what", ":", ":", "return", ":" ]
python
train
edublancas/sklearn-evaluation
sklearn_evaluation/metrics.py
https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/metrics.py#L7-L29
def precision_at(y_true, y_score, proportion, ignore_nas=False): ''' Calculates precision at a given proportion. Only supports binary classification. ''' # Sort scores in descending order scores_sorted = np.sort(y_score)[::-1] # Based on the proportion, get the index to split the data #...
[ "def", "precision_at", "(", "y_true", ",", "y_score", ",", "proportion", ",", "ignore_nas", "=", "False", ")", ":", "# Sort scores in descending order", "scores_sorted", "=", "np", ".", "sort", "(", "y_score", ")", "[", ":", ":", "-", "1", "]", "# Based on t...
Calculates precision at a given proportion. Only supports binary classification.
[ "Calculates", "precision", "at", "a", "given", "proportion", ".", "Only", "supports", "binary", "classification", "." ]
python
train
google/transitfeed
merge.py
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L394-L411
def _MergeIdentical(self, a, b): """Tries to merge two values. The values are required to be identical. Args: a: The first value. b: The second value. Returns: The trivially merged value. Raises: MergeError: The values were not identical. """ if a != b: raise Mer...
[ "def", "_MergeIdentical", "(", "self", ",", "a", ",", "b", ")", ":", "if", "a", "!=", "b", ":", "raise", "MergeError", "(", "\"values must be identical ('%s' vs '%s')\"", "%", "(", "transitfeed", ".", "EncodeUnicode", "(", "a", ")", ",", "transitfeed", ".", ...
Tries to merge two values. The values are required to be identical. Args: a: The first value. b: The second value. Returns: The trivially merged value. Raises: MergeError: The values were not identical.
[ "Tries", "to", "merge", "two", "values", ".", "The", "values", "are", "required", "to", "be", "identical", "." ]
python
train
google-research/batch-ppo
agents/parts/normalize.py
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/parts/normalize.py#L124-L135
def summary(self): """Summary string of mean and standard deviation. Returns: Summary tensor. """ with tf.name_scope(self._name + '/summary'): mean_summary = tf.cond( self._count > 0, lambda: self._summary('mean', self._mean), str) std_summary = tf.cond( self._coun...
[ "def", "summary", "(", "self", ")", ":", "with", "tf", ".", "name_scope", "(", "self", ".", "_name", "+", "'/summary'", ")", ":", "mean_summary", "=", "tf", ".", "cond", "(", "self", ".", "_count", ">", "0", ",", "lambda", ":", "self", ".", "_summa...
Summary string of mean and standard deviation. Returns: Summary tensor.
[ "Summary", "string", "of", "mean", "and", "standard", "deviation", "." ]
python
train
joferkington/mpldatacursor
mpldatacursor/datacursor.py
https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L764-L770
def create_highlight(self, artist): """Create a new highlight for the given artist.""" highlight = copy.copy(artist) highlight.set(color=self.highlight_color, mec=self.highlight_color, lw=self.highlight_width, mew=self.highlight_width) artist.axes.add_artist(highlig...
[ "def", "create_highlight", "(", "self", ",", "artist", ")", ":", "highlight", "=", "copy", ".", "copy", "(", "artist", ")", "highlight", ".", "set", "(", "color", "=", "self", ".", "highlight_color", ",", "mec", "=", "self", ".", "highlight_color", ",", ...
Create a new highlight for the given artist.
[ "Create", "a", "new", "highlight", "for", "the", "given", "artist", "." ]
python
train
eumis/pyviews
pyviews/rendering/node.py
https://github.com/eumis/pyviews/blob/80a868242ee9cdc6f4ded594b3e0544cc238ed55/pyviews/rendering/node.py#L34-L48
def get_init_args(inst_type, init_args: dict, add_kwargs=False) -> Tuple[List, Dict]: '''Returns tuple with args and kwargs to pass it to inst_type constructor''' try: parameters = signature(inst_type).parameters.values() args_keys = [p.name for p in parameters \ if p.kind in [Pa...
[ "def", "get_init_args", "(", "inst_type", ",", "init_args", ":", "dict", ",", "add_kwargs", "=", "False", ")", "->", "Tuple", "[", "List", ",", "Dict", "]", ":", "try", ":", "parameters", "=", "signature", "(", "inst_type", ")", ".", "parameters", ".", ...
Returns tuple with args and kwargs to pass it to inst_type constructor
[ "Returns", "tuple", "with", "args", "and", "kwargs", "to", "pass", "it", "to", "inst_type", "constructor" ]
python
train
Xion/callee
callee/collections.py
https://github.com/Xion/callee/blob/58740f73ff9a76f5fe0075bf18d7345a0f9d961c/callee/collections.py#L163-L208
def _initialize(self, *args, **kwargs): """Initiaize the mapping matcher with constructor arguments.""" self.items = None self.keys = None self.values = None if args: if len(args) != 2: raise TypeError("expected exactly two positional arguments, " ...
[ "def", "_initialize", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "items", "=", "None", "self", ".", "keys", "=", "None", "self", ".", "values", "=", "None", "if", "args", ":", "if", "len", "(", "args", ")", "...
Initiaize the mapping matcher with constructor arguments.
[ "Initiaize", "the", "mapping", "matcher", "with", "constructor", "arguments", "." ]
python
train
mitsei/dlkit
dlkit/records/assessment/basic/base_records.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/basic/base_records.py#L35-L40
def has_provenance(self): """to handle deprecated mecqbank data""" if 'provenanceId' in self.my_osid_object._my_map: return bool(self.my_osid_object._my_map['provenanceId'] != '') else: return bool(self.my_osid_object._my_map['provenanceItemId'] != '')
[ "def", "has_provenance", "(", "self", ")", ":", "if", "'provenanceId'", "in", "self", ".", "my_osid_object", ".", "_my_map", ":", "return", "bool", "(", "self", ".", "my_osid_object", ".", "_my_map", "[", "'provenanceId'", "]", "!=", "''", ")", "else", ":"...
to handle deprecated mecqbank data
[ "to", "handle", "deprecated", "mecqbank", "data" ]
python
train
aws/aws-xray-sdk-python
aws_xray_sdk/core/sampling/sampling_rule.py
https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/sampling/sampling_rule.py#L30-L49
def match(self, sampling_req): """ Determines whether or not this sampling rule applies to the incoming request based on some of the request's parameters. Any ``None`` parameter provided will be considered an implicit match. """ if sampling_req is None: return...
[ "def", "match", "(", "self", ",", "sampling_req", ")", ":", "if", "sampling_req", "is", "None", ":", "return", "False", "host", "=", "sampling_req", ".", "get", "(", "'host'", ",", "None", ")", "method", "=", "sampling_req", ".", "get", "(", "'method'", ...
Determines whether or not this sampling rule applies to the incoming request based on some of the request's parameters. Any ``None`` parameter provided will be considered an implicit match.
[ "Determines", "whether", "or", "not", "this", "sampling", "rule", "applies", "to", "the", "incoming", "request", "based", "on", "some", "of", "the", "request", "s", "parameters", ".", "Any", "None", "parameter", "provided", "will", "be", "considered", "an", ...
python
train
volafiled/python-volapi
volapi/user.py
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/user.py#L18-L34
def login(self, password): """Attempts to log in as the current user with given password""" if self.logged_in: raise RuntimeError("User already logged in!") params = {"name": self.nick, "password": password} resp = self.conn.make_api_call("login", params) if "error"...
[ "def", "login", "(", "self", ",", "password", ")", ":", "if", "self", ".", "logged_in", ":", "raise", "RuntimeError", "(", "\"User already logged in!\"", ")", "params", "=", "{", "\"name\"", ":", "self", ".", "nick", ",", "\"password\"", ":", "password", "...
Attempts to log in as the current user with given password
[ "Attempts", "to", "log", "in", "as", "the", "current", "user", "with", "given", "password" ]
python
train
saltstack/salt
salt/states/user.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/user.py#L875-L919
def absent(name, purge=False, force=False): ''' Ensure that the named user is absent name The name of the user to remove purge Set purge to True to delete all of the user's files as well as the user, Default is ``False``. force If the user is logged in, the absent ...
[ "def", "absent", "(", "name", ",", "purge", "=", "False", ",", "force", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "lusr", "=", ...
Ensure that the named user is absent name The name of the user to remove purge Set purge to True to delete all of the user's files as well as the user, Default is ``False``. force If the user is logged in, the absent state will fail. Set the force option to True to...
[ "Ensure", "that", "the", "named", "user", "is", "absent" ]
python
train
juju-solutions/charms.reactive
charms/reactive/relations.py
https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L388-L401
def _find_subclass(cls, module): """ Attempt to find subclass of :class:`RelationBase` in the given module. Note: This means strictly subclasses and not :class:`RelationBase` itself. This is to prevent picking up :class:`RelationBase` being imported to be used as the base class....
[ "def", "_find_subclass", "(", "cls", ",", "module", ")", ":", "for", "attr", "in", "dir", "(", "module", ")", ":", "candidate", "=", "getattr", "(", "module", ",", "attr", ")", "if", "(", "isclass", "(", "candidate", ")", "and", "issubclass", "(", "c...
Attempt to find subclass of :class:`RelationBase` in the given module. Note: This means strictly subclasses and not :class:`RelationBase` itself. This is to prevent picking up :class:`RelationBase` being imported to be used as the base class.
[ "Attempt", "to", "find", "subclass", "of", ":", "class", ":", "RelationBase", "in", "the", "given", "module", "." ]
python
train
DistrictDataLabs/yellowbrick
yellowbrick/draw.py
https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/draw.py#L29-L90
def manual_legend(g, labels, colors, **legend_kwargs): """ Adds a manual legend for a scatter plot to the visualizer where the labels and associated colors are drawn with circle patches instead of determining them from the labels of the artist objects on the axes. This helper is used either when the...
[ "def", "manual_legend", "(", "g", ",", "labels", ",", "colors", ",", "*", "*", "legend_kwargs", ")", ":", "# Get access to the matplotlib Axes", "if", "isinstance", "(", "g", ",", "Visualizer", ")", ":", "g", "=", "g", ".", "ax", "elif", "g", "is", "None...
Adds a manual legend for a scatter plot to the visualizer where the labels and associated colors are drawn with circle patches instead of determining them from the labels of the artist objects on the axes. This helper is used either when there are a lot of duplicate labels, no labeled artists, or when t...
[ "Adds", "a", "manual", "legend", "for", "a", "scatter", "plot", "to", "the", "visualizer", "where", "the", "labels", "and", "associated", "colors", "are", "drawn", "with", "circle", "patches", "instead", "of", "determining", "them", "from", "the", "labels", ...
python
train
jic-dtool/dtoolcore
dtoolcore/storagebroker.py
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/storagebroker.py#L537-L549
def iter_item_handles(self): """Return iterator over item handles.""" path = self._data_abspath path_length = len(path) + 1 for dirpath, dirnames, filenames in os.walk(path): for fn in filenames: path = os.path.join(dirpath, fn) relative_path...
[ "def", "iter_item_handles", "(", "self", ")", ":", "path", "=", "self", ".", "_data_abspath", "path_length", "=", "len", "(", "path", ")", "+", "1", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "path", ")", ":", ...
Return iterator over item handles.
[ "Return", "iterator", "over", "item", "handles", "." ]
python
train
tjcsl/ion
intranet/apps/eighth/models.py
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/eighth/models.py#L395-L414
def get_upcoming_blocks(self, max_number=-1): """Gets the X number of upcoming blocks (that will take place in the future). If there is no block in the future, the most recent block will be returned. Returns: A QuerySet of `EighthBlock` objects """ now = datetime.datetime.now(...
[ "def", "get_upcoming_blocks", "(", "self", ",", "max_number", "=", "-", "1", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "# Show same day if it's before 17:00", "if", "now", ".", "hour", "<", "17", ":", "now", "=", "now", "."...
Gets the X number of upcoming blocks (that will take place in the future). If there is no block in the future, the most recent block will be returned. Returns: A QuerySet of `EighthBlock` objects
[ "Gets", "the", "X", "number", "of", "upcoming", "blocks", "(", "that", "will", "take", "place", "in", "the", "future", ")", ".", "If", "there", "is", "no", "block", "in", "the", "future", "the", "most", "recent", "block", "will", "be", "returned", "." ...
python
train
SUNCAT-Center/CatHub
cathub/classification.py
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/classification.py#L159-L254
def get_site_dict(self, ads_pos): """Get dictionary with high symmetry sites close to adsorbate position. Top sites: Optained from the atomic positions of the top layer of the slab. Bridge sites: The average position of atomic pairs Hollow sites: Optained as ...
[ "def", "get_site_dict", "(", "self", ",", "ads_pos", ")", ":", "# Get top layer", "C", "=", "self", ".", "B", "[", "-", "self", ".", "ntop", "-", "1", ":", "-", "1", "]", "SC", "=", "C", "*", "(", "3", ",", "3", ",", "1", ")", "D", "=", "{"...
Get dictionary with high symmetry sites close to adsorbate position. Top sites: Optained from the atomic positions of the top layer of the slab. Bridge sites: The average position of atomic pairs Hollow sites: Optained as the Voronoi vertices 4-fold sites: As...
[ "Get", "dictionary", "with", "high", "symmetry", "sites", "close", "to", "adsorbate", "position", ".", "Top", "sites", ":", "Optained", "from", "the", "atomic", "positions", "of", "the", "top", "layer", "of", "the", "slab", ".", "Bridge", "sites", ":", "Th...
python
train
googleapis/google-cloud-python
bigquery_storage/google/cloud/bigquery_storage_v1beta1/gapic/big_query_storage_client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/gapic/big_query_storage_client.py#L385-L472
def batch_create_read_session_streams( self, session, requested_streams, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates additional streams for a ReadSession. This API can be...
[ "def", "batch_create_read_session_streams", "(", "self", ",", "session", ",", "requested_streams", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", "....
Creates additional streams for a ReadSession. This API can be used to dynamically adjust the parallelism of a batch processing task upwards by adding additional workers. Example: >>> from google.cloud import bigquery_storage_v1beta1 >>> >>> client = bigquery_...
[ "Creates", "additional", "streams", "for", "a", "ReadSession", ".", "This", "API", "can", "be", "used", "to", "dynamically", "adjust", "the", "parallelism", "of", "a", "batch", "processing", "task", "upwards", "by", "adding", "additional", "workers", "." ]
python
train
CodeReclaimers/neat-python
neat/genome.py
https://github.com/CodeReclaimers/neat-python/blob/e3dbe77c0d776eae41d598e6439e6ac02ab90b18/neat/genome.py#L267-L303
def mutate(self, config): """ Mutates this genome. """ if config.single_structural_mutation: div = max(1,(config.node_add_prob + config.node_delete_prob + config.conn_add_prob + config.conn_delete_prob)) r = random() if r < (config.node_add_p...
[ "def", "mutate", "(", "self", ",", "config", ")", ":", "if", "config", ".", "single_structural_mutation", ":", "div", "=", "max", "(", "1", ",", "(", "config", ".", "node_add_prob", "+", "config", ".", "node_delete_prob", "+", "config", ".", "conn_add_prob...
Mutates this genome.
[ "Mutates", "this", "genome", "." ]
python
train
trailofbits/manticore
manticore/native/memory.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/memory.py#L616-L664
def mmapFile(self, addr, size, perms, filename, offset=0): """ Creates a new file mapping in the memory address space. :param addr: the starting address (took as hint). If C{addr} is C{0} the first big enough chunk of memory will be selected as starting address. :pa...
[ "def", "mmapFile", "(", "self", ",", "addr", ",", "size", ",", "perms", ",", "filename", ",", "offset", "=", "0", ")", ":", "# If addr is NULL, the system determines where to allocate the region.", "assert", "addr", "is", "None", "or", "isinstance", "(", "addr", ...
Creates a new file mapping in the memory address space. :param addr: the starting address (took as hint). If C{addr} is C{0} the first big enough chunk of memory will be selected as starting address. :param size: the contents of a file mapping are initialized using C{size} bytes st...
[ "Creates", "a", "new", "file", "mapping", "in", "the", "memory", "address", "space", "." ]
python
valid
Neurita/boyle
boyle/image/base.py
https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/image/base.py#L332-L353
def apply_smoothing(self, smooth_fwhm): """Set self._smooth_fwhm and then smooths the data. See boyle.nifti.smooth.smooth_imgs. Returns ------- the smoothed data deepcopied. """ if smooth_fwhm <= 0: return old_smooth_fwhm = self._smooth_fw...
[ "def", "apply_smoothing", "(", "self", ",", "smooth_fwhm", ")", ":", "if", "smooth_fwhm", "<=", "0", ":", "return", "old_smooth_fwhm", "=", "self", ".", "_smooth_fwhm", "self", ".", "_smooth_fwhm", "=", "smooth_fwhm", "try", ":", "data", "=", "self", ".", ...
Set self._smooth_fwhm and then smooths the data. See boyle.nifti.smooth.smooth_imgs. Returns ------- the smoothed data deepcopied.
[ "Set", "self", ".", "_smooth_fwhm", "and", "then", "smooths", "the", "data", ".", "See", "boyle", ".", "nifti", ".", "smooth", ".", "smooth_imgs", "." ]
python
valid
manns/pyspread
pyspread/src/gui/_toolbars.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_toolbars.py#L924-L930
def _update_bgbrush(self, bgcolor): """Updates background color""" brush_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW) brush_color.SetRGB(bgcolor) self.bgcolor_choice.SetColour(brush_color)
[ "def", "_update_bgbrush", "(", "self", ",", "bgcolor", ")", ":", "brush_color", "=", "wx", ".", "SystemSettings_GetColour", "(", "wx", ".", "SYS_COLOUR_WINDOW", ")", "brush_color", ".", "SetRGB", "(", "bgcolor", ")", "self", ".", "bgcolor_choice", ".", "SetCol...
Updates background color
[ "Updates", "background", "color" ]
python
train
3ll3d00d/vibe
backend/src/analyser/common/measurementcontroller.py
https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/common/measurementcontroller.py#L344-L358
def startMeasurement(self, measurementId, deviceId): """ Starts the measurement for the device. :param deviceId: the device that is starting. :param measurementId: the measurement that is started. :return: true if it started (i.e. device and measurement exists). """ ...
[ "def", "startMeasurement", "(", "self", ",", "measurementId", ",", "deviceId", ")", ":", "am", ",", "handler", "=", "self", ".", "getDataHandler", "(", "measurementId", ",", "deviceId", ")", "if", "am", "is", "not", "None", ":", "am", ".", "status", "=",...
Starts the measurement for the device. :param deviceId: the device that is starting. :param measurementId: the measurement that is started. :return: true if it started (i.e. device and measurement exists).
[ "Starts", "the", "measurement", "for", "the", "device", ".", ":", "param", "deviceId", ":", "the", "device", "that", "is", "starting", ".", ":", "param", "measurementId", ":", "the", "measurement", "that", "is", "started", ".", ":", "return", ":", "true", ...
python
train
IBMStreams/pypi.streamsx
streamsx/rest.py
https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest.py#L218-L225
def get_resources(self): """Retrieves a list of all known Streams high-level REST resources. Returns: :py:obj:`list` of :py:class:`~.rest_primitives.RestResource`: List of all Streams high-level REST resources. """ json_resources = self.rest_client.make_request(self.resource...
[ "def", "get_resources", "(", "self", ")", ":", "json_resources", "=", "self", ".", "rest_client", ".", "make_request", "(", "self", ".", "resource_url", ")", "[", "'resources'", "]", "return", "[", "RestResource", "(", "resource", ",", "self", ".", "rest_cli...
Retrieves a list of all known Streams high-level REST resources. Returns: :py:obj:`list` of :py:class:`~.rest_primitives.RestResource`: List of all Streams high-level REST resources.
[ "Retrieves", "a", "list", "of", "all", "known", "Streams", "high", "-", "level", "REST", "resources", "." ]
python
train
fake-name/WebRequest
WebRequest/Captcha/PunchPort.py
https://github.com/fake-name/WebRequest/blob/b6c94631ff88b5f81f26a9f99a2d5c706810b11f/WebRequest/Captcha/PunchPort.py#L9-L51
def _is_private_ip(ip): """ Taken from https://stackoverflow.com/a/39656628/268006 Check if the IP belongs to private network blocks. @param ip: IP address to verify. @return: boolean representing whether the IP belongs or not to a private network block. """ networks = [ "0.0.0.0/8", "10.0.0.0/8", "10...
[ "def", "_is_private_ip", "(", "ip", ")", ":", "networks", "=", "[", "\"0.0.0.0/8\"", ",", "\"10.0.0.0/8\"", ",", "\"100.64.0.0/10\"", ",", "\"127.0.0.0/8\"", ",", "\"169.254.0.0/16\"", ",", "\"172.16.0.0/12\"", ",", "\"192.0.0.0/24\"", ",", "\"192.0.2.0/24\"", ",", ...
Taken from https://stackoverflow.com/a/39656628/268006 Check if the IP belongs to private network blocks. @param ip: IP address to verify. @return: boolean representing whether the IP belongs or not to a private network block.
[ "Taken", "from", "https", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "39656628", "/", "268006" ]
python
train
gamechanger/dusty
dusty/commands/cp.py
https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/commands/cp.py#L49-L61
def copy_from_local(local_path, remote_name, remote_path, demote=True): """Copy a path from the local filesystem to a path inside a Dusty container. The files on the local filesystem must be accessible by the user specified in mac_username.""" if not os.path.exists(local_path): raise RuntimeErro...
[ "def", "copy_from_local", "(", "local_path", ",", "remote_name", ",", "remote_path", ",", "demote", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "local_path", ")", ":", "raise", "RuntimeError", "(", "'ERROR: Path {} does not exist...
Copy a path from the local filesystem to a path inside a Dusty container. The files on the local filesystem must be accessible by the user specified in mac_username.
[ "Copy", "a", "path", "from", "the", "local", "filesystem", "to", "a", "path", "inside", "a", "Dusty", "container", ".", "The", "files", "on", "the", "local", "filesystem", "must", "be", "accessible", "by", "the", "user", "specified", "in", "mac_username", ...
python
valid
bpannier/simpletr64
simpletr64/devicetr64.py
https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/devicetr64.py#L356-L483
def execute(self, uri, namespace, action, timeout=2, **kwargs): """Executes a given action with optional arguments. The execution of an action of an UPnP/TR64 device needs more than just the name of an action. It needs the control URI which is called to place the action and also the namespace a...
[ "def", "execute", "(", "self", ",", "uri", ",", "namespace", ",", "action", ",", "timeout", "=", "2", ",", "*", "*", "kwargs", ")", ":", "if", "not", "uri", ":", "raise", "ValueError", "(", "\"No action URI has been defined.\"", ")", "if", "not", "namesp...
Executes a given action with optional arguments. The execution of an action of an UPnP/TR64 device needs more than just the name of an action. It needs the control URI which is called to place the action and also the namespace aka service type is needed. The namespace defines the scope or servi...
[ "Executes", "a", "given", "action", "with", "optional", "arguments", "." ]
python
train
atztogo/phonopy
phonopy/file_IO.py
https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/file_IO.py#L285-L326
def write_force_constants_to_hdf5(force_constants, filename='force_constants.hdf5', p2s_map=None, physical_unit=None, compression=None): """Write force constants in hdf5 format. ...
[ "def", "write_force_constants_to_hdf5", "(", "force_constants", ",", "filename", "=", "'force_constants.hdf5'", ",", "p2s_map", "=", "None", ",", "physical_unit", "=", "None", ",", "compression", "=", "None", ")", ":", "try", ":", "import", "h5py", "except", "Im...
Write force constants in hdf5 format. Parameters ---------- force_constants: ndarray Force constants shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3) dtype=double filename: str Filename to be saved p2s_map: ndarray Primitive atom indices in supercell inde...
[ "Write", "force", "constants", "in", "hdf5", "format", "." ]
python
train
zebpalmer/WeatherAlerts
weatheralerts/feed.py
https://github.com/zebpalmer/WeatherAlerts/blob/b99513571571fa0d65b90be883bb3bc000994027/weatheralerts/feed.py#L62-L67
def _get_nws_feed(self): """get nws alert feed, and cache it""" url = '''http://alerts.weather.gov/cap/%s.php?x=0''' % (str(self._state).lower()) # pylint: disable=E1103 xml = requests.get(url).content return xml
[ "def", "_get_nws_feed", "(", "self", ")", ":", "url", "=", "'''http://alerts.weather.gov/cap/%s.php?x=0'''", "%", "(", "str", "(", "self", ".", "_state", ")", ".", "lower", "(", ")", ")", "# pylint: disable=E1103", "xml", "=", "requests", ".", "get", "(", "u...
get nws alert feed, and cache it
[ "get", "nws", "alert", "feed", "and", "cache", "it" ]
python
train
mcs07/PubChemPy
pubchempy.py
https://github.com/mcs07/PubChemPy/blob/e3c4f4a9b6120433e5cc3383464c7a79e9b2b86e/pubchempy.py#L1253-L1262
def substances_to_frame(substances, properties=None): """Construct a pandas :class:`~pandas.DataFrame` from a list of :class:`~pubchempy.Substance` objects. Optionally specify a list of the desired :class:`~pubchempy.Substance` properties. """ import pandas as pd if isinstance(substances, Substance...
[ "def", "substances_to_frame", "(", "substances", ",", "properties", "=", "None", ")", ":", "import", "pandas", "as", "pd", "if", "isinstance", "(", "substances", ",", "Substance", ")", ":", "substances", "=", "[", "substances", "]", "properties", "=", "set",...
Construct a pandas :class:`~pandas.DataFrame` from a list of :class:`~pubchempy.Substance` objects. Optionally specify a list of the desired :class:`~pubchempy.Substance` properties.
[ "Construct", "a", "pandas", ":", "class", ":", "~pandas", ".", "DataFrame", "from", "a", "list", "of", ":", "class", ":", "~pubchempy", ".", "Substance", "objects", "." ]
python
train
openstack/networking-cisco
networking_cisco/plugins/cisco/db/l3/l3_router_appliance_db.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/l3/l3_router_appliance_db.py#L1614-L1633
def _notify_cfg_agent_port_update(resource, event, trigger, **kwargs): """Called when router port/interface is enabled/disabled""" original_port = kwargs.get('original_port') updated_port = kwargs.get('port') if (updated_port is not None and original_port is not None and ( updated_port.get('admin...
[ "def", "_notify_cfg_agent_port_update", "(", "resource", ",", "event", ",", "trigger", ",", "*", "*", "kwargs", ")", ":", "original_port", "=", "kwargs", ".", "get", "(", "'original_port'", ")", "updated_port", "=", "kwargs", ".", "get", "(", "'port'", ")", ...
Called when router port/interface is enabled/disabled
[ "Called", "when", "router", "port", "/", "interface", "is", "enabled", "/", "disabled" ]
python
train
saltstack/salt
salt/cloud/clouds/digitalocean.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L155-L172
def avail_sizes(call=None): ''' Return a list of the image sizes that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) items = query(m...
[ "def", "avail_sizes", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The avail_sizes function must be called with '", "'-f or --function, or with the --list-sizes option'", ")", "items", "=", "query", "(", ...
Return a list of the image sizes that are on the provider
[ "Return", "a", "list", "of", "the", "image", "sizes", "that", "are", "on", "the", "provider" ]
python
train
BetterWorks/django-anonymizer
anonymizer/replacers.py
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L39-L43
def small_integer(anon, obj, field, val): """ Returns a random small integer (for a Django SmallIntegerField) """ return anon.faker.small_integer(field=field)
[ "def", "small_integer", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "small_integer", "(", "field", "=", "field", ")" ]
Returns a random small integer (for a Django SmallIntegerField)
[ "Returns", "a", "random", "small", "integer", "(", "for", "a", "Django", "SmallIntegerField", ")" ]
python
train
glormph/msstitch
src/app/drivers/pycolator/qvality.py
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/drivers/pycolator/qvality.py#L53-L60
def write(self): """This actually runs the qvality program from PATH.""" outfn = self.create_outfilepath(self.fn, self.outsuffix) command = ['qvality'] command.extend(self.qvalityoptions) command.extend([self.scores['target']['fn'], self.scores['decoy']['fn'], ...
[ "def", "write", "(", "self", ")", ":", "outfn", "=", "self", ".", "create_outfilepath", "(", "self", ".", "fn", ",", "self", ".", "outsuffix", ")", "command", "=", "[", "'qvality'", "]", "command", ".", "extend", "(", "self", ".", "qvalityoptions", ")"...
This actually runs the qvality program from PATH.
[ "This", "actually", "runs", "the", "qvality", "program", "from", "PATH", "." ]
python
train
PySimpleGUI/PySimpleGUI
PySimpleGUI27.py
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L7522-L7573
def PopupError(*args, **_3to2kwargs): if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location'] else: location = (None, None) if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_on_top'] else: keep_on_top = False if 'gr...
[ "def", "PopupError", "(", "*", "args", ",", "*", "*", "_3to2kwargs", ")", ":", "if", "'location'", "in", "_3to2kwargs", ":", "location", "=", "_3to2kwargs", "[", "'location'", "]", "del", "_3to2kwargs", "[", "'location'", "]", "else", ":", "location", "=",...
Popup with colored button and 'Error' as button text :param args: :param button_color: :param background_color: :param text_color: :param auto_close: :param auto_close_duration: :param non_blocking: :param icon: :param line_width: :param font: :param no_titlebar: :param g...
[ "Popup", "with", "colored", "button", "and", "Error", "as", "button", "text", ":", "param", "args", ":", ":", "param", "button_color", ":", ":", "param", "background_color", ":", ":", "param", "text_color", ":", ":", "param", "auto_close", ":", ":", "param...
python
train
google/budou
budou/chunk.py
https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/chunk.py#L261-L272
def _insert_breaklines(self): """Inserts a breakline instead of a trailing space if the chunk is in CJK. """ target_chunks = ChunkList() for chunk in self: if chunk.word[-1] == ' ' and chunk.has_cjk(): chunk.word = chunk.word[:-1] target_chunks.append(chunk) target_chunks.a...
[ "def", "_insert_breaklines", "(", "self", ")", ":", "target_chunks", "=", "ChunkList", "(", ")", "for", "chunk", "in", "self", ":", "if", "chunk", ".", "word", "[", "-", "1", "]", "==", "' '", "and", "chunk", ".", "has_cjk", "(", ")", ":", "chunk", ...
Inserts a breakline instead of a trailing space if the chunk is in CJK.
[ "Inserts", "a", "breakline", "instead", "of", "a", "trailing", "space", "if", "the", "chunk", "is", "in", "CJK", "." ]
python
train
materialsvirtuallab/monty
monty/io.py
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/io.py#L229-L250
def acquire(self): """ Acquire the lock, if possible. If the lock is in use, it check again every `delay` seconds. It does this until it either gets the lock or exceeds `timeout` number of seconds, in which case it throws an exception. """ start_time = time.time()...
[ "def", "acquire", "(", "self", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "while", "True", ":", "try", ":", "self", ".", "fd", "=", "os", ".", "open", "(", "self", ".", "lockfile", ",", "os", ".", "O_CREAT", "|", "os", ".", "O_...
Acquire the lock, if possible. If the lock is in use, it check again every `delay` seconds. It does this until it either gets the lock or exceeds `timeout` number of seconds, in which case it throws an exception.
[ "Acquire", "the", "lock", "if", "possible", ".", "If", "the", "lock", "is", "in", "use", "it", "check", "again", "every", "delay", "seconds", ".", "It", "does", "this", "until", "it", "either", "gets", "the", "lock", "or", "exceeds", "timeout", "number",...
python
train
suurjaak/InputScope
inputscope/db.py
https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/db.py#L41-L45
def select(table, cols="*", where=(), group="", order=(), limit=(), **kwargs): """Convenience wrapper for database SELECT.""" where = dict(where, **kwargs).items() sql, args = makeSQL("SELECT", table, cols, where, group, order, limit) return execute(sql, args)
[ "def", "select", "(", "table", ",", "cols", "=", "\"*\"", ",", "where", "=", "(", ")", ",", "group", "=", "\"\"", ",", "order", "=", "(", ")", ",", "limit", "=", "(", ")", ",", "*", "*", "kwargs", ")", ":", "where", "=", "dict", "(", "where",...
Convenience wrapper for database SELECT.
[ "Convenience", "wrapper", "for", "database", "SELECT", "." ]
python
train
freakboy3742/pyxero
xero/filesmanager.py
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/filesmanager.py#L118-L121
def _get_files(self, folderId): """Retrieve the list of files contained in a folder""" uri = '/'.join([self.base_url, self.name, folderId, 'Files']) return uri, {}, 'get', None, None, False, None
[ "def", "_get_files", "(", "self", ",", "folderId", ")", ":", "uri", "=", "'/'", ".", "join", "(", "[", "self", ".", "base_url", ",", "self", ".", "name", ",", "folderId", ",", "'Files'", "]", ")", "return", "uri", ",", "{", "}", ",", "'get'", ","...
Retrieve the list of files contained in a folder
[ "Retrieve", "the", "list", "of", "files", "contained", "in", "a", "folder" ]
python
train
spyder-ide/spyder
spyder/plugins/editor/extensions/closequotes.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/closequotes.py#L61-L113
def _autoinsert_quotes(self, key): """Control how to automatically insert quotes in various situations.""" char = {Qt.Key_QuoteDbl: '"', Qt.Key_Apostrophe: '\''}[key] line_text = self.editor.get_text('sol', 'eol') line_to_cursor = self.editor.get_text('sol', 'cursor') cursor = s...
[ "def", "_autoinsert_quotes", "(", "self", ",", "key", ")", ":", "char", "=", "{", "Qt", ".", "Key_QuoteDbl", ":", "'\"'", ",", "Qt", ".", "Key_Apostrophe", ":", "'\\''", "}", "[", "key", "]", "line_text", "=", "self", ".", "editor", ".", "get_text", ...
Control how to automatically insert quotes in various situations.
[ "Control", "how", "to", "automatically", "insert", "quotes", "in", "various", "situations", "." ]
python
train
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/jinja2/environment.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/environment.py#L601-L693
def compile_templates(self, target, extensions=None, filter_func=None, zip='deflated', log_function=None, ignore_errors=True, py_compile=False): """Finds all the templates the loader can find, compiles them and stores them in `target`. If `zip` is `No...
[ "def", "compile_templates", "(", "self", ",", "target", ",", "extensions", "=", "None", ",", "filter_func", "=", "None", ",", "zip", "=", "'deflated'", ",", "log_function", "=", "None", ",", "ignore_errors", "=", "True", ",", "py_compile", "=", "False", ")...
Finds all the templates the loader can find, compiles them and stores them in `target`. If `zip` is `None`, instead of in a zipfile, the templates will be will be stored in a directory. By default a deflate zip algorithm is used, to switch to the stored algorithm, `zip` can be set to ``...
[ "Finds", "all", "the", "templates", "the", "loader", "can", "find", "compiles", "them", "and", "stores", "them", "in", "target", ".", "If", "zip", "is", "None", "instead", "of", "in", "a", "zipfile", "the", "templates", "will", "be", "will", "be", "store...
python
test
emory-libraries/eulxml
eulxml/xpath/parserules.py
https://github.com/emory-libraries/eulxml/blob/17d71c7d98c0cebda9932b7f13e72093805e1fe2/eulxml/xpath/parserules.py#L270-L277
def p_filter_expr_predicate(p): """ FilterExpr : FilterExpr Predicate """ if not hasattr(p[1], 'append_predicate'): p[1] = ast.PredicatedExpression(p[1]) p[1].append_predicate(p[2]) p[0] = p[1]
[ "def", "p_filter_expr_predicate", "(", "p", ")", ":", "if", "not", "hasattr", "(", "p", "[", "1", "]", ",", "'append_predicate'", ")", ":", "p", "[", "1", "]", "=", "ast", ".", "PredicatedExpression", "(", "p", "[", "1", "]", ")", "p", "[", "1", ...
FilterExpr : FilterExpr Predicate
[ "FilterExpr", ":", "FilterExpr", "Predicate" ]
python
train
loli/medpy
doc/numpydoc/numpydoc/compiler_unparse.py
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/compiler_unparse.py#L60-L65
def _fill(self, text = ""): "Indent a piece of text, according to the current indentation level" if self._do_indent: self._write("\n"+" "*self._indent + text) else: self._write(text)
[ "def", "_fill", "(", "self", ",", "text", "=", "\"\"", ")", ":", "if", "self", ".", "_do_indent", ":", "self", ".", "_write", "(", "\"\\n\"", "+", "\" \"", "*", "self", ".", "_indent", "+", "text", ")", "else", ":", "self", ".", "_write", "(", ...
Indent a piece of text, according to the current indentation level
[ "Indent", "a", "piece", "of", "text", "according", "to", "the", "current", "indentation", "level" ]
python
train
amol-/dukpy
dukpy/module_loader.py
https://github.com/amol-/dukpy/blob/69f56f375a217c9f907499c28dbc964af76feae6/dukpy/module_loader.py#L27-L37
def lookup(self, module_name): """Searches for a file providing given module. Returns the normalized module id and path of the file. """ for search_path in self._paths: module_path = os.path.join(search_path, module_name) new_module_name, module_file = self._look...
[ "def", "lookup", "(", "self", ",", "module_name", ")", ":", "for", "search_path", "in", "self", ".", "_paths", ":", "module_path", "=", "os", ".", "path", ".", "join", "(", "search_path", ",", "module_name", ")", "new_module_name", ",", "module_file", "=",...
Searches for a file providing given module. Returns the normalized module id and path of the file.
[ "Searches", "for", "a", "file", "providing", "given", "module", "." ]
python
train
angr/angr
angr/analyses/cfg/cfg_utils.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_utils.py#L182-L212
def _append_scc(graph, ordered_nodes, scc): """ Append all nodes from a strongly connected component to a list of ordered nodes and ensure the topological order. :param networkx.DiGraph graph: The graph where all nodes belong to. :param list ordered_nodes: Ordered nodes. ...
[ "def", "_append_scc", "(", "graph", ",", "ordered_nodes", ",", "scc", ")", ":", "# find the first node in the strongly connected component that is the successor to any node in ordered_nodes", "loop_head", "=", "None", "for", "parent_node", "in", "reversed", "(", "ordered_nodes"...
Append all nodes from a strongly connected component to a list of ordered nodes and ensure the topological order. :param networkx.DiGraph graph: The graph where all nodes belong to. :param list ordered_nodes: Ordered nodes. :param iterable scc: A set of nodes that forms a ...
[ "Append", "all", "nodes", "from", "a", "strongly", "connected", "component", "to", "a", "list", "of", "ordered", "nodes", "and", "ensure", "the", "topological", "order", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/parallel/client/client.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/client/client.py#L680-L691
def _unregister_engine(self, msg): """Unregister an engine that has died.""" content = msg['content'] eid = int(content['id']) if eid in self._ids: self._ids.remove(eid) uuid = self._engines.pop(eid) self._handle_stranded_msgs(eid, uuid) if s...
[ "def", "_unregister_engine", "(", "self", ",", "msg", ")", ":", "content", "=", "msg", "[", "'content'", "]", "eid", "=", "int", "(", "content", "[", "'id'", "]", ")", "if", "eid", "in", "self", ".", "_ids", ":", "self", ".", "_ids", ".", "remove",...
Unregister an engine that has died.
[ "Unregister", "an", "engine", "that", "has", "died", "." ]
python
test
HDI-Project/RDT
examples/airbnb.py
https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/examples/airbnb.py#L28-L44
def run_airbnb_demo(data_dir): """HyperTransfomer will transform back and forth data airbnb data.""" # Setup meta_file = os.path.join(data_dir, 'Airbnb_demo_meta.json') transformer_list = ['NumberTransformer', 'DTTransformer', 'CatTransformer'] ht = HyperTransformer(meta_file) # Run transf...
[ "def", "run_airbnb_demo", "(", "data_dir", ")", ":", "# Setup", "meta_file", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'Airbnb_demo_meta.json'", ")", "transformer_list", "=", "[", "'NumberTransformer'", ",", "'DTTransformer'", ",", "'CatTransform...
HyperTransfomer will transform back and forth data airbnb data.
[ "HyperTransfomer", "will", "transform", "back", "and", "forth", "data", "airbnb", "data", "." ]
python
train
awslabs/serverless-application-model
samtranslator/model/sam_resources.py
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/sam_resources.py#L456-L493
def to_cloudformation(self, **kwargs): """Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanill...
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "resources", "=", "[", "]", "api_generator", "=", "ApiGenerator", "(", "self", ".", "logical_id", ",", "self", ".", "CacheClusterEnabled", ",", "self", ".", "CacheClusterSize", ",", ...
Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds. :param dict kwargs: already-converted resources that may need to be modified when converting this \ macro to pure CloudFormation :returns: a list of vanilla CloudFormation Resources, to which this Function...
[ "Returns", "the", "API", "Gateway", "RestApi", "Deployment", "and", "Stage", "to", "which", "this", "SAM", "Api", "corresponds", "." ]
python
train
ml4ai/delphi
delphi/inspection.py
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/inspection.py#L28-L44
def _get_edge_sentences( G: AnalysisGraph, source: str, target: str ) -> List[str]: """ Return the sentences that led to the construction of a specified edge. Args: G source: The source of the edge. target: The target of the edge. """ return chain.from_iterable( [ ...
[ "def", "_get_edge_sentences", "(", "G", ":", "AnalysisGraph", ",", "source", ":", "str", ",", "target", ":", "str", ")", "->", "List", "[", "str", "]", ":", "return", "chain", ".", "from_iterable", "(", "[", "[", "repr", "(", "e", ".", "text", ")", ...
Return the sentences that led to the construction of a specified edge. Args: G source: The source of the edge. target: The target of the edge.
[ "Return", "the", "sentences", "that", "led", "to", "the", "construction", "of", "a", "specified", "edge", "." ]
python
train
aioworkers/aioworkers
aioworkers/core/formatter.py
https://github.com/aioworkers/aioworkers/blob/94caa5584a75bae1cee6c8c7a24667bff9cefa90/aioworkers/core/formatter.py#L183-L195
def add_converter(cls, klass, conv, score=0): """ Add converter :param klass: class or str :param conv: callable :param score: :return: """ if isinstance(klass, str): klass = import_name(klass) item = klass, conv, score cls.converters.a...
[ "def", "add_converter", "(", "cls", ",", "klass", ",", "conv", ",", "score", "=", "0", ")", ":", "if", "isinstance", "(", "klass", ",", "str", ")", ":", "klass", "=", "import_name", "(", "klass", ")", "item", "=", "klass", ",", "conv", ",", "score"...
Add converter :param klass: class or str :param conv: callable :param score: :return:
[ "Add", "converter", ":", "param", "klass", ":", "class", "or", "str", ":", "param", "conv", ":", "callable", ":", "param", "score", ":", ":", "return", ":" ]
python
train
bunq/sdk_python
bunq/sdk/model/core.py
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/core.py#L72-L83
def _unwrap_response_single(cls, obj, wrapper=None): """ :type obj: dict :type wrapper: str|None :rtype: dict """ if wrapper is not None: return obj[cls._FIELD_RESPONSE][cls._INDEX_FIRST][wrapper] return obj[cls._FIELD_RESPONSE][cls._INDEX_FIRST]
[ "def", "_unwrap_response_single", "(", "cls", ",", "obj", ",", "wrapper", "=", "None", ")", ":", "if", "wrapper", "is", "not", "None", ":", "return", "obj", "[", "cls", ".", "_FIELD_RESPONSE", "]", "[", "cls", ".", "_INDEX_FIRST", "]", "[", "wrapper", ...
:type obj: dict :type wrapper: str|None :rtype: dict
[ ":", "type", "obj", ":", "dict", ":", "type", "wrapper", ":", "str|None" ]
python
train
loverajoel/sqlalchemy-elasticquery
sqlalchemy_elasticquery/elastic_query.py
https://github.com/loverajoel/sqlalchemy-elasticquery/blob/4c99b81f59e7bb20eaeedb3adbf5126e62bbc25c/sqlalchemy_elasticquery/elastic_query.py#L40-L49
def elastic_query(model, query, session=None, enabled_fields=None): """ Public method for init the class ElasticQuery :model: SQLAlchemy model :query: valid string like a ElasticSearch :session: SQLAlchemy session *optional :enabled_fields: Fields allowed for make a query *optional ...
[ "def", "elastic_query", "(", "model", ",", "query", ",", "session", "=", "None", ",", "enabled_fields", "=", "None", ")", ":", "# TODO: make session to optional", "instance", "=", "ElasticQuery", "(", "model", ",", "query", ",", "session", ",", "enabled_fields",...
Public method for init the class ElasticQuery :model: SQLAlchemy model :query: valid string like a ElasticSearch :session: SQLAlchemy session *optional :enabled_fields: Fields allowed for make a query *optional
[ "Public", "method", "for", "init", "the", "class", "ElasticQuery", ":", "model", ":", "SQLAlchemy", "model", ":", "query", ":", "valid", "string", "like", "a", "ElasticSearch", ":", "session", ":", "SQLAlchemy", "session", "*", "optional", ":", "enabled_fields...
python
valid
UCL-INGI/INGInious
inginious/frontend/static_middleware.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/static_middleware.py#L66-L71
def normpath(self, path): """ Normalize the path """ path2 = posixpath.normpath(urllib.parse.unquote(path)) if path.endswith("/"): path2 += "/" return path2
[ "def", "normpath", "(", "self", ",", "path", ")", ":", "path2", "=", "posixpath", ".", "normpath", "(", "urllib", ".", "parse", ".", "unquote", "(", "path", ")", ")", "if", "path", ".", "endswith", "(", "\"/\"", ")", ":", "path2", "+=", "\"/\"", "r...
Normalize the path
[ "Normalize", "the", "path" ]
python
train
Capitains/MyCapytain
MyCapytain/resolvers/cts/local.py
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/cts/local.py#L399-L424
def pagination(page, limit, length): """ Help for pagination :param page: Provided Page :param limit: Number of item to show :param length: Length of the list to paginate :return: (Start Index, End Index, Page Number, Item Count) """ realpage = page page =...
[ "def", "pagination", "(", "page", ",", "limit", ",", "length", ")", ":", "realpage", "=", "page", "page", "=", "page", "or", "CtsCapitainsLocalResolver", ".", "DEFAULT_PAGE", "limit", "=", "limit", "or", "CtsCapitainsLocalResolver", ".", "PER_PAGE", "[", "1", ...
Help for pagination :param page: Provided Page :param limit: Number of item to show :param length: Length of the list to paginate :return: (Start Index, End Index, Page Number, Item Count)
[ "Help", "for", "pagination", ":", "param", "page", ":", "Provided", "Page", ":", "param", "limit", ":", "Number", "of", "item", "to", "show", ":", "param", "length", ":", "Length", "of", "the", "list", "to", "paginate", ":", "return", ":", "(", "Start"...
python
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L361-L372
def constants(self): """Constants declaration lines.""" lines = Lines() for (name, member) in vars(self.cythonizer).items(): if (name.isupper() and (not inspect.isclass(member)) and (type(member) in TYPE2STR)): ndim = numpy.arra...
[ "def", "constants", "(", "self", ")", ":", "lines", "=", "Lines", "(", ")", "for", "(", "name", ",", "member", ")", "in", "vars", "(", "self", ".", "cythonizer", ")", ".", "items", "(", ")", ":", "if", "(", "name", ".", "isupper", "(", ")", "an...
Constants declaration lines.
[ "Constants", "declaration", "lines", "." ]
python
train
jobovy/galpy
galpy/potential/FerrersPotential.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/FerrersPotential.py#L131-L148
def _Rforce(self,R,z,phi=0.,t=0.): """ NAME: _Rforce PURPOSE:T evaluate the radial force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
[ "def", "_Rforce", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "if", "not", "self", ".", "isNonAxi", ":", "phi", "=", "0.", "self", ".", "_compute_xyzforces", "(", "R", ",", "z", ",", "phi", ",", "t",...
NAME: _Rforce PURPOSE:T evaluate the radial force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the radial force
[ "NAME", ":", "_Rforce", "PURPOSE", ":", "T", "evaluate", "the", "radial", "force", "for", "this", "potential", "INPUT", ":", "R", "-", "Galactocentric", "cylindrical", "radius", "z", "-", "vertical", "height", "phi", "-", "azimuth", "t", "-", "time", "OUTP...
python
train
Unity-Technologies/ml-agents
ml-agents/mlagents/trainers/ppo/models.py
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/ppo/models.py#L116-L134
def create_inverse_model(self, encoded_state, encoded_next_state): """ Creates inverse model TensorFlow ops for Curiosity module. Predicts action taken given current and future encoded states. :param encoded_state: Tensor corresponding to encoded current state. :param encoded_nex...
[ "def", "create_inverse_model", "(", "self", ",", "encoded_state", ",", "encoded_next_state", ")", ":", "combined_input", "=", "tf", ".", "concat", "(", "[", "encoded_state", ",", "encoded_next_state", "]", ",", "axis", "=", "1", ")", "hidden", "=", "tf", "."...
Creates inverse model TensorFlow ops for Curiosity module. Predicts action taken given current and future encoded states. :param encoded_state: Tensor corresponding to encoded current state. :param encoded_next_state: Tensor corresponding to encoded next state.
[ "Creates", "inverse", "model", "TensorFlow", "ops", "for", "Curiosity", "module", ".", "Predicts", "action", "taken", "given", "current", "and", "future", "encoded", "states", ".", ":", "param", "encoded_state", ":", "Tensor", "corresponding", "to", "encoded", "...
python
train
deepmind/pysc2
pysc2/lib/features.py
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L222-L226
def unpack(self, obs): """Return a correctly shaped numpy array for this feature.""" planes = getattr(obs.feature_layer_data, self.layer_set) plane = getattr(planes, self.name) return self.unpack_layer(plane)
[ "def", "unpack", "(", "self", ",", "obs", ")", ":", "planes", "=", "getattr", "(", "obs", ".", "feature_layer_data", ",", "self", ".", "layer_set", ")", "plane", "=", "getattr", "(", "planes", ",", "self", ".", "name", ")", "return", "self", ".", "un...
Return a correctly shaped numpy array for this feature.
[ "Return", "a", "correctly", "shaped", "numpy", "array", "for", "this", "feature", "." ]
python
train
modin-project/modin
modin/pandas/base.py
https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/base.py#L1138-L1180
def filter(self, items=None, like=None, regex=None, axis=None): """Subset rows or columns based on their labels Args: items (list): list of labels to subset like (string): retain labels where `arg in label == True` regex (string): retain labels matching regex i...
[ "def", "filter", "(", "self", ",", "items", "=", "None", ",", "like", "=", "None", ",", "regex", "=", "None", ",", "axis", "=", "None", ")", ":", "nkw", "=", "count_not_none", "(", "items", ",", "like", ",", "regex", ")", "if", "nkw", ">", "1", ...
Subset rows or columns based on their labels Args: items (list): list of labels to subset like (string): retain labels where `arg in label == True` regex (string): retain labels matching regex input axis: axis to filter on Returns: A...
[ "Subset", "rows", "or", "columns", "based", "on", "their", "labels", "Args", ":", "items", "(", "list", ")", ":", "list", "of", "labels", "to", "subset", "like", "(", "string", ")", ":", "retain", "labels", "where", "arg", "in", "label", "==", "True", ...
python
train
phaethon/kamene
kamene/contrib/gsm_um.py
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L1184-L1191
def systemInformationType16(): """SYSTEM INFORMATION TYPE 16 Section 9.1.43d""" a = L2PseudoLength(l2pLength=0x01) b = TpPd(pd=0x6) c = MessageType(mesType=0x3d) # 00111101 d = Si16RestOctets() packet = a / b / c / d return packet
[ "def", "systemInformationType16", "(", ")", ":", "a", "=", "L2PseudoLength", "(", "l2pLength", "=", "0x01", ")", "b", "=", "TpPd", "(", "pd", "=", "0x6", ")", "c", "=", "MessageType", "(", "mesType", "=", "0x3d", ")", "# 00111101", "d", "=", "Si16RestO...
SYSTEM INFORMATION TYPE 16 Section 9.1.43d
[ "SYSTEM", "INFORMATION", "TYPE", "16", "Section", "9", ".", "1", ".", "43d" ]
python
train
astroML/gatspy
gatspy/periodic/modeler.py
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L27-L51
def fit(self, t, y, dy=None): """Fit the multiterm Periodogram model to the data. Parameters ---------- t : array_like, one-dimensional sequence of observation times y : array_like, one-dimensional sequence of observed values dy : float or array_l...
[ "def", "fit", "(", "self", ",", "t", ",", "y", ",", "dy", "=", "None", ")", ":", "# For linear models, dy=1 is equivalent to no errors", "if", "dy", "is", "None", ":", "dy", "=", "1", "self", ".", "t", ",", "self", ".", "y", ",", "self", ".", "dy", ...
Fit the multiterm Periodogram model to the data. Parameters ---------- t : array_like, one-dimensional sequence of observation times y : array_like, one-dimensional sequence of observed values dy : float or array_like (optional) errors on obse...
[ "Fit", "the", "multiterm", "Periodogram", "model", "to", "the", "data", "." ]
python
train
Jammy2211/PyAutoLens
autolens/model/profiles/mass_profiles.py
https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/mass_profiles.py#L1424-L1434
def potential_from_grid(self, grid): """ Calculate the potential at a given set of arc-second gridded coordinates. Parameters ---------- grid : grids.RegularGrid The grid of (y,x) arc-second coordinates the deflection angles are computed on. """ eta =...
[ "def", "potential_from_grid", "(", "self", ",", "grid", ")", ":", "eta", "=", "(", "1.0", "/", "self", ".", "scale_radius", ")", "*", "self", ".", "grid_to_grid_radii", "(", "grid", ")", "+", "0j", "return", "np", ".", "real", "(", "2.0", "*", "self"...
Calculate the potential at a given set of arc-second gridded coordinates. Parameters ---------- grid : grids.RegularGrid The grid of (y,x) arc-second coordinates the deflection angles are computed on.
[ "Calculate", "the", "potential", "at", "a", "given", "set", "of", "arc", "-", "second", "gridded", "coordinates", "." ]
python
valid
junaruga/rpm-py-installer
install.py
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L161-L184
def download_and_install(self): """Download and install RPM Python binding.""" if self.is_installed_from_bin: try: self.installer.install_from_rpm_py_package() return except RpmPyPackageNotFoundError as e: Log.warn('RPM Py Package n...
[ "def", "download_and_install", "(", "self", ")", ":", "if", "self", ".", "is_installed_from_bin", ":", "try", ":", "self", ".", "installer", ".", "install_from_rpm_py_package", "(", ")", "return", "except", "RpmPyPackageNotFoundError", "as", "e", ":", "Log", "."...
Download and install RPM Python binding.
[ "Download", "and", "install", "RPM", "Python", "binding", "." ]
python
train
rjdkmr/do_x3dna
dnaMD/dnaMD/dnaEY.py
https://github.com/rjdkmr/do_x3dna/blob/fe910335eefcada76737f9e7cd6f25036cd32ab6/dnaMD/dnaMD/dnaEY.py#L372-L455
def getStretchTwistBendModulus(self, bp, frames=None, paxis='Z', masked=True, matrix=False): r"""Calculate Bending-Stretching-Twisting matrix It calculate elastic matrix and modulus matrix. .. math:: \text{modulus matrix} = 4.1419464 \times \begin{bmatrix} K_{Bx} ...
[ "def", "getStretchTwistBendModulus", "(", "self", ",", "bp", ",", "frames", "=", "None", ",", "paxis", "=", "'Z'", ",", "masked", "=", "True", ",", "matrix", "=", "False", ")", ":", "if", "self", ".", "esType", "==", "'ST'", ":", "raise", "KeyError", ...
r"""Calculate Bending-Stretching-Twisting matrix It calculate elastic matrix and modulus matrix. .. math:: \text{modulus matrix} = 4.1419464 \times \begin{bmatrix} K_{Bx} & K_{Bx,By} & K_{Bx,S} & K_{Bx,T} \\ K_{Bx,By} & K_{By} & K_{By,S} & K_{By,T} \\ ...
[ "r", "Calculate", "Bending", "-", "Stretching", "-", "Twisting", "matrix" ]
python
train
apache/incubator-heron
heron/tools/tracker/src/python/topology.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/topology.py#L231-L249
def get_status(self): """ Get the current state of this topology. The state values are from the topology.proto RUNNING = 1, PAUSED = 2, KILLED = 3 if the state is None "Unknown" is returned. """ status = None if self.physical_plan and self.physical_plan.topology: status = self.phys...
[ "def", "get_status", "(", "self", ")", ":", "status", "=", "None", "if", "self", ".", "physical_plan", "and", "self", ".", "physical_plan", ".", "topology", ":", "status", "=", "self", ".", "physical_plan", ".", "topology", ".", "state", "if", "status", ...
Get the current state of this topology. The state values are from the topology.proto RUNNING = 1, PAUSED = 2, KILLED = 3 if the state is None "Unknown" is returned.
[ "Get", "the", "current", "state", "of", "this", "topology", ".", "The", "state", "values", "are", "from", "the", "topology", ".", "proto", "RUNNING", "=", "1", "PAUSED", "=", "2", "KILLED", "=", "3", "if", "the", "state", "is", "None", "Unknown", "is",...
python
valid
has2k1/plotnine
plotnine/stats/stat_summary.py
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/stat_summary.py#L75-L83
def mean_se(series, mult=1): """ Calculate mean and standard errors on either side """ m = np.mean(series) se = mult * np.sqrt(np.var(series) / len(series)) return pd.DataFrame({'y': [m], 'ymin': m-se, 'ymax': m+se})
[ "def", "mean_se", "(", "series", ",", "mult", "=", "1", ")", ":", "m", "=", "np", ".", "mean", "(", "series", ")", "se", "=", "mult", "*", "np", ".", "sqrt", "(", "np", ".", "var", "(", "series", ")", "/", "len", "(", "series", ")", ")", "r...
Calculate mean and standard errors on either side
[ "Calculate", "mean", "and", "standard", "errors", "on", "either", "side" ]
python
train
mabuchilab/QNET
src/qnet/algebra/core/abstract_quantum_algebra.py
https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/core/abstract_quantum_algebra.py#L159-L201
def series_expand( self, param: Symbol, about, order: int) -> tuple: r"""Expand the expression as a truncated power series in a scalar parameter. When expanding an expr for a parameter $x$ about the point $x_0$ up to order $N$, the resulting coefficients $(c_1, \dots, c_N)$ ...
[ "def", "series_expand", "(", "self", ",", "param", ":", "Symbol", ",", "about", ",", "order", ":", "int", ")", "->", "tuple", ":", "expansion", "=", "self", ".", "_series_expand", "(", "param", ",", "about", ",", "order", ")", "# _series_expand is generall...
r"""Expand the expression as a truncated power series in a scalar parameter. When expanding an expr for a parameter $x$ about the point $x_0$ up to order $N$, the resulting coefficients $(c_1, \dots, c_N)$ fulfill .. math:: \text{expr} = \sum_{n=0}^{N} c_n (x - x_0)^n + O(...
[ "r", "Expand", "the", "expression", "as", "a", "truncated", "power", "series", "in", "a", "scalar", "parameter", "." ]
python
train
SBRG/ssbio
ssbio/pipeline/gempro.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/gempro.py#L1283-L1285
def missing_representative_structure(self): """list: List of genes with no mapping to a representative structure.""" return [x.id for x in self.genes if not self.genes_with_a_representative_structure.has_id(x.id)]
[ "def", "missing_representative_structure", "(", "self", ")", ":", "return", "[", "x", ".", "id", "for", "x", "in", "self", ".", "genes", "if", "not", "self", ".", "genes_with_a_representative_structure", ".", "has_id", "(", "x", ".", "id", ")", "]" ]
list: List of genes with no mapping to a representative structure.
[ "list", ":", "List", "of", "genes", "with", "no", "mapping", "to", "a", "representative", "structure", "." ]
python
train
cltrudeau/wrench
wrench/logtools/srothandler.py
https://github.com/cltrudeau/wrench/blob/bc231dd085050a63a87ff3eb8f0a863928f65a41/wrench/logtools/srothandler.py#L166-L177
def close(self): """ Close log stream and stream_lock. """ try: self._close() if hasattr(self.stream_lock, 'closed') and \ not self.stream_lock.closed: self.stream_lock.close() finally: self.stream_lock = None ...
[ "def", "close", "(", "self", ")", ":", "try", ":", "self", ".", "_close", "(", ")", "if", "hasattr", "(", "self", ".", "stream_lock", ",", "'closed'", ")", "and", "not", "self", ".", "stream_lock", ".", "closed", ":", "self", ".", "stream_lock", ".",...
Close log stream and stream_lock.
[ "Close", "log", "stream", "and", "stream_lock", "." ]
python
train
diux-dev/ncluster
ncluster/util.py
https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L130-L147
def is_bash_builtin(cmd): """Return true if command is invoking bash built-in """ # from compgen -b bash_builtins = ['alias', 'bg', 'bind', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'cd', 'command', 'compgen', 'complete', 'compopt', 'continue', 'declare', 'dirs',...
[ "def", "is_bash_builtin", "(", "cmd", ")", ":", "# from compgen -b", "bash_builtins", "=", "[", "'alias'", ",", "'bg'", ",", "'bind'", ",", "'alias'", ",", "'bg'", ",", "'bind'", ",", "'break'", ",", "'builtin'", ",", "'caller'", ",", "'cd'", ",", "'comman...
Return true if command is invoking bash built-in
[ "Return", "true", "if", "command", "is", "invoking", "bash", "built", "-", "in" ]
python
train
davidmiller/urlhelp
urlhelp/__init__.py
https://github.com/davidmiller/urlhelp/blob/9cc417a5dc5bd4a7e17ed78a1f1394a6ece9faa5/urlhelp/__init__.py#L34-L52
def find_links(url): """ Find the href destinations of all links at URL Arguments: - `url`: Return: list[str] Exceptions: None """ url = protocolise(url) content = requests.get(url).content flike = StringIO(content) root = html.parse(flike).getroot() atags = root.cssse...
[ "def", "find_links", "(", "url", ")", ":", "url", "=", "protocolise", "(", "url", ")", "content", "=", "requests", ".", "get", "(", "url", ")", ".", "content", "flike", "=", "StringIO", "(", "content", ")", "root", "=", "html", ".", "parse", "(", "...
Find the href destinations of all links at URL Arguments: - `url`: Return: list[str] Exceptions: None
[ "Find", "the", "href", "destinations", "of", "all", "links", "at", "URL" ]
python
test
NoMore201/googleplay-api
gpapi/googleplay.py
https://github.com/NoMore201/googleplay-api/blob/e5e60b83563055bd7e13778ad13a260d2547cbf2/gpapi/googleplay.py#L578-L619
def download(self, packageName, versionCode=None, offerType=1, expansion_files=False): """Download an app and return its raw data (APK file). Free apps need to be "purchased" first, in order to retrieve the download cookie. If you want to download an already purchased app, use *delivery* method....
[ "def", "download", "(", "self", ",", "packageName", ",", "versionCode", "=", "None", ",", "offerType", "=", "1", ",", "expansion_files", "=", "False", ")", ":", "if", "self", ".", "authSubToken", "is", "None", ":", "raise", "LoginError", "(", "\"You need t...
Download an app and return its raw data (APK file). Free apps need to be "purchased" first, in order to retrieve the download cookie. If you want to download an already purchased app, use *delivery* method. Args: packageName (str): app unique ID (usually starting with 'com.') ...
[ "Download", "an", "app", "and", "return", "its", "raw", "data", "(", "APK", "file", ")", ".", "Free", "apps", "need", "to", "be", "purchased", "first", "in", "order", "to", "retrieve", "the", "download", "cookie", ".", "If", "you", "want", "to", "downl...
python
valid
optimizely/python-sdk
optimizely/optimizely.py
https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/optimizely.py#L507-L524
def get_feature_variable_boolean(self, feature_key, variable_key, user_id, attributes=None): """ Returns value for a certain boolean variable attached to a feature flag. Args: feature_key: Key of the feature whose variable's value is being accessed. variable_key: Key of the variable whose value is ...
[ "def", "get_feature_variable_boolean", "(", "self", ",", "feature_key", ",", "variable_key", ",", "user_id", ",", "attributes", "=", "None", ")", ":", "variable_type", "=", "entities", ".", "Variable", ".", "Type", ".", "BOOLEAN", "return", "self", ".", "_get_...
Returns value for a certain boolean variable attached to a feature flag. Args: feature_key: Key of the feature whose variable's value is being accessed. variable_key: Key of the variable whose value is to be accessed. user_id: ID for user. attributes: Dict representing user attributes. ...
[ "Returns", "value", "for", "a", "certain", "boolean", "variable", "attached", "to", "a", "feature", "flag", "." ]
python
train
joke2k/faker
faker/providers/ssn/en_US/__init__.py
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/ssn/en_US/__init__.py#L13-L33
def itin(self): """Generate a random United States Individual Taxpayer Identification Number (ITIN). An United States Individual Taxpayer Identification Number (ITIN) is a tax processing number issued by the Internal Revenue Service. It is a nine-digit number that always begins ...
[ "def", "itin", "(", "self", ")", ":", "area", "=", "self", ".", "random_int", "(", "min", "=", "900", ",", "max", "=", "999", ")", "serial", "=", "self", ".", "random_int", "(", "min", "=", "0", ",", "max", "=", "9999", ")", "# The group number mus...
Generate a random United States Individual Taxpayer Identification Number (ITIN). An United States Individual Taxpayer Identification Number (ITIN) is a tax processing number issued by the Internal Revenue Service. It is a nine-digit number that always begins with the number 9 and has a...
[ "Generate", "a", "random", "United", "States", "Individual", "Taxpayer", "Identification", "Number", "(", "ITIN", ")", "." ]
python
train
ojii/django-multilingual-ng
multilingual/templatetags/multilingual_tags.py
https://github.com/ojii/django-multilingual-ng/blob/0d320a0732ec59949380d4b5f21e153174d3ecf7/multilingual/templatetags/multilingual_tags.py#L73-L81
def reorder_translation_formset_by_language_code(inline_admin_form): """ Shuffle the forms in the formset of multilingual model in the order of their language_ids. """ lang_to_form = dict([(form.form.initial['language_id'], form) for form in inline_admin_form]) return [l...
[ "def", "reorder_translation_formset_by_language_code", "(", "inline_admin_form", ")", ":", "lang_to_form", "=", "dict", "(", "[", "(", "form", ".", "form", ".", "initial", "[", "'language_id'", "]", ",", "form", ")", "for", "form", "in", "inline_admin_form", "]"...
Shuffle the forms in the formset of multilingual model in the order of their language_ids.
[ "Shuffle", "the", "forms", "in", "the", "formset", "of", "multilingual", "model", "in", "the", "order", "of", "their", "language_ids", "." ]
python
train
nhanb/fundoshi
fundoshi/sites/kissmanga/decoder.py
https://github.com/nhanb/fundoshi/blob/d92aab2507bc9e8b568d09d92a0f1e7b27e050a0/fundoshi/sites/kissmanga/decoder.py#L37-L54
def get_key(soup): ''' On each chapter page, a <script> tag is inserted that overrides the encryption key, so we'll need to find that. Only fall back to default key if such a tag is not found. ''' crypto_tag = soup.find(_crypto_tag) if crypto_tag is None: return _default_key pa...
[ "def", "get_key", "(", "soup", ")", ":", "crypto_tag", "=", "soup", ".", "find", "(", "_crypto_tag", ")", "if", "crypto_tag", "is", "None", ":", "return", "_default_key", "pat", "=", "re", ".", "compile", "(", "'\\[\"(.+)\"\\]'", ")", "keys", "=", "pat",...
On each chapter page, a <script> tag is inserted that overrides the encryption key, so we'll need to find that. Only fall back to default key if such a tag is not found.
[ "On", "each", "chapter", "page", "a", "<script", ">", "tag", "is", "inserted", "that", "overrides", "the", "encryption", "key", "so", "we", "ll", "need", "to", "find", "that", ".", "Only", "fall", "back", "to", "default", "key", "if", "such", "a", "tag...
python
train
dmlc/gluon-nlp
scripts/parsing/common/utils.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L367-L455
def arc_argmax(parse_probs, length, tokens_to_keep, ensure_tree=True): """MST Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py Parameters ---------- parse_probs : NDArray seq_len x seq_len, the probability of arcs length : NDArray real sen...
[ "def", "arc_argmax", "(", "parse_probs", ",", "length", ",", "tokens_to_keep", ",", "ensure_tree", "=", "True", ")", ":", "if", "ensure_tree", ":", "I", "=", "np", ".", "eye", "(", "len", "(", "tokens_to_keep", ")", ")", "# block loops and pad heads", "parse...
MST Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py Parameters ---------- parse_probs : NDArray seq_len x seq_len, the probability of arcs length : NDArray real sentence length tokens_to_keep : NDArray mask matrix ensure_tree ...
[ "MST", "Adopted", "from", "Timothy", "Dozat", "https", ":", "//", "github", ".", "com", "/", "tdozat", "/", "Parser", "/", "blob", "/", "master", "/", "lib", "/", "models", "/", "nn", ".", "py" ]
python
train
ARMmbed/yotta
yotta/lib/component.py
https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/component.py#L233-L247
def hasDependencyRecursively(self, name, target=None, test_dependencies=False): ''' Check if this module, or any of its dependencies, have a dependencies with the specified name in their dependencies, or in their targetDependencies corresponding to the specified target. Note...
[ "def", "hasDependencyRecursively", "(", "self", ",", "name", ",", "target", "=", "None", ",", "test_dependencies", "=", "False", ")", ":", "# checking dependencies recursively isn't entirely straightforward, so", "# use the existing method to resolve them all before checking:", "...
Check if this module, or any of its dependencies, have a dependencies with the specified name in their dependencies, or in their targetDependencies corresponding to the specified target. Note that if recursive dependencies are not installed, this test may return a false-...
[ "Check", "if", "this", "module", "or", "any", "of", "its", "dependencies", "have", "a", "dependencies", "with", "the", "specified", "name", "in", "their", "dependencies", "or", "in", "their", "targetDependencies", "corresponding", "to", "the", "specified", "targ...
python
valid
tensorflow/tensor2tensor
tensor2tensor/layers/common_video.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_video.py#L254-L304
def cdna_transformation(prev_image, cdna_input, num_masks, color_channels, dna_kernel_size, relu_shift): """Apply convolutional dynamic neural advection to previous image. Args: prev_image: previous image to be transformed. cdna_input: hidden lyaer to be used for computing CDNA kern...
[ "def", "cdna_transformation", "(", "prev_image", ",", "cdna_input", ",", "num_masks", ",", "color_channels", ",", "dna_kernel_size", ",", "relu_shift", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "cdna_input", ")", "[", "0", "]", "height", "=", "in...
Apply convolutional dynamic neural advection to previous image. Args: prev_image: previous image to be transformed. cdna_input: hidden lyaer to be used for computing CDNA kernels. num_masks: number of masks and hence the number of CDNA transformations. color_channels: the number of color channels in ...
[ "Apply", "convolutional", "dynamic", "neural", "advection", "to", "previous", "image", "." ]
python
train
lawsie/guizero
guizero/Box.py
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Box.py#L87-L98
def set_border(self, thickness, color="black"): """ Sets the border thickness and color. :param int thickness: The thickenss of the border. :param str color: The color of the border. """ self._set_tk_config("highlightthickness", thickness) ...
[ "def", "set_border", "(", "self", ",", "thickness", ",", "color", "=", "\"black\"", ")", ":", "self", ".", "_set_tk_config", "(", "\"highlightthickness\"", ",", "thickness", ")", "self", ".", "_set_tk_config", "(", "\"highlightbackground\"", ",", "utils", ".", ...
Sets the border thickness and color. :param int thickness: The thickenss of the border. :param str color: The color of the border.
[ "Sets", "the", "border", "thickness", "and", "color", "." ]
python
train
geographika/mappyfile
mappyfile/utils.py
https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/utils.py#L164-L202
def dump(d, fp, indent=4, spacer=" ", quote='"', newlinechar="\n", end_comment=False): """ Write d (the Mapfile dictionary) as a formatted stream to fp Parameters ---------- d: dict A Python dictionary based on the the mappyfile schema fp: file A file-like object indent: in...
[ "def", "dump", "(", "d", ",", "fp", ",", "indent", "=", "4", ",", "spacer", "=", "\" \"", ",", "quote", "=", "'\"'", ",", "newlinechar", "=", "\"\\n\"", ",", "end_comment", "=", "False", ")", ":", "map_string", "=", "_pprint", "(", "d", ",", "inden...
Write d (the Mapfile dictionary) as a formatted stream to fp Parameters ---------- d: dict A Python dictionary based on the the mappyfile schema fp: file A file-like object indent: int The number of ``spacer`` characters to indent structures in the Mapfile spacer: strin...
[ "Write", "d", "(", "the", "Mapfile", "dictionary", ")", "as", "a", "formatted", "stream", "to", "fp" ]
python
train
mdickinson/bigfloat
bigfloat/core.py
https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L1750-L1802
def atan2(y, x, context=None): """ Return ``atan(y / x)`` with the appropriate choice of function branch. If ``x > 0``, then ``atan2(y, x)`` is mathematically equivalent to ``atan(y / x)``. If ``x < 0`` and ``y > 0``, ``atan(y, x)`` is equivalent to ``π + atan(y, x)``. If ``x < 0`` and ``y < 0``,...
[ "def", "atan2", "(", "y", ",", "x", ",", "context", "=", "None", ")", ":", "return", "_apply_function_in_current_context", "(", "BigFloat", ",", "mpfr", ".", "mpfr_atan2", ",", "(", "BigFloat", ".", "_implicit_convert", "(", "y", ")", ",", "BigFloat", ".",...
Return ``atan(y / x)`` with the appropriate choice of function branch. If ``x > 0``, then ``atan2(y, x)`` is mathematically equivalent to ``atan(y / x)``. If ``x < 0`` and ``y > 0``, ``atan(y, x)`` is equivalent to ``π + atan(y, x)``. If ``x < 0`` and ``y < 0``, the result is ``-π + atan(y, x)``. ...
[ "Return", "atan", "(", "y", "/", "x", ")", "with", "the", "appropriate", "choice", "of", "function", "branch", "." ]
python
train
KeithSSmith/switcheo-python
switcheo/authenticated_client.py
https://github.com/KeithSSmith/switcheo-python/blob/22f943dea1ad7d692b2bfcd9f0822ec80f4641a6/switcheo/authenticated_client.py#L653-L687
def withdrawal(self, asset, amount, private_key): """ This function is a wrapper function around the create and execute withdrawal functions to help make this processes simpler for the end user by combining these requests in 1 step. Execution of this function is as follows:: ...
[ "def", "withdrawal", "(", "self", ",", "asset", ",", "amount", ",", "private_key", ")", ":", "create_withdrawal", "=", "self", ".", "create_withdrawal", "(", "asset", "=", "asset", ",", "amount", "=", "amount", ",", "private_key", "=", "private_key", ")", ...
This function is a wrapper function around the create and execute withdrawal functions to help make this processes simpler for the end user by combining these requests in 1 step. Execution of this function is as follows:: withdrawal(asset="SWTH", amount=1.1, private_key=kp)) The ex...
[ "This", "function", "is", "a", "wrapper", "function", "around", "the", "create", "and", "execute", "withdrawal", "functions", "to", "help", "make", "this", "processes", "simpler", "for", "the", "end", "user", "by", "combining", "these", "requests", "in", "1", ...
python
train
QualiSystems/vCenterShell
package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py
https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/vcenter/vmomi_service.py#L650-L659
def vm_reconfig_task(vm, device_change): """ Create Task for VM re-configure :param vm: <vim.vm obj> VM which will be re-configure :param device_change: :return: Task """ config_spec = vim.vm.ConfigSpec(deviceChange=device_change) task = vm.ReconfigVM_Task...
[ "def", "vm_reconfig_task", "(", "vm", ",", "device_change", ")", ":", "config_spec", "=", "vim", ".", "vm", ".", "ConfigSpec", "(", "deviceChange", "=", "device_change", ")", "task", "=", "vm", ".", "ReconfigVM_Task", "(", "config_spec", ")", "return", "task...
Create Task for VM re-configure :param vm: <vim.vm obj> VM which will be re-configure :param device_change: :return: Task
[ "Create", "Task", "for", "VM", "re", "-", "configure", ":", "param", "vm", ":", "<vim", ".", "vm", "obj", ">", "VM", "which", "will", "be", "re", "-", "configure", ":", "param", "device_change", ":", ":", "return", ":", "Task" ]
python
train
MycroftAI/mycroft-precise
precise/functions.py
https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/functions.py#L30-L41
def weighted_log_loss(yt, yp) -> Any: """ Binary crossentropy with a bias towards false negatives yt: Target yp: Prediction """ from keras import backend as K pos_loss = -(0 + yt) * K.log(0 + yp + K.epsilon()) neg_loss = -(1 - yt) * K.log(1 - yp + K.epsilon()) return LOSS_BIAS * K....
[ "def", "weighted_log_loss", "(", "yt", ",", "yp", ")", "->", "Any", ":", "from", "keras", "import", "backend", "as", "K", "pos_loss", "=", "-", "(", "0", "+", "yt", ")", "*", "K", ".", "log", "(", "0", "+", "yp", "+", "K", ".", "epsilon", "(", ...
Binary crossentropy with a bias towards false negatives yt: Target yp: Prediction
[ "Binary", "crossentropy", "with", "a", "bias", "towards", "false", "negatives", "yt", ":", "Target", "yp", ":", "Prediction" ]
python
train