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 None, the urllib default is used :return: html of the url """ headers = {'User-Agent': 'Mozilla/5.0'} req = urllib.request.Request(url, None, headers) html = urllib.request.urlopen(req, data=None, timeout=timeout).read() if is_threaded: SimpleCrawler._results[url] = html return html
[ "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, return servers that have one or more of the given roles. """ def func(): return [s['external_ip'] for s in self.servers_with_roles(roles, env, match_all)] return func
[ "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 namespace of arguments """ parser = argparse.ArgumentParser() # Required arguments parser.add_argument("callsign", help="Callsign of radio") parser.add_argument("id", type=int, help="ID number radio") # Optional arguments parser.add_argument("-l", "--loopback", action="store_true", help="Use software loopback serial port") parser.add_argument("-p", "--port", default="/dev/ttyUSB0", help="Physical serial port of radio") # Parse and return arguments return parser.parse_args()
[ "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 pycdlibexception.PyCdlibInternalError('PD record not yet initialized!') return b'PD' + struct.pack('=BB', RRPDRecord.length(self.padding), SU_ENTRY_VERSION) + self.padding
[ "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': 'Most seen people/groups', 'score_attr': 'num_events', 'object_list': object_list, }
[ "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.auto_encode_decode and hasattr(content, 'content_encoding')): try: content.body = content.body.decode(content.content_encoding) except Exception: pass amqp_method = (self._method_override.get(method_sig) or channel._METHOD_MAP.get(method_sig, None)) if amqp_method is None: raise AMQPNotImplementedError( 'Unknown AMQP method {0!r}'.format(method_sig)) if content is None: return amqp_method(channel, args) else: return amqp_method(channel, args, content)
[ "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._update_config_location(directory) elif filename==TAG_FILE: print("%s - Updating tags"%(TAG_FILE)) return self._update_config_tags(directory) elif filename==SET_FILE: print("%s - Updating sets"%(SET_FILE)) return self._update_config_sets(directory) elif filename==MEGAPIXEL_FILE: print("%s - Updating photo size"%(MEGAPIXEL_FILE)) return self._upload_media(directory,resize_request=True) elif ext in self.FLICKR_META_EXTENSIONS: return self._update_meta(directory,basefilename) return False
[ "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 """ import utool as ut if order in ['mru', 'lru']: cmdkw = dict(verbose=False, quiet=True, silence=True) winid_order_str = ut.cmd( 'xprop -root | grep "^_NET_CLIENT_LIST_STACKING"', **cmdkw)[0] winid_order = winid_order_str.split('#')[1].strip().split(', ')[::-1] winid_order = [int(h, 16) for h in winid_order] if order == 'lru': winid_order = winid_order[::-1] else: raise NotImplementedError(order) return winid_order
[ "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 : list list of names of klass methods to be constructed Returns ------- The generator yields a sequence of strings, each suitable for exec'ing, that define implementations of the named methods for DataFrameGroupBy or SeriesGroupBy. Since we don't want to override methods explicitly defined in the base class, any such name is skipped. """ method_wrapper_template = \ """def %(name)s(%(sig)s) : \""" %(doc)s \""" f = %(self)s.__getattr__('%(name)s') return f(%(args)s)""" property_wrapper_template = \ """@property def %(name)s(self) : \"""%(doc)s\""" return self.__getattr__('%(name)s')""" for name in whitelist: # don't override anything that was explicitly defined # in the base class if hasattr(base, name): continue # ugly, but we need the name string itself in the method. f = getattr(klass, name) doc = f.__doc__ doc = doc if type(doc) == str else '' if isinstance(f, types.MethodType): wrapper_template = method_wrapper_template decl, args = make_signature(f) # pass args by name to f because otherwise # GroupBy._make_wrapper won't know whether # we passed in an axis parameter. args_by_name = ['{0}={0}'.format(arg) for arg in args[1:]] params = {'name': name, 'doc': doc, 'sig': ','.join(decl), 'self': args[0], 'args': ','.join(args_by_name)} else: wrapper_template = property_wrapper_template params = {'name': name, 'doc': doc} yield wrapper_template % params
[ "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 Returns ------- The generator yields a sequence of strings, each suitable for exec'ing, that define implementations of the named methods for DataFrameGroupBy or SeriesGroupBy. Since we don't want to override methods explicitly defined in the base class, any such name is skipped.
[ "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 typing ' '"print";\n', fg='yellow', ) + click.style( '3. See the full traceback without submitting details ' '(default: "ignore").\n\n', fg='red', ) + 'Please select an action by typing its name', type=click.Choice([ 'open', 'print', 'ignore', ], ), default='ignore', ) getattr(self, '_process_' + value)()
[ "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 InvalidResourceError(method, uri) check_required_fields(method, uri, body, ['name']) new_password_rule = console.password_rules.add(body) return {'element-uri': new_password_rule.uri}
[ "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 """ ################ > IMPORTS ################ ## STANDARD LIB ## ## THIRD PARTY ## import matplotlib.pyplot as plt import numpy as np ## LOCAL APPLICATION ## ################ > VARIABLE SETTINGS ###### ################ >ACTION(S) ################ for filterFile in filterList: data = np.genfromtxt(filterFile) plt.plot(data[:, 0], data[:, 1]) plt.show() return
[ "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['iterationCount'] if numIters >= 0: iterTracker = iter(xrange(numIters)) else: iterTracker = iter(itertools.count()) # Initialize periodic activities periodic = PeriodicActivityMgr( requestedActivities=self._createPeriodicActivities()) # Reset sequence states in the model, so it starts looking for a new # sequence # TODO: should this be done in OPFTaskDriver.setup(), instead? Is it always # desired in Nupic? self.__model.resetSequenceStates() # Have Task Driver perform its initial setup activities, including setup # callbacks self.__taskDriver.setup() # Run it! while True: # Check controlling iterator first try: next(iterTracker) except StopIteration: break # Read next input record try: inputRecord = self.__datasetReader.next() except StopIteration: break # Process input record result = self.__taskDriver.handleInputRecord(inputRecord=inputRecord) if InferenceElement.encodings in result.inferences: result.inferences.pop(InferenceElement.encodings) self.__predictionLogger.writeRecord(result) # Run periodic activities periodic.tick() # Dump the experiment metrics at the end of the task self._getAndEmitExperimentMetrics(final=True) # Have Task Driver perform its final activities self.__taskDriver.finalize() # Reset sequence states in the model, so it starts looking for a new # sequence # TODO: should this be done in OPFTaskDriver.setup(), instead? Is it always # desired in Nupic? self.__model.resetSequenceStates()
[ "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 # if value is negative, return 0 cutoff_index = max(int(len(y_true) * proportion) - 1, 0) # Get the cutoff value cutoff_value = scores_sorted[cutoff_index] # Convert scores to binary, by comparing them with the cutoff value scores_binary = np.array([int(y >= cutoff_value) for y in y_score]) # Calculate precision using sklearn function if ignore_nas: precision = __precision(y_true, scores_binary) else: precision = precision_score(y_true, scores_binary) return precision, cutoff_value
[ "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 MergeError("values must be identical ('%s' vs '%s')" % (transitfeed.EncodeUnicode(a), transitfeed.EncodeUnicode(b))) return b
[ "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._count > 1, lambda: self._summary('stddev', self._std()), str) return tf.summary.merge([mean_summary, std_summary])
[ "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(highlight) return highlight
[ "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 [Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD] \ and p.default == Parameter.empty] args = [init_args[key] for key in args_keys] kwargs = _get_var_kwargs(parameters, args_keys, init_args)\ if add_kwargs else\ _get_kwargs(parameters, init_args) except KeyError as key_error: msg_format = 'parameter with key "{0}" is not found in node args' raise RenderingError(msg_format.format(key_error.args[0])) return (args, kwargs)
[ "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, " "got %s" % len(args)) if kwargs: raise TypeError( "expected positional or keyword arguments, not both") # got positional arguments only self.keys, self.values = map(self._validate_argument, args) elif kwargs: has_kv = 'keys' in kwargs and 'values' in kwargs has_of = 'of' in kwargs if not (has_kv or has_of): raise TypeError("expected keys/values or items matchers, " "but got: %s" % list(kwargs.keys())) if has_kv and has_of: raise TypeError( "expected keys & values, or items matchers, not both") if has_kv: # got keys= and values= matchers self.keys = self._validate_argument(kwargs['keys']) self.values = self._validate_argument(kwargs['values']) else: # got of= matcher, which can be a tuple of matchers, # or a single matcher for dictionary items of = kwargs['of'] if isinstance(of, tuple): try: # got of= as tuple of matchers self.keys, self.values = \ map(self._validate_argument, of) except ValueError: raise TypeError( "of= tuple has to be a pair of matchers/types" % ( self.__class__.__name__,)) else: # got of= as a single matcher self.items = self._validate_argument(of)
[ "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 False host = sampling_req.get('host', None) method = sampling_req.get('method', None) path = sampling_req.get('path', None) service = sampling_req.get('service', None) service_type = sampling_req.get('service_type', None) return (not host or wildcard_match(self._host, host)) \ and (not method or wildcard_match(self._method, method)) \ and (not path or wildcard_match(self._path, path)) \ and (not service or wildcard_match(self._service, service)) \ and (not service_type or wildcard_match(self._service_type, service_type))
[ "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" in resp: raise RuntimeError( f"Login failed: {resp['error'].get('message') or resp['error']}" ) self.session = resp["session"] self.conn.make_call("useSession", self.session) self.conn.cookies.update({"session": self.session}) self.logged_in = True return True
[ "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 state will fail. Set the force option to True to remove the user even if they are logged in. Not supported in FreeBSD and Solaris, Default is ``False``. ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} lusr = __salt__['user.info'](name) if lusr: # The user is present, make it not present if __opts__['test']: ret['result'] = None ret['comment'] = 'User {0} set for removal'.format(name) return ret beforegroups = set(salt.utils.user.get_group_list(name)) ret['result'] = __salt__['user.delete'](name, purge, force) aftergroups = set([g for g in beforegroups if __salt__['group.info'](g)]) if ret['result']: ret['changes'] = {} for g in beforegroups - aftergroups: ret['changes']['{0} group'.format(g)] = 'removed' ret['changes'][name] = 'removed' ret['comment'] = 'Removed user {0}'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to remove user {0}'.format(name) return ret ret['comment'] = 'User {0} is not present'.format(name) return ret
[ "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 remove the user even if they are logged in. Not supported in FreeBSD and Solaris, Default is ``False``.
[ "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. """ for attr in dir(module): candidate = getattr(module, attr) if (isclass(candidate) and issubclass(candidate, cls) and candidate is not RelationBase): return candidate return None
[ "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 there are a lot of duplicate labels, no labeled artists, or when the color of the legend doesn't exactly match the color in the figure (e.g. because of the use of transparency). Parameters ---------- g : Visualizer or Axes object The graph to draw the legend on, either a Visualizer or a matplotlib Axes object. If None, the current axes are drawn on, but this is not recommended. labels : list of str The text labels to associate with the legend. Note that the labels will be added to the legend in the order specified. colors : list of colors A list of any valid matplotlib color reference. The number of colors specified must be equal to the number of labels. legend_kwargs : dict Any additional keyword arguments to pass to the legend. Returns ------- legend: Legend artist The artist created by the ax.legend() call, returned for further manipulation if required by the caller. Notes ----- Right now this method simply draws the patches as rectangles and cannot take into account the line or scatter plot properties (e.g. line style or marker style). It is possible to add Line2D patches to the artist that do add manual styles like this, which we can explore in the future. .. seealso:: https://matplotlib.org/gallery/text_labels_and_annotations/custom_legends.html """ # Get access to the matplotlib Axes if isinstance(g, Visualizer): g = g.ax elif g is None: g = plt.gca() # Ensure that labels and colors are the same length to prevent odd behavior. if len(colors) != len(labels): raise YellowbrickValueError( "please specify the same number of colors as labels!" ) # Create the legend handles with the associated colors and labels handles = [ patches.Patch(color=color, label=label) for color, label in zip(colors, labels) ] # Return the Legend artist return g.legend(handles=handles, **legend_kwargs)
[ "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 the color of the legend doesn't exactly match the color in the figure (e.g. because of the use of transparency). Parameters ---------- g : Visualizer or Axes object The graph to draw the legend on, either a Visualizer or a matplotlib Axes object. If None, the current axes are drawn on, but this is not recommended. labels : list of str The text labels to associate with the legend. Note that the labels will be added to the legend in the order specified. colors : list of colors A list of any valid matplotlib color reference. The number of colors specified must be equal to the number of labels. legend_kwargs : dict Any additional keyword arguments to pass to the legend. Returns ------- legend: Legend artist The artist created by the ax.legend() call, returned for further manipulation if required by the caller. Notes ----- Right now this method simply draws the patches as rectangles and cannot take into account the line or scatter plot properties (e.g. line style or marker style). It is possible to add Line2D patches to the artist that do add manual styles like this, which we can explore in the future. .. seealso:: https://matplotlib.org/gallery/text_labels_and_annotations/custom_legends.html
[ "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 = path[path_length:] if IS_WINDOWS: relative_path = windows_to_unix_path(relative_path) yield 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() # Show same day if it's before 17:00 if now.hour < 17: now = now.replace(hour=0, minute=0, second=0, microsecond=0) blocks = self.order_by("date", "block_letter").filter(date__gte=now) if max_number == -1: return blocks return blocks[:max_number]
[ "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 the Voronoi vertices 4-fold sites: Assigned when Voronoi vertives overlap """ # Get top layer C = self.B[-self.ntop - 1:-1] SC = C * (3, 3, 1) D = {} cell = C.get_cell() top_dist = 1 """Top sites: atomic positions """ for i, atom in \ enumerate([atom for atom in SC if np.linalg.norm(atom.position[:2] - ads_pos) < top_dist]): k = 'top_site-{}'.format(i) D[k] = {} D[k]['pos'] = atom.position D[k]['sym'] = atom.symbol """Bridge sites: bewteen atomic pairs """ bridge_dist = 0.5 * cell[0][0] b_index = 0 for atomi in [atom for atom in SC if np.linalg.norm(atom.position[:2] - ads_pos) < bridge_dist]: pos1 = atomi.position # Atom bairs should be close to each other and close to # adsorbate for atom in \ [atom for atom in SC if np.linalg.norm(atom.position - pos1) < 1.5 * bridge_dist and np.linalg.norm(atom.position[:2] - ads_pos) < bridge_dist and not (atom.position == pos1).all()]: pos2 = atom.position # bridge site is average position bridge_pos = 0.5 * (pos1 + pos2) k = 'bridge_site-{}'.format(b_index) D[k] = {} D[k]['pos'] = bridge_pos D[k]['sym'] = atomi.symbol + '_' + atom.symbol b_index += 1 """Hollow sites: Voronoi vertices """ hollow_dist = 1 vor = Voronoi(SC.positions[:, :2]) vertices = vor.vertices # map vertices close to adsorbate close_v = [v for v in vertices if np.linalg.norm(v - ads_pos[:2]) < hollow_dist] h_index = 1 ff_index = 1 for v in close_v: # Check if vertices overlap close_v_v = [v0 for v0 in close_v if np.linalg.norm(v0 - v) < 0.5] if len(close_v_v) > 1: v_mean = np.mean(close_v_v, axis=0) k = '4fold_{}'.format(ff_index) D[k] = {} D[k]['pos'] = v_mean # Delete bridge sites overlapping with 4fold for key in [key for key in list(D.keys()) if 'bridge' in key]: bridge_pos = D[key]['pos'] if np.linalg.norm(bridge_pos[:2] - v) < 0.3: del D[key] ffold_max_dist = sorted([np.linalg.norm(v_mean - m[:2]) for m in SC.positions])[4] symb = [atom.symbol for atom in SC if np.linalg.norm(v_mean - atom.position[:2]) < ffold_max_dist] D[k]['sym'] = '_'.join(symb) ff_index += 1 else: # Regular hollow site k = 'hollow_site-{}'.format(h_index) D[k] = {} D[k]['pos'] = v hollow_max_dist = sorted([np.linalg.norm(v - m[:2]) for m in SC.positions])[3] symb = [atom.symbol for atom in SC if np.linalg.norm(v - atom.position[:2]) < hollow_max_dist] D[k]['sym'] = '_'.join(symb) h_index += 1 return D
[ "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: Assigned when Voronoi vertives overlap
[ "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 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_storage_v1beta1.BigQueryStorageClient() >>> >>> # TODO: Initialize `session`: >>> session = {} >>> >>> # TODO: Initialize `requested_streams`: >>> requested_streams = 0 >>> >>> response = client.batch_create_read_session_streams(session, requested_streams) Args: session (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.ReadSession]): Required. Must be a non-expired session obtained from a call to CreateReadSession. Only the name field needs to be set. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_storage_v1beta1.types.ReadSession` requested_streams (int): Required. Number of new streams requested. Must be positive. Number of added streams may be less than this, see CreateReadSessionRequest for more information. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.bigquery_storage_v1beta1.types.BatchCreateReadSessionStreamsResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "batch_create_read_session_streams" not in self._inner_api_calls: self._inner_api_calls[ "batch_create_read_session_streams" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_create_read_session_streams, default_retry=self._method_configs[ "BatchCreateReadSessionStreams" ].retry, default_timeout=self._method_configs[ "BatchCreateReadSessionStreams" ].timeout, client_info=self._client_info, ) request = storage_pb2.BatchCreateReadSessionStreamsRequest( session=session, requested_streams=requested_streams ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("session.name", session.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( # pragma: no cover routing_header ) metadata.append(routing_metadata) # pragma: no cover return self._inner_api_calls["batch_create_read_session_streams"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ "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_storage_v1beta1.BigQueryStorageClient() >>> >>> # TODO: Initialize `session`: >>> session = {} >>> >>> # TODO: Initialize `requested_streams`: >>> requested_streams = 0 >>> >>> response = client.batch_create_read_session_streams(session, requested_streams) Args: session (Union[dict, ~google.cloud.bigquery_storage_v1beta1.types.ReadSession]): Required. Must be a non-expired session obtained from a call to CreateReadSession. Only the name field needs to be set. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.bigquery_storage_v1beta1.types.ReadSession` requested_streams (int): Required. Number of new streams requested. Must be positive. Number of added streams may be less than this, see CreateReadSessionRequest for more information. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.bigquery_storage_v1beta1.types.BatchCreateReadSessionStreamsResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
[ "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_prob/div): self.mutate_add_node(config) elif r < ((config.node_add_prob + config.node_delete_prob)/div): self.mutate_delete_node(config) elif r < ((config.node_add_prob + config.node_delete_prob + config.conn_add_prob)/div): self.mutate_add_connection(config) elif r < ((config.node_add_prob + config.node_delete_prob + config.conn_add_prob + config.conn_delete_prob)/div): self.mutate_delete_connection() else: if random() < config.node_add_prob: self.mutate_add_node(config) if random() < config.node_delete_prob: self.mutate_delete_node(config) if random() < config.conn_add_prob: self.mutate_add_connection(config) if random() < config.conn_delete_prob: self.mutate_delete_connection() # Mutate connection genes. for cg in self.connections.values(): cg.mutate(config) # Mutate node genes (bias, response, etc.). for ng in self.nodes.values(): ng.mutate(config)
[ "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. :param size: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file C{filename}. :param perms: the access permissions to this memory. :param filename: the pathname to the file to map. :param offset: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file C{filename}. :return: the starting address where the file was mapped. :rtype: int :raises error: - 'Address shall be concrete' if C{addr} is not an integer number. - 'Address too big' if C{addr} goes beyond the limit of the memory. - 'Map already used' if the piece of memory starting in C{addr} and with length C{size} isn't free. """ # If addr is NULL, the system determines where to allocate the region. assert addr is None or isinstance(addr, int), 'Address shall be concrete' assert size > 0 self.cpu._publish('will_map_memory', addr, size, perms, filename, offset) # address is rounded down to the nearest multiple of the allocation granularity if addr is not None: assert addr < self.memory_size, 'Address too big' addr = self._floor(addr) # size value is rounded up to the next page boundary size = self._ceil(size) # If zero search for a spot addr = self._search(size, addr) # It should not be allocated for i in range(self._page(addr), self._page(addr + size)): assert i not in self._page2map, 'Map already used' # Create the map m = FileMap(addr, size, perms, filename, offset) # Okay, ready to alloc self._add(m) logger.debug('New file-memory map @%x size:%x', addr, size) self.cpu._publish('did_map_memory', addr, size, perms, filename, offset, addr) return addr
[ "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 starting at offset C{offset} in the file C{filename}. :param perms: the access permissions to this memory. :param filename: the pathname to the file to map. :param offset: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file C{filename}. :return: the starting address where the file was mapped. :rtype: int :raises error: - 'Address shall be concrete' if C{addr} is not an integer number. - 'Address too big' if C{addr} goes beyond the limit of the memory. - 'Map already used' if the piece of memory starting in C{addr} and with length C{size} isn't free.
[ "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_fwhm self._smooth_fwhm = smooth_fwhm try: data = self.get_data(smoothed=True, masked=True, safe_copy=True) except ValueError as ve: self._smooth_fwhm = old_smooth_fwhm raise else: self._smooth_fwhm = smooth_fwhm return data
[ "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). """ am, handler = self.getDataHandler(measurementId, deviceId) if am is not None: am.status = MeasurementStatus.RECORDING am.updateDeviceStatus(deviceId, RecordStatus.RECORDING) handler.start(am.idAsPath) return True else: return False
[ "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_url)['resources'] return [RestResource(resource, self.rest_client) for resource in json_resources]
[ "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", "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", "192.88.99.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "255.255.255.255/32", "224.0.0.0/4", ] for network in networks: try: ipaddr = struct.unpack(">I", socket.inet_aton(ip))[0] netaddr, bits = network.split("/") network_low = struct.unpack(">I", socket.inet_aton(netaddr))[0] network_high = network_low | 1 << (32 - int(bits)) - 1 if ipaddr <= network_high and ipaddr >= network_low: return True except Exception: continue return False
[ "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 RuntimeError('ERROR: Path {} does not exist'.format(local_path)) temp_identifier = str(uuid.uuid1()) if os.path.isdir(local_path): sync_local_path_to_vm(local_path, os.path.join(vm_cp_path(remote_name), temp_identifier), demote=demote) move_dir_inside_container(remote_name, os.path.join(constants.CONTAINER_CP_DIR, temp_identifier), remote_path) else: sync_local_path_to_vm(local_path, os.path.join(vm_cp_path(remote_name), temp_identifier), demote=demote) move_file_inside_container(remote_name, os.path.join(constants.CONTAINER_CP_DIR, temp_identifier), remote_path)
[ "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 aka service type is needed. The namespace defines the scope or service type of the given action, the same action name can appear in different namespaces. The way how to obtain the needed information's is either through the documentation of the vendor of the device. Or through a discovery requests which return's the URL to the root device description XML. :param str uri: the control URI, for example ``/upnp/control/hosts`` :param str namespace: the namespace for the given action, for example ``urn:dslforum-org:service:Hosts:1`` :param str action: the name of the action to call, for example ``GetGenericHostEntry`` :param float timeout: the timeout to wait for the action to be executed :param kwargs: optional arguments for the given action, depends if the action needs parameter. The arguments are given as dict where the key is the parameter name and the value the value of the parameter. :type kwargs: dict[str, str] :return: returns the results of the action, if any. The results are structured as dict where the key is the name of the result argument and the value is the value of the result. :rtype: dict[str,str] :raises ValueError: if parameters are not set correctly :raises requests.exceptions.ConnectionError: when the action can not be placed on the device :raises requests.exceptions.ConnectTimeout: when download time out Example: :: device = DeviceTR64(...) device.execute("/upnp/control/hosts", "urn:dslforum-org:service:Hosts:1", "GetGenericHostEntry", {"NewIndex": 1}) {'NewActive': '0', 'NewIPAddress': '192.168.0.23', 'NewMACAddress': '9C:20:7B:E7:FF:5F', 'NewInterfaceType': 'Ethernet', 'NewHostName': 'Apple-TV', 'NewAddressSource': 'DHCP', 'NewLeaseTimeRemaining': '0'} .. seealso:: `Additional short explanation of the UPnP protocol <http://www.upnp-hacks.org/upnp.html>`_ :class:`~simpletr64.Discover`, :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions`, :meth:`~simpletr64.DeviceTR64.loadSCPD` """ if not uri: raise ValueError("No action URI has been defined.") if not namespace: raise ValueError("No namespace has been defined.") if not action: raise ValueError("No action has been defined.") # soap headers header = {'Content-Type': 'text/xml; charset="UTF-8"', 'Soapaction': '"' + namespace + "#" + action + '"'} # build SOAP body body = '''<?xml version="1.0" encoding="UTF-8"?> <s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <s:Header/> <s:Body>\n''' body += " <u:" + action + ' xmlns="' + namespace + '">\n' arguments = {} for key in kwargs.keys(): body += " <" + key + ">" + str(kwargs[key]) + "</" + key + ">\n" arguments[key] = str(kwargs[key]) body += " </u:" + action + ">\n" body += '''</s:Body> </s:Envelope>''' # setup proxies proxies = {} if self.__httpsProxy: proxies = {"https": self.__httpsProxy} if self.__httpProxy: proxies = {"http": self.__httpProxy} # setup authentication auth = None if self.__password: auth = HTTPDigestAuth(self.__username, self.__password) # build the URL location = self.__protocol + "://" + self.__hostname + ":" + str(self.port) + uri # Post http request request = requests.post(location, data=body, headers=header, auth=auth, proxies=proxies, timeout=float(timeout), verify=self.__verify) if request.status_code != 200: errorStr = DeviceTR64._extractErrorString(request) raise ValueError('Could not execute "' + action + str(arguments) + '": ' + str(request.status_code) + ' - ' + request.reason + " -- " + errorStr) # parse XML return try: root = ET.fromstring(request.text.encode('utf-8')) except Exception as e: raise ValueError("Can not parse results for the action: " + str(e)) # iterate in the XML structure to get the action result actionNode = root[0][0] # we need to remove XML namespace for the action node namespaceLength = len(namespace) + 2 # add braces tag = actionNode.tag[namespaceLength:] if tag != (action + "Response"): raise ValueError('Soap result structure is wrong, expected action "' + action + 'Response" got "' + tag + '".') # pack all the received results results = {} for resultNode in actionNode: results[resultNode.tag] = resultNode.text return results
[ "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 service type of the given action, the same action name can appear in different namespaces. The way how to obtain the needed information's is either through the documentation of the vendor of the device. Or through a discovery requests which return's the URL to the root device description XML. :param str uri: the control URI, for example ``/upnp/control/hosts`` :param str namespace: the namespace for the given action, for example ``urn:dslforum-org:service:Hosts:1`` :param str action: the name of the action to call, for example ``GetGenericHostEntry`` :param float timeout: the timeout to wait for the action to be executed :param kwargs: optional arguments for the given action, depends if the action needs parameter. The arguments are given as dict where the key is the parameter name and the value the value of the parameter. :type kwargs: dict[str, str] :return: returns the results of the action, if any. The results are structured as dict where the key is the name of the result argument and the value is the value of the result. :rtype: dict[str,str] :raises ValueError: if parameters are not set correctly :raises requests.exceptions.ConnectionError: when the action can not be placed on the device :raises requests.exceptions.ConnectTimeout: when download time out Example: :: device = DeviceTR64(...) device.execute("/upnp/control/hosts", "urn:dslforum-org:service:Hosts:1", "GetGenericHostEntry", {"NewIndex": 1}) {'NewActive': '0', 'NewIPAddress': '192.168.0.23', 'NewMACAddress': '9C:20:7B:E7:FF:5F', 'NewInterfaceType': 'Ethernet', 'NewHostName': 'Apple-TV', 'NewAddressSource': 'DHCP', 'NewLeaseTimeRemaining': '0'} .. seealso:: `Additional short explanation of the UPnP protocol <http://www.upnp-hacks.org/upnp.html>`_ :class:`~simpletr64.Discover`, :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions`, :meth:`~simpletr64.DeviceTR64.loadSCPD`
[ "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. 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 index system shape=(n_patom,) dtype=intc physical_unit : str, optional Physical unit used for force contants. Default is None. compression : str or int, optional h5py's lossless compression filters (e.g., "gzip", "lzf"). See the detail at docstring of h5py.Group.create_dataset. Default is None. """ try: import h5py except ImportError: raise ModuleNotFoundError("You need to install python-h5py.") with h5py.File(filename, 'w') as w: w.create_dataset('force_constants', data=force_constants, compression=compression) if p2s_map is not None: w.create_dataset('p2s_map', data=p2s_map) if physical_unit is not None: dset = w.create_dataset('physical_unit', (1,), dtype='S%d' % len(physical_unit)) dset[0] = np.string_(physical_unit)
[ "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 index system shape=(n_patom,) dtype=intc physical_unit : str, optional Physical unit used for force contants. Default is None. compression : str or int, optional h5py's lossless compression filters (e.g., "gzip", "lzf"). See the detail at docstring of h5py.Group.create_dataset. Default is None.
[ "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): substances = [substances] properties = set(properties) | set(['sid']) if properties else None return pd.DataFrame.from_records([s.to_dict(properties) for s in substances], index='sid')
[ "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_state_up')) != ( original_port.get('admin_state_up'))): new_port_data = {'port': {}} new_port_data['port']['admin_state_up'] = ( updated_port.get('admin_state_up')) original_device_owner = original_port.get('device_owner', '') if original_device_owner.startswith('network'): router_id = original_port.get('device_id') context = kwargs.get('context') l3plugin = bc.get_plugin(L3_ROUTER_NAT) if l3plugin and router_id: l3plugin._notify_port_update_routers(context, router_id, original_port, new_port_data, 'update_port_status_cfg')
[ "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(method='sizes', command='?per_page=100') ret = {} for size in items['sizes']: ret[size['slug']] = {} for item in six.iterkeys(size): ret[size['slug']][item] = six.text_type(size[item]) return ret
[ "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'], '-o', outfn]) subprocess.call(command)
[ "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 'grab_anywhere' in _3to2kwargs: grab_anywhere = _3to2kwargs['grab_anywhere']; del _3to2kwargs['grab_anywhere'] else: grab_anywhere = False if 'no_titlebar' in _3to2kwargs: no_titlebar = _3to2kwargs['no_titlebar']; del _3to2kwargs['no_titlebar'] else: no_titlebar = False if 'font' in _3to2kwargs: font = _3to2kwargs['font']; del _3to2kwargs['font'] else: font = None if 'line_width' in _3to2kwargs: line_width = _3to2kwargs['line_width']; del _3to2kwargs['line_width'] else: line_width = None if 'icon' in _3to2kwargs: icon = _3to2kwargs['icon']; del _3to2kwargs['icon'] else: icon = DEFAULT_WINDOW_ICON if 'non_blocking' in _3to2kwargs: non_blocking = _3to2kwargs['non_blocking']; del _3to2kwargs['non_blocking'] else: non_blocking = False if 'auto_close_duration' in _3to2kwargs: auto_close_duration = _3to2kwargs['auto_close_duration']; del _3to2kwargs['auto_close_duration'] else: auto_close_duration = None if 'auto_close' in _3to2kwargs: auto_close = _3to2kwargs['auto_close']; del _3to2kwargs['auto_close'] else: auto_close = False if 'text_color' in _3to2kwargs: text_color = _3to2kwargs['text_color']; del _3to2kwargs['text_color'] else: text_color = None if 'background_color' in _3to2kwargs: background_color = _3to2kwargs['background_color']; del _3to2kwargs['background_color'] else: background_color = None if 'button_color' in _3to2kwargs: button_color = _3to2kwargs['button_color']; del _3to2kwargs['button_color'] else: button_color = (None, None) if 'title' in _3to2kwargs: title = _3to2kwargs['title']; del _3to2kwargs['title'] else: title = None """ 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 grab_anywhere: :param keep_on_top: :param location: :return: """ tbutton_color = DEFAULT_ERROR_BUTTON_COLOR if button_color == (None, None) else button_color Popup(*args, title=title, button_type=POPUP_BUTTONS_ERROR, background_color=background_color, text_color=text_color, non_blocking=non_blocking, icon=icon, line_width=line_width, button_color=tbutton_color, auto_close=auto_close, auto_close_duration=auto_close_duration, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location)
[ "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 grab_anywhere: :param keep_on_top: :param location: :return:
[ "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.append(chunk.breakline()) else: target_chunks.append(chunk) self.list = target_chunks
[ "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() while True: try: self.fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR) break except (OSError,) as e: if e.errno != errno.EEXIST: raise if (time.time() - start_time) >= self.timeout: raise FileLockException("%s: Timeout occured." % self.lockfile) time.sleep(self.delay) self.is_locked = True
[ "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 = self.editor.textCursor() last_three = self.editor.get_text('sol', 'cursor')[-3:] last_two = self.editor.get_text('sol', 'cursor')[-2:] trailing_text = self.editor.get_text('cursor', 'eol').strip() if self.editor.has_selected_text(): text = self.editor.get_selected_text() self.editor.insert_text("{0}{1}{0}".format(char, text)) # keep text selected, for inserting multiple quotes cursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, 1) cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, len(text)) self.editor.setTextCursor(cursor) elif self.editor.in_comment(): self.editor.insert_text(char) elif (len(trailing_text) > 0 and not unmatched_quotes_in_line(line_to_cursor) == char and not trailing_text[0] in (',', ':', ';', ')', ']', '}')): self.editor.insert_text(char) elif (unmatched_quotes_in_line(line_text) and (not last_three == 3*char)): self.editor.insert_text(char) # Move to the right if we are before a quote elif self.editor.next_char() == char: cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, 1) cursor.clearSelection() self.editor.setTextCursor(cursor) # Automatic insertion of triple double quotes (for docstrings) elif last_three == 3*char: self.editor.insert_text(3*char) cursor = self.editor.textCursor() cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor, 3) cursor.clearSelection() self.editor.setTextCursor(cursor) # If last two chars are quotes, just insert one more because most # probably the user wants to write a docstring elif last_two == 2*char: self.editor.insert_text(char) self.editor.delayed_popup_docstring() # Automatic insertion of quotes else: self.editor.insert_text(2*char) cursor = self.editor.textCursor() cursor.movePosition(QTextCursor.PreviousCharacter) self.editor.setTextCursor(cursor)
[ "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 `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 ``'stored'``. `extensions` and `filter_func` are passed to :meth:`list_templates`. Each template returned will be compiled to the target folder or zipfile. By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set `ignore_errors` to `False` and you will get an exception on syntax errors. If `py_compile` is set to `True` .pyc files will be written to the target instead of standard .py files. This flag does not do anything on pypy and Python 3 where pyc files are not picked up by itself and don't give much benefit. .. versionadded:: 2.4 """ from jinja2.loaders import ModuleLoader if log_function is None: log_function = lambda x: None if py_compile: if not PY2 or PYPY: from warnings import warn warn(Warning('py_compile has no effect on pypy or Python 3')) py_compile = False else: import imp, marshal py_header = imp.get_magic() + \ u'\xff\xff\xff\xff'.encode('iso-8859-15') # Python 3.3 added a source filesize to the header if sys.version_info >= (3, 3): py_header += u'\x00\x00\x00\x00'.encode('iso-8859-15') def write_file(filename, data, mode): if zip: info = ZipInfo(filename) info.external_attr = 0o755 << 16 zip_file.writestr(info, data) else: f = open(os.path.join(target, filename), mode) try: f.write(data) finally: f.close() if zip is not None: from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]) log_function('Compiling into Zip archive "%s"' % target) else: if not os.path.isdir(target): os.makedirs(target) log_function('Compiling into folder "%s"' % target) try: for name in self.list_templates(extensions, filter_func): source, filename, _ = self.loader.get_source(self, name) try: code = self.compile(source, name, filename, True, True) except TemplateSyntaxError as e: if not ignore_errors: raise log_function('Could not compile "%s": %s' % (name, e)) continue filename = ModuleLoader.get_module_filename(name) if py_compile: c = self._compile(code, encode_filename(filename)) write_file(filename + 'c', py_header + marshal.dumps(c), 'wb') log_function('Byte-compiled "%s" as %s' % (name, filename + 'c')) else: write_file(filename, code, 'w') log_function('Compiled "%s" as %s' % (name, filename)) finally: if zip: zip_file.close() log_function('Finished compiling templates')
[ "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 ``'stored'``. `extensions` and `filter_func` are passed to :meth:`list_templates`. Each template returned will be compiled to the target folder or zipfile. By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set `ignore_errors` to `False` and you will get an exception on syntax errors. If `py_compile` is set to `True` .pyc files will be written to the target instead of standard .py files. This flag does not do anything on pypy and Python 3 where pyc files are not picked up by itself and don't give much benefit. .. versionadded:: 2.4
[ "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._lookup(module_path, module_name) if module_file: return new_module_name, module_file return None, None
[ "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. :param iterable scc: A set of nodes that forms a strongly connected component in the graph. :return: None """ # 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): for n in scc: if n in graph[parent_node]: loop_head = n break if loop_head is not None: break if loop_head is None: # randomly pick one loop_head = next(iter(scc)) subgraph = graph.subgraph(scc).copy() # type: networkx.DiGraph for src, _ in list(subgraph.in_edges(loop_head)): subgraph.remove_edge(src, loop_head) ordered_nodes.extend(CFGUtils.quasi_topological_sort_nodes(subgraph))
[ "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 strongly connected component in the graph. :return: None
[ "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 self._task_socket and self._task_scheme == 'pure': self._stop_scheduling_tasks()
[ "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 transformed = ht.fit_transform(transformer_list=transformer_list) result = ht.reverse_transform(tables=transformed) # Check assert result.keys() == ht.table_dict.keys() for name, table in result.items(): assert not result[name].isnull().all().all()
[ "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 vanilla CloudFormation Resources, to which this Function expands :rtype: list """ resources = [] api_generator = ApiGenerator(self.logical_id, self.CacheClusterEnabled, self.CacheClusterSize, self.Variables, self.depends_on, self.DefinitionBody, self.DefinitionUri, self.Name, self.StageName, endpoint_configuration=self.EndpointConfiguration, method_settings=self.MethodSettings, binary_media=self.BinaryMediaTypes, minimum_compression_size=self.MinimumCompressionSize, cors=self.Cors, auth=self.Auth, gateway_responses=self.GatewayResponses, access_log_setting=self.AccessLogSetting, canary_setting=self.CanarySetting, tracing_enabled=self.TracingEnabled, resource_attributes=self.resource_attributes, passthrough_resource_attributes=self.get_passthrough_resource_attributes()) rest_api, deployment, stage, permissions = api_generator.to_cloudformation() resources.extend([rest_api, deployment, stage]) resources.extend(permissions) return resources
[ "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 expands :rtype: list
[ "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( [ [repr(e.text) for e in s.evidence] for s in G.edges[source, target]["InfluenceStatements"] ] )
[ "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.append(item) cls.converters.sort(key=lambda x: x[0]) return cls
[ "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 """ # TODO: make session to optional instance = ElasticQuery(model, query, session, enabled_fields) return instance.search()
[ "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 = page or CtsCapitainsLocalResolver.DEFAULT_PAGE limit = limit or CtsCapitainsLocalResolver.PER_PAGE[1] if limit < CtsCapitainsLocalResolver.PER_PAGE[0] or limit > CtsCapitainsLocalResolver.PER_PAGE[2]: limit = CtsCapitainsLocalResolver.PER_PAGE[1] page = (page - 1) * limit if page > length: realpage = int(ceil(length / limit)) page = limit * (realpage - 1) count = length - 1 elif limit - 1 + page < length: count = limit - 1 + page else: count = length - 1 return page, count + 1, realpage, count - page + 1
[ "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.array(member).ndim ctype = TYPE2STR[type(member)] + NDIM2STR[ndim] lines.add(0, 'cdef public %s %s = %s' % (ctype, name, member)) return lines
[ "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: the radial force """ if not self.isNonAxi: phi= 0. self._compute_xyzforces(R,z,phi,t) return np.cos(phi)*self._cached_Fx+np.sin(phi)*self._cached_Fy
[ "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_next_state: Tensor corresponding to encoded next state. """ combined_input = tf.concat([encoded_state, encoded_next_state], axis=1) hidden = tf.layers.dense(combined_input, 256, activation=self.swish) if self.brain.vector_action_space_type == "continuous": pred_action = tf.layers.dense(hidden, self.act_size[0], activation=None) squared_difference = tf.reduce_sum(tf.squared_difference(pred_action, self.selected_actions), axis=1) self.inverse_loss = tf.reduce_mean(tf.dynamic_partition(squared_difference, self.mask, 2)[1]) else: pred_action = tf.concat( [tf.layers.dense(hidden, self.act_size[i], activation=tf.nn.softmax) for i in range(len(self.act_size))], axis=1) cross_entropy = tf.reduce_sum(-tf.log(pred_action + 1e-10) * self.selected_actions, axis=1) self.inverse_loss = tf.reduce_mean(tf.dynamic_partition(cross_entropy, self.mask, 2)[1])
[ "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 input axis: axis to filter on Returns: A new DataFrame with the filter applied. """ nkw = count_not_none(items, like, regex) if nkw > 1: raise TypeError( "Keyword arguments `items`, `like`, or `regex` are mutually exclusive" ) if nkw == 0: raise TypeError("Must pass either `items`, `like`, or `regex`") if axis is None: axis = "columns" # This is the default info axis for dataframes axis = self._get_axis_number(axis) labels = self.columns if axis else self.index if items is not None: bool_arr = labels.isin(items) elif like is not None: def f(x): return like in to_str(x) bool_arr = labels.map(f).tolist() else: def f(x): return matcher.search(to_str(x)) is not None matcher = re.compile(regex) bool_arr = labels.map(f).tolist() if not axis: return self[bool_arr] return self[self.columns[bool_arr]]
[ "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 new DataFrame with the filter applied.
[ "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_like (optional) errors on observed values """ # For linear models, dy=1 is equivalent to no errors if dy is None: dy = 1 self.t, self.y, self.dy = np.broadcast_arrays(t, y, dy) self._fit(self.t, self.y, self.dy) self._best_period = None # reset best period in case of refitting if self.fit_period: self._best_period = self._calc_best_period() return self
[ "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 observed values
[ "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 = (1.0 / self.scale_radius) * self.grid_to_grid_radii(grid) + 0j return np.real(2.0 * self.scale_radius * self.kappa_s * self.potential_func_sph(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 not found. reason: {0}'.format(e)) # Pass to try to install from the source. pass # Download and install from the source. top_dir_name = self.downloader.download_and_expand() rpm_py_dir = os.path.join(top_dir_name, 'python') setup_py_in_found = False with Cmd.pushd(rpm_py_dir): if self.installer.setup_py.exists_in_path(): setup_py_in_found = True self.installer.run() if not setup_py_in_found: self.installer.install_from_rpm_py_package()
[ "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} & K_{Bx,By} & K_{Bx,S} & K_{Bx,T} \\ K_{Bx,By} & K_{By} & K_{By,S} & K_{By,T} \\ K_{Bx,S} & K_{By,S} & K_{S} & K_{S,T} \\ K_{Bx,T} & K_{Bx,T} & K_{S,T} & K_{T} \end{bmatrix} \times L_0 .. currentmodule:: dnaMD Parameters ---------- bp : list List of two base-steps forming the DNA segment. For example: with ``bp=[5, 50]``, 5-50 base-step segment will be considered. frames : list List of two trajectory frames between which parameters will be extracted. It can be used to select portions of the trajectory. For example, with ``frames=[100, 1000]``, 100th to 1000th frame of the trajectory will be considered. paxis : str Axis parallel to global helical-axis(``'X'``, or ``'Y'`` or ``'Z'``). Only require when bending motions are included in the calculation. masked : bool ``Default=False``. To skip specific frames/snapshots. ``DNA.mask`` array should be set to use this functionality. This array contains boolean (either ``True`` or ``False``) value for each frame to mask the frames. Presently, mask array is automatically generated during :meth:`dnaMD.DNA.generate_smooth_axis` to skip those frames where 3D fitting curve was not successful within the given criteria. matrix : bool If it is ``True``, elastic constant matrix will be returned. Otherwise, by default modulus matrix will be returned. Return ------ mean : numpy.ndarray Value of bending angles, contour length and twist angle (as 1D array) at which energy is zero. Minimum point on free energy landscape. .. math:: \begin{bmatrix} \theta^{x}_0 & \theta^{y}_0 & L_0 & \phi_0 \end{bmatrix} result : numpy.ndarray Either elastic matrix or modulus matrix depending on ``matrix`` value. """ if self.esType == 'ST': raise KeyError(' Use dnaEY.getStretchTwistModulus for Stretching-Twisting modulus.') frames = self._validateFrames(frames) name = '{0}-{1}-{2}-{3}'.format(bp[0], bp[1], frames[0], frames[1]) if name not in self.esMatrix: time, array = self.extractGlobalParameters(self.dna, bp, frames=frames, paxis=paxis, masked=masked) mean = np.mean(array, axis=1) esMatrix = np.asarray(self.getElasticMatrix(array)) self.esMatrix[name] = esMatrix self.minimumPoint[name] = mean else: esMatrix = self.esMatrix[name] mean = self.minimumPoint[name] if not matrix: result = 4.1419464 * np.array(esMatrix) * mean[2] # Calculate modulus else: result = esMatrix return mean, result
[ "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} \\ K_{Bx,S} & K_{By,S} & K_{S} & K_{S,T} \\ K_{Bx,T} & K_{Bx,T} & K_{S,T} & K_{T} \end{bmatrix} \times L_0 .. currentmodule:: dnaMD Parameters ---------- bp : list List of two base-steps forming the DNA segment. For example: with ``bp=[5, 50]``, 5-50 base-step segment will be considered. frames : list List of two trajectory frames between which parameters will be extracted. It can be used to select portions of the trajectory. For example, with ``frames=[100, 1000]``, 100th to 1000th frame of the trajectory will be considered. paxis : str Axis parallel to global helical-axis(``'X'``, or ``'Y'`` or ``'Z'``). Only require when bending motions are included in the calculation. masked : bool ``Default=False``. To skip specific frames/snapshots. ``DNA.mask`` array should be set to use this functionality. This array contains boolean (either ``True`` or ``False``) value for each frame to mask the frames. Presently, mask array is automatically generated during :meth:`dnaMD.DNA.generate_smooth_axis` to skip those frames where 3D fitting curve was not successful within the given criteria. matrix : bool If it is ``True``, elastic constant matrix will be returned. Otherwise, by default modulus matrix will be returned. Return ------ mean : numpy.ndarray Value of bending angles, contour length and twist angle (as 1D array) at which energy is zero. Minimum point on free energy landscape. .. math:: \begin{bmatrix} \theta^{x}_0 & \theta^{y}_0 & L_0 & \phi_0 \end{bmatrix} result : numpy.ndarray Either elastic matrix or modulus matrix depending on ``matrix`` value.
[ "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.physical_plan.topology.state if status == 1: return "Running" elif status == 2: return "Paused" elif status == 3: return "Killed" else: return "Unknown"
[ "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)$ fulfill .. math:: \text{expr} = \sum_{n=0}^{N} c_n (x - x_0)^n + O(N+1) Args: param: Expansion parameter $x$ about (Scalar): Point $x_0$ about which to expand order: Maximum order $N$ of expansion (>= 0) Returns: tuple of length ``order + 1``, where the entries are the expansion coefficients, $(c_0, \dots, c_N)$. Note: The expansion coefficients are "type-stable", in that they share a common base class with the original expression. In particular, this applies to "zero" coefficients:: >>> expr = KetSymbol("Psi", hs=0) >>> t = sympy.symbols("t") >>> assert expr.series_expand(t, 0, 1) == (expr, ZeroKet) """ expansion = self._series_expand(param, about, order) # _series_expand is generally not "type-stable", so we continue to # ensure the type-stability res = [] for v in expansion: if v == 0 or v.is_zero: v = self._zero elif v == 1: v = self._one assert isinstance(v, self._base_cls) res.append(v) return tuple(res)
[ "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(N+1) Args: param: Expansion parameter $x$ about (Scalar): Point $x_0$ about which to expand order: Maximum order $N$ of expansion (>= 0) Returns: tuple of length ``order + 1``, where the entries are the expansion coefficients, $(c_0, \dots, c_N)$. Note: The expansion coefficients are "type-stable", in that they share a common base class with the original expression. In particular, this applies to "zero" coefficients:: >>> expr = KetSymbol("Psi", hs=0) >>> t = sympy.symbols("t") >>> assert expr.series_expand(t, 0, 1) == (expr, ZeroKet)
[ "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 if Handler: Handler.close(self)
[ "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', 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc', 'fg', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill', 'let', 'local', 'logout', 'mapfile', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readarray', 'readonly', 'return', 'set', 'shift', 'shopt', 'source', 'suspend', 'test', 'times', 'trap', 'true', 'type', 'typeset', 'ulimit', 'umask', 'unalias', 'unset', 'wait'] toks = cmd.split() if toks and toks[0] in bash_builtins: return True return False
[ "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.cssselect('a') hrefs = [a.attrib['href'] for a in atags] # !!! This does the wrong thing for bbc.co.uk/index.html hrefs = [h if h.startswith('http') else '/'.join([url, h]) for h in hrefs ] return hrefs
[ "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. Args: packageName (str): app unique ID (usually starting with 'com.') versionCode (int): version to download offerType (int): different type of downloads (mostly unused for apks) downloadToken (str): download token returned by 'purchase' API progress_bar (bool): wether or not to print a progress bar to stdout Returns Dictionary containing apk data and optional expansion files (see *delivery*) """ if self.authSubToken is None: raise LoginError("You need to login before executing any request") if versionCode is None: # pick up latest version appDetails = self.details(packageName).get('details').get('appDetails') versionCode = appDetails.get('versionCode') headers = self.getHeaders() params = {'ot': str(offerType), 'doc': packageName, 'vc': str(versionCode)} self.log(packageName) response = requests.post(PURCHASE_URL, headers=headers, params=params, verify=ssl_verify, timeout=60, proxies=self.proxies_config) response = googleplay_pb2.ResponseWrapper.FromString(response.content) if response.commands.displayErrorMessage != "": raise RequestError(response.commands.displayErrorMessage) else: dlToken = response.payload.buyResponse.downloadToken return self.delivery(packageName, versionCode, offerType, dlToken, expansion_files=expansion_files)
[ "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.') versionCode (int): version to download offerType (int): different type of downloads (mostly unused for apks) downloadToken (str): download token returned by 'purchase' API progress_bar (bool): wether or not to print a progress bar to stdout Returns Dictionary containing apk data and optional expansion files (see *delivery*)
[ "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 to be accessed. user_id: ID for user. attributes: Dict representing user attributes. Returns: Boolean value of the variable. None if: - Feature key is invalid. - Variable key is invalid. - Mismatch with type of variable. """ variable_type = entities.Variable.Type.BOOLEAN return self._get_feature_variable_for_type(feature_key, variable_key, variable_type, user_id, attributes)
[ "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: Boolean value of the variable. None if: - Feature key is invalid. - Variable key is invalid. - Mismatch with type of variable.
[ "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 with the number 9 and has a range of 70-88 in the fourth and fifth digit. Effective April 12, 2011, the range was extended to include 900-70-0000 through 999-88-9999, 900-90-0000 through 999-92-9999 and 900-94-0000 through 999-99-9999. https://www.irs.gov/individuals/international-taxpayers/general-itin-information """ area = self.random_int(min=900, max=999) serial = self.random_int(min=0, max=9999) # The group number must be between 70 and 99 inclusively but not 89 or 93 group = random.choice([x for x in range(70, 100) if x not in [89, 93]]) itin = "{0:03d}-{1:02d}-{2:04d}".format(area, group, serial) return itin
[ "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 range of 70-88 in the fourth and fifth digit. Effective April 12, 2011, the range was extended to include 900-70-0000 through 999-88-9999, 900-90-0000 through 999-92-9999 and 900-94-0000 through 999-99-9999. https://www.irs.gov/individuals/international-taxpayers/general-itin-information
[ "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 [lang_to_form[language_code] for language_code in get_language_code_list()]
[ "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 pat = re.compile('\["(.+)"\]') keys = pat.findall(crypto_tag.text) if len(keys) > 0: unhashed_key = keys[-1].encode().decode('unicode_escape') return _generate_sha(unhashed_key) else: return _default_key
[ "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 sentence length tokens_to_keep : NDArray mask matrix ensure_tree : whether to ensure tree structure of output (apply MST) Returns ------- parse_preds : np.ndarray prediction of arc parsing with size of (seq_len,) """ if ensure_tree: I = np.eye(len(tokens_to_keep)) # block loops and pad heads parse_probs = parse_probs * tokens_to_keep * (1 - I) parse_preds = np.argmax(parse_probs, axis=1) tokens = np.arange(1, length) roots = np.where(parse_preds[tokens] == 0)[0] + 1 # ensure at least one root if len(roots) < 1: # The current root probabilities root_probs = parse_probs[tokens, 0] # The current head probabilities old_head_probs = parse_probs[tokens, parse_preds[tokens]] # Get new potential root probabilities new_root_probs = root_probs / old_head_probs # Select the most probable root new_root = tokens[np.argmax(new_root_probs)] # Make the change parse_preds[new_root] = 0 # ensure at most one root elif len(roots) > 1: # The probabilities of the current heads root_probs = parse_probs[roots, 0] # Set the probability of depending on the root zero parse_probs[roots, 0] = 0 # Get new potential heads and their probabilities new_heads = np.argmax(parse_probs[roots][:, tokens], axis=1) + 1 new_head_probs = parse_probs[roots, new_heads] / root_probs # Select the most probable root new_root = roots[np.argmin(new_head_probs)] # Make the change parse_preds[roots] = new_heads parse_preds[new_root] = 0 # remove cycles tarjan = Tarjan(parse_preds, tokens) for SCC in tarjan.SCCs: if len(SCC) > 1: dependents = set() to_visit = set(SCC) while len(to_visit) > 0: node = to_visit.pop() if not node in dependents: dependents.add(node) to_visit.update(tarjan.edges[node]) # The indices of the nodes that participate in the cycle cycle = np.array(list(SCC)) # The probabilities of the current heads old_heads = parse_preds[cycle] old_head_probs = parse_probs[cycle, old_heads] # Set the probability of depending on a non-head to zero non_heads = np.array(list(dependents)) parse_probs[np.repeat(cycle, len(non_heads)), np.repeat([non_heads], len(cycle), axis=0).flatten()] = 0 # Get new potential heads and their probabilities new_heads = np.argmax(parse_probs[cycle][:, tokens], axis=1) + 1 new_head_probs = parse_probs[cycle, new_heads] / old_head_probs # Select the most probable change change = np.argmax(new_head_probs) changed_cycle = cycle[change] old_head = old_heads[change] new_head = new_heads[change] # Make the change parse_preds[changed_cycle] = new_head tarjan.edges[new_head].add(changed_cycle) tarjan.edges[old_head].remove(changed_cycle) return parse_preds else: # block and pad heads parse_probs = parse_probs * tokens_to_keep parse_preds = np.argmax(parse_probs, axis=1) return parse_preds
[ "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 : whether to ensure tree structure of output (apply MST) Returns ------- parse_preds : np.ndarray prediction of arc parsing with size of (seq_len,)
[ "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 that if recursive dependencies are not installed, this test may return a false-negative. ''' # checking dependencies recursively isn't entirely straightforward, so # use the existing method to resolve them all before checking: dependencies = self.getDependenciesRecursive( target = target, test = test_dependencies ) return (name in dependencies)
[ "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-negative.
[ "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 kernels. num_masks: number of masks and hence the number of CDNA transformations. color_channels: the number of color channels in the images. dna_kernel_size: dna kernel size. relu_shift: shift for ReLU function. Returns: List of images transformed by the predicted CDNA kernels. """ batch_size = tf.shape(cdna_input)[0] height = int(prev_image.get_shape()[1]) width = int(prev_image.get_shape()[2]) # Predict kernels using linear function of last hidden layer. cdna_kerns = tfl.dense( cdna_input, dna_kernel_size * dna_kernel_size * num_masks, name="cdna_params", activation=None) # Reshape and normalize. cdna_kerns = tf.reshape( cdna_kerns, [batch_size, dna_kernel_size, dna_kernel_size, 1, num_masks]) cdna_kerns = (tf.nn.relu(cdna_kerns - relu_shift) + relu_shift) norm_factor = tf.reduce_sum(cdna_kerns, [1, 2, 3], keep_dims=True) cdna_kerns /= norm_factor # Treat the color channel dimension as the batch dimension since the same # transformation is applied to each color channel. # Treat the batch dimension as the channel dimension so that # depthwise_conv2d can apply a different transformation to each sample. cdna_kerns = tf.transpose(cdna_kerns, [1, 2, 0, 4, 3]) cdna_kerns = tf.reshape( cdna_kerns, [dna_kernel_size, dna_kernel_size, batch_size, num_masks]) # Swap the batch and channel dimensions. prev_image = tf.transpose(prev_image, [3, 1, 2, 0]) # Transform image. transformed = tf.nn.depthwise_conv2d( prev_image, cdna_kerns, [1, 1, 1, 1], "SAME") # Transpose the dimensions to where they belong. transformed = tf.reshape( transformed, [color_channels, height, width, batch_size, num_masks]) transformed = tf.transpose(transformed, [3, 1, 2, 0, 4]) transformed = tf.unstack(transformed, axis=-1) return transformed
[ "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 the images. dna_kernel_size: dna kernel size. relu_shift: shift for ReLU function. Returns: List of images transformed by the predicted CDNA kernels.
[ "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) self._set_tk_config("highlightbackground", utils.convert_color(color))
[ "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: int The number of ``spacer`` characters to indent structures in the Mapfile spacer: string The character to use for indenting structures in the Mapfile. Typically spaces or tab characters (``\\t``) quote: string The quote character to use in the Mapfile (double or single quotes) newlinechar: string The character used to insert newlines in the Mapfile end_comment: bool Add a comment with the block type at each closing END statement e.g. END # MAP Example ------- To open a Mapfile from a string, and then dump it back out to an open file, using 2 spaces for indentation, and single-quotes for properties:: s = '''MAP NAME "TEST" END''' d = mappyfile.loads(s) with open(fn, "w") as f: mappyfile.dump(d, f, indent=2, quote="'") """ map_string = _pprint(d, indent, spacer, quote, newlinechar, end_comment) fp.write(map_string)
[ "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: string The character to use for indenting structures in the Mapfile. Typically spaces or tab characters (``\\t``) quote: string The quote character to use in the Mapfile (double or single quotes) newlinechar: string The character used to insert newlines in the Mapfile end_comment: bool Add a comment with the block type at each closing END statement e.g. END # MAP Example ------- To open a Mapfile from a string, and then dump it back out to an open file, using 2 spaces for indentation, and single-quotes for properties:: s = '''MAP NAME "TEST" END''' d = mappyfile.loads(s) with open(fn, "w") as f: mappyfile.dump(d, f, indent=2, quote="'")
[ "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``, the result is ``-π + atan(y, x)``. Geometrically, ``atan2(y, x)`` is the angle (measured counterclockwise, in radians) from the positive x-axis to the line segment joining (0, 0) to (x, y), in the usual representation of the x-y plane. Special values are handled as described in the ISO C99 and IEEE 754-2008 standards for the atan2 function. The following examples illustrate the rules for positive y; for negative y, apply the symmetry ``atan(-y, x) == -atan(y, x)``. >>> finite = positive = 2.3 >>> negative = -2.3 >>> inf = BigFloat('inf') >>> print(atan2(+0.0, -0.0)) # pi 3.1415926535897931 >>> print(atan2(+0.0, +0.0)) # 0 0 >>> print(atan2(+0.0, negative)) # pi 3.1415926535897931 >>> print(atan2(+0.0, positive)) # 0 0 >>> print(atan2(positive, 0.0)) # pi / 2 1.5707963267948966 >>> print(atan2(inf, -inf)) # 3*pi / 4 2.3561944901923448 >>> print(atan2(inf, inf)) # pi / 4 0.78539816339744828 >>> print(atan2(inf, finite)) # pi / 2 1.5707963267948966 >>> print(atan2(positive, -inf)) # pi 3.1415926535897931 >>> print(atan2(positive, +inf)) # 0 0 """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_atan2, ( BigFloat._implicit_convert(y), BigFloat._implicit_convert(x), ), context, )
[ "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)``. Geometrically, ``atan2(y, x)`` is the angle (measured counterclockwise, in radians) from the positive x-axis to the line segment joining (0, 0) to (x, y), in the usual representation of the x-y plane. Special values are handled as described in the ISO C99 and IEEE 754-2008 standards for the atan2 function. The following examples illustrate the rules for positive y; for negative y, apply the symmetry ``atan(-y, x) == -atan(y, x)``. >>> finite = positive = 2.3 >>> negative = -2.3 >>> inf = BigFloat('inf') >>> print(atan2(+0.0, -0.0)) # pi 3.1415926535897931 >>> print(atan2(+0.0, +0.0)) # 0 0 >>> print(atan2(+0.0, negative)) # pi 3.1415926535897931 >>> print(atan2(+0.0, positive)) # 0 0 >>> print(atan2(positive, 0.0)) # pi / 2 1.5707963267948966 >>> print(atan2(inf, -inf)) # 3*pi / 4 2.3561944901923448 >>> print(atan2(inf, inf)) # pi / 4 0.78539816339744828 >>> print(atan2(inf, finite)) # pi / 2 1.5707963267948966 >>> print(atan2(positive, -inf)) # pi 3.1415926535897931 >>> print(atan2(positive, +inf)) # 0 0
[ "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:: withdrawal(asset="SWTH", amount=1.1, private_key=kp)) The expected return result for this function is the same as the execute_withdrawal function:: { 'event_type': 'withdrawal', 'amount': -100000, 'asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'status': 'confirming', 'id': '96e5f797-435b-40ab-9085-4e95c6749218', 'blockchain': 'neo', 'reason_code': 9, 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'transaction_hash': None, 'created_at': '2018-08-05T10:03:58.885Z', 'updated_at': '2018-08-05T10:03:59.828Z', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82' } :param asset: Script Hash of asset ID from the available products. :type asset: str :param amount: The amount of coins/tokens to be withdrawn. :type amount: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary with the status of the withdrawal request and blockchain details. """ create_withdrawal = self.create_withdrawal(asset=asset, amount=amount, private_key=private_key) return self.execute_withdrawal(withdrawal_params=create_withdrawal, private_key=private_key)
[ "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 expected return result for this function is the same as the execute_withdrawal function:: { 'event_type': 'withdrawal', 'amount': -100000, 'asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132', 'status': 'confirming', 'id': '96e5f797-435b-40ab-9085-4e95c6749218', 'blockchain': 'neo', 'reason_code': 9, 'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59', 'transaction_hash': None, 'created_at': '2018-08-05T10:03:58.885Z', 'updated_at': '2018-08-05T10:03:59.828Z', 'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82' } :param asset: Script Hash of asset ID from the available products. :type asset: str :param amount: The amount of coins/tokens to be withdrawn. :type amount: float :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary with the status of the withdrawal request and blockchain details.
[ "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(config_spec) return 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.mean(neg_loss) + (1. - LOSS_BIAS) * K.mean(pos_loss)
[ "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