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
zooniverse/panoptes-python-client
panoptes_client/exportable.py
https://github.com/zooniverse/panoptes-python-client/blob/138d93cb03378501a8d349428e381ad73f928680/panoptes_client/exportable.py#L30-L92
def get_export( self, export_type, generate=False, wait=False, wait_timeout=None, ): """ Downloads a data export over HTTP. Returns a `Requests Response <http://docs.python-requests.org/en/master/api/#requests.Response>`_ object containing the content of the export. - **export_type** is a string specifying which type of export should be downloaded. - **generate** is a boolean specifying whether to generate a new export and wait for it to be ready, or to just download the latest export. - **wait** is a boolean specifying whether to wait for an in-progress export to finish, if there is one. Has no effect if ``generate`` is ``True``. - **wait_timeout** is the number of seconds to wait if ``wait`` is ``True``. Has no effect if ``wait`` is ``False`` or if ``generate`` is ``True``. The returned :py:class:`.Response` object has two additional attributes as a convenience for working with the CSV content; **csv_reader** and **csv_dictreader**, which are wrappers for :py:meth:`.csv.reader` and :py:class:`csv.DictReader` respectively. These wrappers take care of correctly decoding the export content for the CSV parser. Example:: classification_export = Project(1234).get_export('classifications') for row in classification_export.csv_reader(): print(row) classification_export = Project(1234).get_export('classifications') for row in classification_export.csv_dictreader(): print(row) """ if generate: self.generate_export(export_type) if generate or wait: export = self.wait_export(export_type, wait_timeout) else: export = self.describe_export(export_type) if export_type in TALK_EXPORT_TYPES: media_url = export['data_requests'][0]['url'] else: media_url = export['media'][0]['src'] response = requests.get(media_url, stream=True) response.csv_reader = functools.partial( csv.reader, response.iter_lines(decode_unicode=True), ) response.csv_dictreader = functools.partial( csv.DictReader, response.iter_lines(decode_unicode=True), ) return response
[ "def", "get_export", "(", "self", ",", "export_type", ",", "generate", "=", "False", ",", "wait", "=", "False", ",", "wait_timeout", "=", "None", ",", ")", ":", "if", "generate", ":", "self", ".", "generate_export", "(", "export_type", ")", "if", "genera...
Downloads a data export over HTTP. Returns a `Requests Response <http://docs.python-requests.org/en/master/api/#requests.Response>`_ object containing the content of the export. - **export_type** is a string specifying which type of export should be downloaded. - **generate** is a boolean specifying whether to generate a new export and wait for it to be ready, or to just download the latest export. - **wait** is a boolean specifying whether to wait for an in-progress export to finish, if there is one. Has no effect if ``generate`` is ``True``. - **wait_timeout** is the number of seconds to wait if ``wait`` is ``True``. Has no effect if ``wait`` is ``False`` or if ``generate`` is ``True``. The returned :py:class:`.Response` object has two additional attributes as a convenience for working with the CSV content; **csv_reader** and **csv_dictreader**, which are wrappers for :py:meth:`.csv.reader` and :py:class:`csv.DictReader` respectively. These wrappers take care of correctly decoding the export content for the CSV parser. Example:: classification_export = Project(1234).get_export('classifications') for row in classification_export.csv_reader(): print(row) classification_export = Project(1234).get_export('classifications') for row in classification_export.csv_dictreader(): print(row)
[ "Downloads", "a", "data", "export", "over", "HTTP", ".", "Returns", "a", "Requests", "Response", "<http", ":", "//", "docs", ".", "python", "-", "requests", ".", "org", "/", "en", "/", "master", "/", "api", "/", "#requests", ".", "Response", ">", "_", ...
python
train
sorgerlab/indra
indra/databases/chebi_client.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chebi_client.py#L86-L106
def get_chebi_name_from_id(chebi_id, offline=False): """Return a ChEBI name corresponding to the given ChEBI ID. Parameters ---------- chebi_id : str The ChEBI ID whose name is to be returned. offline : Optional[bool] Choose whether to allow an online lookup if the local lookup fails. If True, the online lookup is not attempted. Default: False. Returns ------- chebi_name : str The name corresponding to the given ChEBI ID. If the lookup fails, None is returned. """ chebi_name = chebi_id_to_name.get(chebi_id) if chebi_name is None and not offline: chebi_name = get_chebi_name_from_id_web(chebi_id) return chebi_name
[ "def", "get_chebi_name_from_id", "(", "chebi_id", ",", "offline", "=", "False", ")", ":", "chebi_name", "=", "chebi_id_to_name", ".", "get", "(", "chebi_id", ")", "if", "chebi_name", "is", "None", "and", "not", "offline", ":", "chebi_name", "=", "get_chebi_nam...
Return a ChEBI name corresponding to the given ChEBI ID. Parameters ---------- chebi_id : str The ChEBI ID whose name is to be returned. offline : Optional[bool] Choose whether to allow an online lookup if the local lookup fails. If True, the online lookup is not attempted. Default: False. Returns ------- chebi_name : str The name corresponding to the given ChEBI ID. If the lookup fails, None is returned.
[ "Return", "a", "ChEBI", "name", "corresponding", "to", "the", "given", "ChEBI", "ID", "." ]
python
train
bachiraoun/pyrep
Repository.py
https://github.com/bachiraoun/pyrep/blob/0449bf2fad3e3e8dda855d4686a8869efeefd433/Repository.py#L836-L862
def is_repository(self, path): """ Check if there is a Repository in path. :Parameters: #. path (string): The real path of the directory where to check if there is a repository. :Returns: #. result (boolean): Whether it's a repository or not. """ if path.strip() in ('','.'): path = os.getcwd() repoPath = os.path.realpath( os.path.expanduser(path) ) if os.path.isfile( os.path.join(repoPath,self.__repoFile) ): return True else: try: from .OldRepository import Repository REP = Repository() result = REP.is_repository(repoPath) except: return False else: if result: warnings.warn("This is an old repository version 2.x.y! Make sure to start using repositories 3.x.y ") return result
[ "def", "is_repository", "(", "self", ",", "path", ")", ":", "if", "path", ".", "strip", "(", ")", "in", "(", "''", ",", "'.'", ")", ":", "path", "=", "os", ".", "getcwd", "(", ")", "repoPath", "=", "os", ".", "path", ".", "realpath", "(", "os",...
Check if there is a Repository in path. :Parameters: #. path (string): The real path of the directory where to check if there is a repository. :Returns: #. result (boolean): Whether it's a repository or not.
[ "Check", "if", "there", "is", "a", "Repository", "in", "path", "." ]
python
valid
rbarrois/mpdlcd
mpdlcd/display_fields.py
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/display_fields.py#L104-L112
def hook_changed(self, hook_name, widget, new_data): """Handle a hook upate.""" if hook_name == 'song': self.song_changed(widget, new_data) elif hook_name == 'state': self.state_changed(widget, new_data) elif hook_name == 'elapsed_and_total': elapsed, total = new_data self.time_changed(widget, elapsed, total)
[ "def", "hook_changed", "(", "self", ",", "hook_name", ",", "widget", ",", "new_data", ")", ":", "if", "hook_name", "==", "'song'", ":", "self", ".", "song_changed", "(", "widget", ",", "new_data", ")", "elif", "hook_name", "==", "'state'", ":", "self", "...
Handle a hook upate.
[ "Handle", "a", "hook", "upate", "." ]
python
train
iotile/coretools
iotilecore/iotile/core/hw/transport/adapterstream.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L351-L379
def enable_streaming(self): """Open the streaming interface and accumute reports in a queue. This method is safe to call multiple times in a single device connection. There is no way to check if the streaming interface is opened or to close it once it is opened (apart from disconnecting from the device). The first time this method is called, it will open the streaming interface and return a queue that will be filled asynchronously with reports as they are received. Subsequent calls will just empty the queue and return the same queue without interacting with the device at all. Returns: queue.Queue: A queue that will be filled with reports from the device. """ if not self.connected: raise HardwareError("Cannot enable streaming if we are not in a connected state") if self._reports is not None: _clear_queue(self._reports) return self._reports self._reports = queue.Queue() self._loop.run_coroutine(self.adapter.open_interface(0, 'streaming')) return self._reports
[ "def", "enable_streaming", "(", "self", ")", ":", "if", "not", "self", ".", "connected", ":", "raise", "HardwareError", "(", "\"Cannot enable streaming if we are not in a connected state\"", ")", "if", "self", ".", "_reports", "is", "not", "None", ":", "_clear_queue...
Open the streaming interface and accumute reports in a queue. This method is safe to call multiple times in a single device connection. There is no way to check if the streaming interface is opened or to close it once it is opened (apart from disconnecting from the device). The first time this method is called, it will open the streaming interface and return a queue that will be filled asynchronously with reports as they are received. Subsequent calls will just empty the queue and return the same queue without interacting with the device at all. Returns: queue.Queue: A queue that will be filled with reports from the device.
[ "Open", "the", "streaming", "interface", "and", "accumute", "reports", "in", "a", "queue", "." ]
python
train
cronofy/pycronofy
pycronofy/client.py
https://github.com/cronofy/pycronofy/blob/3d807603029478fa9387a9dfb6c3acd9faa4f08e/pycronofy/client.py#L128-L153
def elevated_permissions(self, permissions, redirect_uri=None): """Requests elevated permissions for a set of calendars. :param tuple permissions - calendar permission dicts set each dict must contain values for both `calendar_id` and `permission_level` :param string redirect_uri - A uri to redirect the end user back to after they have either granted or rejected the request for elevated permission. In the case of normal accounts: After making this call the end user will have to grant the extended permissions to their calendar via rhe url returned from the response. In the case of service accounts: After making this call the exteneded permissions will be granted provided the relevant scope has been granted to the account :return: a extended permissions response. :rtype: ``dict`` """ body = {'permissions': permissions} if redirect_uri: body['redirect_uri'] = redirect_uri return self.request_handler.post('permissions', data=body).json()['permissions_request']
[ "def", "elevated_permissions", "(", "self", ",", "permissions", ",", "redirect_uri", "=", "None", ")", ":", "body", "=", "{", "'permissions'", ":", "permissions", "}", "if", "redirect_uri", ":", "body", "[", "'redirect_uri'", "]", "=", "redirect_uri", "return"...
Requests elevated permissions for a set of calendars. :param tuple permissions - calendar permission dicts set each dict must contain values for both `calendar_id` and `permission_level` :param string redirect_uri - A uri to redirect the end user back to after they have either granted or rejected the request for elevated permission. In the case of normal accounts: After making this call the end user will have to grant the extended permissions to their calendar via rhe url returned from the response. In the case of service accounts: After making this call the exteneded permissions will be granted provided the relevant scope has been granted to the account :return: a extended permissions response. :rtype: ``dict``
[ "Requests", "elevated", "permissions", "for", "a", "set", "of", "calendars", "." ]
python
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/objecteditor.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/objecteditor.py#L51-L103
def create_dialog(obj, obj_name): """Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt suggested this indirection here so that he can monkey patch oedit to show eMZed related data) """ # Local import from spyder_kernels.utils.nsview import (ndarray, FakeObject, Image, is_known_type, DataFrame, Series) from spyder.plugins.variableexplorer.widgets.texteditor import TextEditor from spyder.plugins.variableexplorer.widgets.collectionseditor import ( CollectionsEditor) from spyder.plugins.variableexplorer.widgets.arrayeditor import ( ArrayEditor) if DataFrame is not FakeObject: from spyder.plugins.variableexplorer.widgets.dataframeeditor import ( DataFrameEditor) conv_func = lambda data: data readonly = not is_known_type(obj) if isinstance(obj, ndarray) and ndarray is not FakeObject: dialog = ArrayEditor() if not dialog.setup_and_check(obj, title=obj_name, readonly=readonly): return elif isinstance(obj, Image) and Image is not FakeObject \ and ndarray is not FakeObject: dialog = ArrayEditor() import numpy as np data = np.array(obj) if not dialog.setup_and_check(data, title=obj_name, readonly=readonly): return from spyder.pil_patch import Image conv_func = lambda data: Image.fromarray(data, mode=obj.mode) elif isinstance(obj, (DataFrame, Series)) and DataFrame is not FakeObject: dialog = DataFrameEditor() if not dialog.setup_and_check(obj): return elif is_text_string(obj): dialog = TextEditor(obj, title=obj_name, readonly=readonly) else: dialog = CollectionsEditor() dialog.setup(obj, title=obj_name, readonly=readonly) def end_func(dialog): return conv_func(dialog.get_value()) return dialog, end_func
[ "def", "create_dialog", "(", "obj", ",", "obj_name", ")", ":", "# Local import\r", "from", "spyder_kernels", ".", "utils", ".", "nsview", "import", "(", "ndarray", ",", "FakeObject", ",", "Image", ",", "is_known_type", ",", "DataFrame", ",", "Series", ")", "...
Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt suggested this indirection here so that he can monkey patch oedit to show eMZed related data)
[ "Creates", "the", "editor", "dialog", "and", "returns", "a", "tuple", "(", "dialog", "func", ")", "where", "func", "is", "the", "function", "to", "be", "called", "with", "the", "dialog", "instance", "as", "argument", "after", "quitting", "the", "dialog", "...
python
train
awslabs/aws-sam-cli
samcli/local/lambdafn/env_vars.py
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/env_vars.py#L175-L204
def _stringify_value(self, value): """ This method stringifies values of environment variables. If the value of the method is a list or dictionary, then this method will replace it with empty string. Values of environment variables in Lambda must be a string. List or dictionary usually means they are intrinsic functions which have not been resolved. :param value: Value to stringify :return string: Stringified value """ # List/dict/None values are replaced with a blank if isinstance(value, (dict, list, tuple)) or value is None: result = self._BLANK_VALUE # str(True) will output "True". To maintain backwards compatibility we need to output "true" or "false" elif value is True: result = "true" elif value is False: result = "false" # value is a scalar type like int, str which can be stringified # do not stringify unicode in Py2, Py3 str supports unicode elif sys.version_info.major > 2: result = str(value) elif not isinstance(value, unicode): # noqa: F821 pylint: disable=undefined-variable result = str(value) else: result = value return result
[ "def", "_stringify_value", "(", "self", ",", "value", ")", ":", "# List/dict/None values are replaced with a blank", "if", "isinstance", "(", "value", ",", "(", "dict", ",", "list", ",", "tuple", ")", ")", "or", "value", "is", "None", ":", "result", "=", "se...
This method stringifies values of environment variables. If the value of the method is a list or dictionary, then this method will replace it with empty string. Values of environment variables in Lambda must be a string. List or dictionary usually means they are intrinsic functions which have not been resolved. :param value: Value to stringify :return string: Stringified value
[ "This", "method", "stringifies", "values", "of", "environment", "variables", ".", "If", "the", "value", "of", "the", "method", "is", "a", "list", "or", "dictionary", "then", "this", "method", "will", "replace", "it", "with", "empty", "string", ".", "Values",...
python
train
michal-stuglik/django-blastplus
blastplus/forms.py
https://github.com/michal-stuglik/django-blastplus/blob/4f5e15fb9f8069c3bed5f8fd941c4b9891daad4b/blastplus/forms.py#L113-L135
def validate_word_size(word_size, BLAST_SETS): """Validate word size in blast/tblastn form. """ blast_min_int_word_size = BLAST_SETS.min_word_size blast_max_int_word_size = BLAST_SETS.max_word_size blast_word_size_error = BLAST_SETS.get_word_size_error() try: if len(word_size) <= 0: raise forms.ValidationError(blast_word_size_error) int_word_size = int(word_size) if int_word_size < blast_min_int_word_size: raise forms.ValidationError(blast_word_size_error) if int_word_size >= blast_max_int_word_size: raise forms.ValidationError(blast_word_size_error) except: raise forms.ValidationError(blast_word_size_error) return int_word_size
[ "def", "validate_word_size", "(", "word_size", ",", "BLAST_SETS", ")", ":", "blast_min_int_word_size", "=", "BLAST_SETS", ".", "min_word_size", "blast_max_int_word_size", "=", "BLAST_SETS", ".", "max_word_size", "blast_word_size_error", "=", "BLAST_SETS", ".", "get_word_s...
Validate word size in blast/tblastn form.
[ "Validate", "word", "size", "in", "blast", "/", "tblastn", "form", "." ]
python
train
vicalloy/lbutils
lbutils/forms.py
https://github.com/vicalloy/lbutils/blob/66ae7e73bc939f073cdc1b91602a95e67caf4ba6/lbutils/forms.py#L74-L78
def add_class2fields(self, html_class, fields=[], exclude=[], include_all_if_empty=True): """ add class to html widgets. """ self.add_attr2fields('class', html_class, fields, exclude)
[ "def", "add_class2fields", "(", "self", ",", "html_class", ",", "fields", "=", "[", "]", ",", "exclude", "=", "[", "]", ",", "include_all_if_empty", "=", "True", ")", ":", "self", ".", "add_attr2fields", "(", "'class'", ",", "html_class", ",", "fields", ...
add class to html widgets.
[ "add", "class", "to", "html", "widgets", "." ]
python
train
dwavesystems/dwavebinarycsp
dwavebinarycsp/compilers/stitcher.py
https://github.com/dwavesystems/dwavebinarycsp/blob/d6b1e70ceaa8f451d7afaa87ea10c7fc948a64e2/dwavebinarycsp/compilers/stitcher.py#L275-L311
def iter_complete_graphs(start, stop, factory=None): """Iterate over complete graphs. Args: start (int/iterable): Define the size of the starting graph. If an int, the nodes will be index-labeled, otherwise should be an iterable of node labels. stop (int): Stops yielding graphs when the size equals stop. factory (iterator, optional): If provided, nodes added will be labeled according to the values returned by factory. Otherwise the extra nodes will be index-labeled. Yields: :class:`nx.Graph` """ _, nodes = start nodes = list(nodes) # we'll be appending if factory is None: factory = count() while len(nodes) < stop: # we need to construct a new graph each time, this is actually faster than copy and add # the new edges in any case G = nx.complete_graph(nodes) yield G v = next(factory) while v in G: v = next(factory) nodes.append(v)
[ "def", "iter_complete_graphs", "(", "start", ",", "stop", ",", "factory", "=", "None", ")", ":", "_", ",", "nodes", "=", "start", "nodes", "=", "list", "(", "nodes", ")", "# we'll be appending", "if", "factory", "is", "None", ":", "factory", "=", "count"...
Iterate over complete graphs. Args: start (int/iterable): Define the size of the starting graph. If an int, the nodes will be index-labeled, otherwise should be an iterable of node labels. stop (int): Stops yielding graphs when the size equals stop. factory (iterator, optional): If provided, nodes added will be labeled according to the values returned by factory. Otherwise the extra nodes will be index-labeled. Yields: :class:`nx.Graph`
[ "Iterate", "over", "complete", "graphs", "." ]
python
valid
kivy/buildozer
buildozer/targets/android.py
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/targets/android.py#L457-L470
def _android_update_sdk(self, *sdkmanager_commands): """Update the tools and package-tools if possible""" auto_accept_license = self.buildozer.config.getbooldefault( 'app', 'android.accept_sdk_license', False) if auto_accept_license: # `SIGPIPE` is not being reported somehow, but `EPIPE` is. # This leads to a stderr "Broken pipe" message which is harmless, # but doesn't look good on terminal, hence redirecting to /dev/null yes_command = 'yes 2>/dev/null' command = '{} | {} --licenses'.format( yes_command, self.sdkmanager_path) self.buildozer.cmd(command, cwd=self.android_sdk_dir) self._sdkmanager(*sdkmanager_commands)
[ "def", "_android_update_sdk", "(", "self", ",", "*", "sdkmanager_commands", ")", ":", "auto_accept_license", "=", "self", ".", "buildozer", ".", "config", ".", "getbooldefault", "(", "'app'", ",", "'android.accept_sdk_license'", ",", "False", ")", "if", "auto_acce...
Update the tools and package-tools if possible
[ "Update", "the", "tools", "and", "package", "-", "tools", "if", "possible" ]
python
train
OSSOS/MOP
src/ossos/core/ossos/planning/ObsStatus.py
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/ObsStatus.py#L22-L74
def query_for_observations(mjd, observable, runid_list): """Do a QUERY on the TAP service for all observations that are part of runid, where taken after mjd and have calibration 'observable'. Schema is at: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/tables mjd : float observable: str ( 2 or 1 ) runid: tuple eg. ('13AP05', '13AP06') """ data = {"QUERY": ("SELECT Observation.target_name as TargetName, " "COORD1(CENTROID(Plane.position_bounds)) AS RA," "COORD2(CENTROID(Plane.position_bounds)) AS DEC, " "Plane.time_bounds_lower AS StartDate, " "Plane.time_exposure AS ExposureTime, " "Observation.instrument_name AS Instrument, " "Plane.energy_bandpassName AS Filter, " "Observation.observationID AS dataset_name, " "Observation.proposal_id AS ProposalID, " "Observation.proposal_pi AS PI " "FROM caom2.Observation AS Observation " "JOIN caom2.Plane AS Plane ON " "Observation.obsID = Plane.obsID " "WHERE ( Observation.collection = 'CFHT' ) " "AND Plane.time_bounds_lower > %d " "AND Plane.calibrationLevel=%s " "AND Observation.proposal_id IN %s ") % (mjd, observable, str(runid_list)), "REQUEST": "doQuery", "LANG": "ADQL", "FORMAT": "votable"} result = requests.get(storage.TAP_WEB_SERVICE, params=data, verify=False) assert isinstance(result, requests.Response) logging.debug("Doing TAP Query using url: %s" % (str(result.url))) temp_file = tempfile.NamedTemporaryFile() with open(temp_file.name, 'w') as outfile: outfile.write(result.text) try: vot = parse(temp_file.name).get_first_table() except Exception as ex: logging.error(str(ex)) logging.error(result.text) raise ex vot.array.sort(order='StartDate') t = vot.array temp_file.close() logging.debug("Got {} lines from tap query".format(len(t))) return t
[ "def", "query_for_observations", "(", "mjd", ",", "observable", ",", "runid_list", ")", ":", "data", "=", "{", "\"QUERY\"", ":", "(", "\"SELECT Observation.target_name as TargetName, \"", "\"COORD1(CENTROID(Plane.position_bounds)) AS RA,\"", "\"COORD2(CENTROID(Plane.position_boun...
Do a QUERY on the TAP service for all observations that are part of runid, where taken after mjd and have calibration 'observable'. Schema is at: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/tables mjd : float observable: str ( 2 or 1 ) runid: tuple eg. ('13AP05', '13AP06')
[ "Do", "a", "QUERY", "on", "the", "TAP", "service", "for", "all", "observations", "that", "are", "part", "of", "runid", "where", "taken", "after", "mjd", "and", "have", "calibration", "observable", "." ]
python
train
secdev/scapy
scapy/plist.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/plist.py#L163-L167
def filter(self, func): """Returns a packet list filtered by a truth function. This truth function has to take a packet as the only argument and return a boolean value.""" # noqa: E501 return self.__class__([x for x in self.res if func(x)], name="filtered %s" % self.listname)
[ "def", "filter", "(", "self", ",", "func", ")", ":", "# noqa: E501", "return", "self", ".", "__class__", "(", "[", "x", "for", "x", "in", "self", ".", "res", "if", "func", "(", "x", ")", "]", ",", "name", "=", "\"filtered %s\"", "%", "self", ".", ...
Returns a packet list filtered by a truth function. This truth function has to take a packet as the only argument and return a boolean value.
[ "Returns", "a", "packet", "list", "filtered", "by", "a", "truth", "function", ".", "This", "truth", "function", "has", "to", "take", "a", "packet", "as", "the", "only", "argument", "and", "return", "a", "boolean", "value", "." ]
python
train
mikeboers/PyMemoize
memoize/core.py
https://github.com/mikeboers/PyMemoize/blob/b10f0d8937e519353a980b41c4a1243d7049133a/memoize/core.py#L141-L150
def expire_at(self, key, expiry, **opts): """Set the explicit unix expiry time of a key.""" key, store = self._expand_opts(key, opts) data = store.get(key) if data is not None: data = list(data) data[EXPIRY_INDEX] = expiry store[key] = tuple(data) else: raise KeyError(key)
[ "def", "expire_at", "(", "self", ",", "key", ",", "expiry", ",", "*", "*", "opts", ")", ":", "key", ",", "store", "=", "self", ".", "_expand_opts", "(", "key", ",", "opts", ")", "data", "=", "store", ".", "get", "(", "key", ")", "if", "data", "...
Set the explicit unix expiry time of a key.
[ "Set", "the", "explicit", "unix", "expiry", "time", "of", "a", "key", "." ]
python
train
pydata/xarray
xarray/core/common.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/common.py#L793-L877
def where(self, cond, other=dtypes.NA, drop: bool = False): """Filter elements from this object according to a condition. This operation follows the normal broadcasting and alignment rules that xarray uses for binary arithmetic. Parameters ---------- cond : DataArray or Dataset with boolean dtype Locations at which to preserve this object's values. other : scalar, DataArray or Dataset, optional Value to use for locations in this object where ``cond`` is False. By default, these locations filled with NA. drop : boolean, optional If True, coordinate labels that only correspond to False values of the condition are dropped from the result. Mutually exclusive with ``other``. Returns ------- Same type as caller. Examples -------- >>> import numpy as np >>> a = xr.DataArray(np.arange(25).reshape(5, 5), dims=('x', 'y')) >>> a.where(a.x + a.y < 4) <xarray.DataArray (x: 5, y: 5)> array([[ 0., 1., 2., 3., nan], [ 5., 6., 7., nan, nan], [ 10., 11., nan, nan, nan], [ 15., nan, nan, nan, nan], [ nan, nan, nan, nan, nan]]) Dimensions without coordinates: x, y >>> a.where(a.x + a.y < 5, -1) <xarray.DataArray (x: 5, y: 5)> array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, -1], [10, 11, 12, -1, -1], [15, 16, -1, -1, -1], [20, -1, -1, -1, -1]]) Dimensions without coordinates: x, y >>> a.where(a.x + a.y < 4, drop=True) <xarray.DataArray (x: 4, y: 4)> array([[ 0., 1., 2., 3.], [ 5., 6., 7., nan], [ 10., 11., nan, nan], [ 15., nan, nan, nan]]) Dimensions without coordinates: x, y See also -------- numpy.where : corresponding numpy function where : equivalent function """ from .alignment import align from .dataarray import DataArray from .dataset import Dataset if drop: if other is not dtypes.NA: raise ValueError('cannot set `other` if drop=True') if not isinstance(cond, (Dataset, DataArray)): raise TypeError("cond argument is %r but must be a %r or %r" % (cond, Dataset, DataArray)) # align so we can use integer indexing self, cond = align(self, cond) # get cond with the minimal size needed for the Dataset if isinstance(cond, Dataset): clipcond = cond.to_array().any('variable') else: clipcond = cond # clip the data corresponding to coordinate dims that are not used nonzeros = zip(clipcond.dims, np.nonzero(clipcond.values)) indexers = {k: np.unique(v) for k, v in nonzeros} self = self.isel(**indexers) cond = cond.isel(**indexers) return ops.where_method(self, cond, other)
[ "def", "where", "(", "self", ",", "cond", ",", "other", "=", "dtypes", ".", "NA", ",", "drop", ":", "bool", "=", "False", ")", ":", "from", ".", "alignment", "import", "align", "from", ".", "dataarray", "import", "DataArray", "from", ".", "dataset", ...
Filter elements from this object according to a condition. This operation follows the normal broadcasting and alignment rules that xarray uses for binary arithmetic. Parameters ---------- cond : DataArray or Dataset with boolean dtype Locations at which to preserve this object's values. other : scalar, DataArray or Dataset, optional Value to use for locations in this object where ``cond`` is False. By default, these locations filled with NA. drop : boolean, optional If True, coordinate labels that only correspond to False values of the condition are dropped from the result. Mutually exclusive with ``other``. Returns ------- Same type as caller. Examples -------- >>> import numpy as np >>> a = xr.DataArray(np.arange(25).reshape(5, 5), dims=('x', 'y')) >>> a.where(a.x + a.y < 4) <xarray.DataArray (x: 5, y: 5)> array([[ 0., 1., 2., 3., nan], [ 5., 6., 7., nan, nan], [ 10., 11., nan, nan, nan], [ 15., nan, nan, nan, nan], [ nan, nan, nan, nan, nan]]) Dimensions without coordinates: x, y >>> a.where(a.x + a.y < 5, -1) <xarray.DataArray (x: 5, y: 5)> array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, -1], [10, 11, 12, -1, -1], [15, 16, -1, -1, -1], [20, -1, -1, -1, -1]]) Dimensions without coordinates: x, y >>> a.where(a.x + a.y < 4, drop=True) <xarray.DataArray (x: 4, y: 4)> array([[ 0., 1., 2., 3.], [ 5., 6., 7., nan], [ 10., 11., nan, nan], [ 15., nan, nan, nan]]) Dimensions without coordinates: x, y See also -------- numpy.where : corresponding numpy function where : equivalent function
[ "Filter", "elements", "from", "this", "object", "according", "to", "a", "condition", "." ]
python
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/__init__.py#L355-L383
def _call_linker_cb(env, callback, args, result = None): """Returns the result of env['LINKCALLBACKS'][callback](*args) if env['LINKCALLBACKS'] is a dictionary and env['LINKCALLBACKS'][callback] is callable. If these conditions are not met, return the value provided as the *result* argument. This function is mainly used for generating library info such as versioned suffixes, symlink maps, sonames etc. by delegating the core job to callbacks configured by current linker tool""" Verbose = False if Verbose: print('_call_linker_cb: args=%r' % args) print('_call_linker_cb: callback=%r' % callback) try: cbfun = env['LINKCALLBACKS'][callback] except (KeyError, TypeError): if Verbose: print('_call_linker_cb: env["LINKCALLBACKS"][%r] not found or can not be used' % callback) pass else: if Verbose: print('_call_linker_cb: env["LINKCALLBACKS"][%r] found' % callback) print('_call_linker_cb: env["LINKCALLBACKS"][%r]=%r' % (callback, cbfun)) if(isinstance(cbfun, collections.Callable)): if Verbose: print('_call_linker_cb: env["LINKCALLBACKS"][%r] is callable' % callback) result = cbfun(env, *args) return result
[ "def", "_call_linker_cb", "(", "env", ",", "callback", ",", "args", ",", "result", "=", "None", ")", ":", "Verbose", "=", "False", "if", "Verbose", ":", "print", "(", "'_call_linker_cb: args=%r'", "%", "args", ")", "print", "(", "'_call_linker_cb: callback=%r'...
Returns the result of env['LINKCALLBACKS'][callback](*args) if env['LINKCALLBACKS'] is a dictionary and env['LINKCALLBACKS'][callback] is callable. If these conditions are not met, return the value provided as the *result* argument. This function is mainly used for generating library info such as versioned suffixes, symlink maps, sonames etc. by delegating the core job to callbacks configured by current linker tool
[ "Returns", "the", "result", "of", "env", "[", "LINKCALLBACKS", "]", "[", "callback", "]", "(", "*", "args", ")", "if", "env", "[", "LINKCALLBACKS", "]", "is", "a", "dictionary", "and", "env", "[", "LINKCALLBACKS", "]", "[", "callback", "]", "is", "call...
python
train
codelv/enaml-native
src/enamlnative/ios/uikit_button.py
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/ios/uikit_button.py#L56-L61
def create_widget(self): """ Create the toolkit widget for the proxy object. """ d = self.declaration button_type = UIButton.UIButtonTypeSystem if d.flat else UIButton.UIButtonTypeRoundedRect self.widget = UIButton(buttonWithType=button_type)
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "button_type", "=", "UIButton", ".", "UIButtonTypeSystem", "if", "d", ".", "flat", "else", "UIButton", ".", "UIButtonTypeRoundedRect", "self", ".", "widget", "=", "UIButton", ...
Create the toolkit widget for the proxy object.
[ "Create", "the", "toolkit", "widget", "for", "the", "proxy", "object", "." ]
python
train
pymc-devs/pymc
pymc/Model.py
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L304-L347
def stats(self, variables=None, alpha=0.05, start=0, batches=100, chain=None, quantiles=(2.5, 25, 50, 75, 97.5)): """ Statistical output for variables. :Parameters: variables : iterable List or array of variables for which statistics are to be generated. If it is not specified, all the tallied variables are summarized. alpha : float The alpha level for generating posterior intervals. Defaults to 0.05. start : int The starting index from which to summarize (each) chain. Defaults to zero. batches : int Batch size for calculating standard deviation for non-independent samples. Defaults to 100. chain : int The index for which chain to summarize. Defaults to None (all chains). """ # If no names provided, run them all if variables is None: variables = self._variables_to_tally else: variables = [v for v in self.variables if v.__name__ in variables] stat_dict = {} # Loop over nodes for variable in variables: # Plot object stat_dict[variable.__name__] = self.trace( variable.__name__).stats(alpha=alpha, start=start, batches=batches, chain=chain, quantiles=quantiles) return stat_dict
[ "def", "stats", "(", "self", ",", "variables", "=", "None", ",", "alpha", "=", "0.05", ",", "start", "=", "0", ",", "batches", "=", "100", ",", "chain", "=", "None", ",", "quantiles", "=", "(", "2.5", ",", "25", ",", "50", ",", "75", ",", "97.5...
Statistical output for variables. :Parameters: variables : iterable List or array of variables for which statistics are to be generated. If it is not specified, all the tallied variables are summarized. alpha : float The alpha level for generating posterior intervals. Defaults to 0.05. start : int The starting index from which to summarize (each) chain. Defaults to zero. batches : int Batch size for calculating standard deviation for non-independent samples. Defaults to 100. chain : int The index for which chain to summarize. Defaults to None (all chains).
[ "Statistical", "output", "for", "variables", "." ]
python
train
wbond/asn1crypto
asn1crypto/util.py
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/util.py#L578-L619
def replace(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): """ Returns a new datetime.datetime or asn1crypto.util.extended_datetime object with the specified components replaced :return: A datetime.datetime or asn1crypto.util.extended_datetime object """ if year is None: year = self.year if month is None: month = self.month if day is None: day = self.day if hour is None: hour = self.hour if minute is None: minute = self.minute if second is None: second = self.second if microsecond is None: microsecond = self.microsecond if tzinfo is None: tzinfo = self.tzinfo if year > 0: cls = datetime else: cls = extended_datetime return cls( year, month, day, hour, minute, second, microsecond, tzinfo )
[ "def", "replace", "(", "self", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "hour", "=", "None", ",", "minute", "=", "None", ",", "second", "=", "None", ",", "microsecond", "=", "None", ",", "tzinfo", "=", "N...
Returns a new datetime.datetime or asn1crypto.util.extended_datetime object with the specified components replaced :return: A datetime.datetime or asn1crypto.util.extended_datetime object
[ "Returns", "a", "new", "datetime", ".", "datetime", "or", "asn1crypto", ".", "util", ".", "extended_datetime", "object", "with", "the", "specified", "components", "replaced" ]
python
train
aws/aws-dynamodb-encryption-python
src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py
https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/jce_bridge/primitives.py#L368-L392
def encrypt(self, key, data, mode, padding): # this can be disabled by _disable_encryption, so pylint: disable=method-hidden """Encrypt data using the supplied values. :param bytes key: Loaded encryption key :param bytes data: Data to encrypt :param JavaMode mode: Encryption mode to use :param JavaPadding padding: Padding mode to use :returns: IV prepended to encrypted data :rtype: bytes """ try: block_size = self.cipher.block_size iv_len = block_size // 8 iv = os.urandom(iv_len) encryptor = Cipher(self.cipher(key), mode.build(iv), backend=default_backend()).encryptor() padder = padding.build(block_size).padder() padded_data = padder.update(data) + padder.finalize() return iv + encryptor.update(padded_data) + encryptor.finalize() except Exception: error_message = "Encryption failed" _LOGGER.exception(error_message) raise EncryptionError(error_message)
[ "def", "encrypt", "(", "self", ",", "key", ",", "data", ",", "mode", ",", "padding", ")", ":", "# this can be disabled by _disable_encryption, so pylint: disable=method-hidden", "try", ":", "block_size", "=", "self", ".", "cipher", ".", "block_size", "iv_len", "=", ...
Encrypt data using the supplied values. :param bytes key: Loaded encryption key :param bytes data: Data to encrypt :param JavaMode mode: Encryption mode to use :param JavaPadding padding: Padding mode to use :returns: IV prepended to encrypted data :rtype: bytes
[ "Encrypt", "data", "using", "the", "supplied", "values", "." ]
python
train
ConsenSys/mythril-classic
mythril/laser/smt/expression.py
https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/laser/smt/expression.py#L41-L43
def simplify(self) -> None: """Simplify this expression.""" self.raw = cast(T, z3.simplify(self.raw))
[ "def", "simplify", "(", "self", ")", "->", "None", ":", "self", ".", "raw", "=", "cast", "(", "T", ",", "z3", ".", "simplify", "(", "self", ".", "raw", ")", ")" ]
Simplify this expression.
[ "Simplify", "this", "expression", "." ]
python
train
steinitzu/giveme
giveme/core.py
https://github.com/steinitzu/giveme/blob/b250995c59eb7e141d2cd8260e292c417785bbd1/giveme/core.py#L111-L176
def inject(function=None, **overridden_names): """ :deprecated: 1.0.0 Use :class:`giveme.injector.Injector` instead. Inject dependencies into given function's arguments. By default the injector looks for keyword arguments matching registered dependency names. Example: @register def db_connection(): return create_db_connection() @inject def save_thing(thing, db_connection=None): db_connection.store(thing) Arbitrary arguments may also be mapped to specific dependency names by passing them to the decorator as ``arg='dependency_name'`` Example: @inject(db='db_connection') def save_thing(thing, db=None): # `db_connection` injected as `db` Args: function (callable): The function that accepts a dependency. Implicitly passed when used as a decorator. **overridden_names: Mappings of `function` arguments to dependency names in the form of ``function_argument='dependency name'`` """ warnings.warn( ( 'Module level `inject` decorator has been deprecated and will ' 'be removed in a future release. ' 'Use the Injector class instead' ), DeprecationWarning ) def decorator(function): @wraps(function) def wrapper(*args, **kwargs): signature = inspect.signature(function) params = signature.parameters if not params: return function(*args, **kwargs) for name, param in params.items(): if param.kind not in (param.KEYWORD_ONLY, param.POSITIONAL_OR_KEYWORD): continue if name in kwargs: # Manual override, ignore it continue try: resolved_name = overridden_names.get(name, name) kwargs[name] = manager.get_value(resolved_name) except KeyError: pass return function(*args, **kwargs) return wrapper if function: return decorator(function) else: return decorator
[ "def", "inject", "(", "function", "=", "None", ",", "*", "*", "overridden_names", ")", ":", "warnings", ".", "warn", "(", "(", "'Module level `inject` decorator has been deprecated and will '", "'be removed in a future release. '", "'Use the Injector class instead'", ")", "...
:deprecated: 1.0.0 Use :class:`giveme.injector.Injector` instead. Inject dependencies into given function's arguments. By default the injector looks for keyword arguments matching registered dependency names. Example: @register def db_connection(): return create_db_connection() @inject def save_thing(thing, db_connection=None): db_connection.store(thing) Arbitrary arguments may also be mapped to specific dependency names by passing them to the decorator as ``arg='dependency_name'`` Example: @inject(db='db_connection') def save_thing(thing, db=None): # `db_connection` injected as `db` Args: function (callable): The function that accepts a dependency. Implicitly passed when used as a decorator. **overridden_names: Mappings of `function` arguments to dependency names in the form of ``function_argument='dependency name'``
[ ":", "deprecated", ":", "1", ".", "0", ".", "0", "Use", ":", "class", ":", "giveme", ".", "injector", ".", "Injector", "instead", "." ]
python
train
chaoss/grimoirelab-perceval
perceval/backends/core/git.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/git.py#L330-L342
def _pre_init(self): """Initialize repositories directory path""" if self.parsed_args.git_log: git_path = self.parsed_args.git_log elif not self.parsed_args.git_path: base_path = os.path.expanduser('~/.perceval/repositories/') processed_uri = self.parsed_args.uri.lstrip('/') git_path = os.path.join(base_path, processed_uri) + '-git' else: git_path = self.parsed_args.git_path setattr(self.parsed_args, 'gitpath', git_path)
[ "def", "_pre_init", "(", "self", ")", ":", "if", "self", ".", "parsed_args", ".", "git_log", ":", "git_path", "=", "self", ".", "parsed_args", ".", "git_log", "elif", "not", "self", ".", "parsed_args", ".", "git_path", ":", "base_path", "=", "os", ".", ...
Initialize repositories directory path
[ "Initialize", "repositories", "directory", "path" ]
python
test
raghakot/keras-vis
docs/md_autogen.py
https://github.com/raghakot/keras-vis/blob/668b0e11dab93f3487f23c17e07f40554a8939e9/docs/md_autogen.py#L116-L136
def get_src_path(self, obj, append_base=True): """Creates a src path string with line info for use as markdown link. """ path = getsourcefile(obj) if self.src_root not in path: # this can happen with e.g. # inlinefunc-wrapped functions if hasattr(obj, "__module__"): path = "%s.%s" % (obj.__module__, obj.__name__) else: path = obj.__name__ path = path.replace(".", "/") pre, post = path.rsplit(self.src_root + "/", 1) lineno = self.get_line_no(obj) lineno = "" if lineno is None else "#L{}".format(lineno) path = self.src_root + "/" + post + lineno if append_base: path = os.path.join(self.github_link, path) return path
[ "def", "get_src_path", "(", "self", ",", "obj", ",", "append_base", "=", "True", ")", ":", "path", "=", "getsourcefile", "(", "obj", ")", "if", "self", ".", "src_root", "not", "in", "path", ":", "# this can happen with e.g.", "# inlinefunc-wrapped functions", ...
Creates a src path string with line info for use as markdown link.
[ "Creates", "a", "src", "path", "string", "with", "line", "info", "for", "use", "as", "markdown", "link", "." ]
python
train
Microsoft/knack
knack/commands.py
https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/commands.py#L200-L218
def load_arguments(self, command): """ Load the arguments for the specified command :param command: The command to load arguments for :type command: str """ from knack.arguments import ArgumentsContext self.cli_ctx.raise_event(EVENT_CMDLOADER_LOAD_ARGUMENTS, cmd_tbl=self.command_table, command=command) try: self.command_table[command].load_arguments() except KeyError: return # ensure global 'cmd' is ignored with ArgumentsContext(self, '') as c: c.ignore('cmd') self._apply_parameter_info(command, self.command_table[command])
[ "def", "load_arguments", "(", "self", ",", "command", ")", ":", "from", "knack", ".", "arguments", "import", "ArgumentsContext", "self", ".", "cli_ctx", ".", "raise_event", "(", "EVENT_CMDLOADER_LOAD_ARGUMENTS", ",", "cmd_tbl", "=", "self", ".", "command_table", ...
Load the arguments for the specified command :param command: The command to load arguments for :type command: str
[ "Load", "the", "arguments", "for", "the", "specified", "command" ]
python
train
brunato/lograptor
lograptor/report.py
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/report.py#L495-L509
def make_format(self, fmt, width): """ Make subreport text in a specified format """ if not self.report_data: return for data_item in self.report_data: if data_item.results: if fmt is None or fmt == 'text': data_item.make_text(width) elif fmt == 'html': data_item.make_html() elif fmt == 'csv': data_item.make_csv()
[ "def", "make_format", "(", "self", ",", "fmt", ",", "width", ")", ":", "if", "not", "self", ".", "report_data", ":", "return", "for", "data_item", "in", "self", ".", "report_data", ":", "if", "data_item", ".", "results", ":", "if", "fmt", "is", "None",...
Make subreport text in a specified format
[ "Make", "subreport", "text", "in", "a", "specified", "format" ]
python
train
pvlib/pvlib-python
pvlib/pvsystem.py
https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/pvsystem.py#L2832-L2873
def pvwatts_dc(g_poa_effective, temp_cell, pdc0, gamma_pdc, temp_ref=25.): r""" Implements NREL's PVWatts DC power model [1]_: .. math:: P_{dc} = \frac{G_{poa eff}}{1000} P_{dc0} ( 1 + \gamma_{pdc} (T_{cell} - T_{ref})) Parameters ---------- g_poa_effective: numeric Irradiance transmitted to the PV cells in units of W/m**2. To be fully consistent with PVWatts, the user must have already applied angle of incidence losses, but not soiling, spectral, etc. temp_cell: numeric Cell temperature in degrees C. pdc0: numeric Nameplate DC rating. gamma_pdc: numeric The temperature coefficient in units of 1/C. Typically -0.002 to -0.005 per degree C. temp_ref: numeric, default 25.0 Cell reference temperature. PVWatts defines it to be 25 C and is included here for flexibility. Returns ------- pdc: numeric DC power. References ---------- .. [1] A. P. Dobos, "PVWatts Version 5 Manual" http://pvwatts.nrel.gov/downloads/pvwattsv5.pdf (2014). """ pdc = (g_poa_effective * 0.001 * pdc0 * (1 + gamma_pdc * (temp_cell - temp_ref))) return pdc
[ "def", "pvwatts_dc", "(", "g_poa_effective", ",", "temp_cell", ",", "pdc0", ",", "gamma_pdc", ",", "temp_ref", "=", "25.", ")", ":", "pdc", "=", "(", "g_poa_effective", "*", "0.001", "*", "pdc0", "*", "(", "1", "+", "gamma_pdc", "*", "(", "temp_cell", ...
r""" Implements NREL's PVWatts DC power model [1]_: .. math:: P_{dc} = \frac{G_{poa eff}}{1000} P_{dc0} ( 1 + \gamma_{pdc} (T_{cell} - T_{ref})) Parameters ---------- g_poa_effective: numeric Irradiance transmitted to the PV cells in units of W/m**2. To be fully consistent with PVWatts, the user must have already applied angle of incidence losses, but not soiling, spectral, etc. temp_cell: numeric Cell temperature in degrees C. pdc0: numeric Nameplate DC rating. gamma_pdc: numeric The temperature coefficient in units of 1/C. Typically -0.002 to -0.005 per degree C. temp_ref: numeric, default 25.0 Cell reference temperature. PVWatts defines it to be 25 C and is included here for flexibility. Returns ------- pdc: numeric DC power. References ---------- .. [1] A. P. Dobos, "PVWatts Version 5 Manual" http://pvwatts.nrel.gov/downloads/pvwattsv5.pdf (2014).
[ "r", "Implements", "NREL", "s", "PVWatts", "DC", "power", "model", "[", "1", "]", "_", ":" ]
python
train
saltstack/salt
salt/modules/parted_partition.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/parted_partition.py#L700-L725
def toggle(device, partition, flag): ''' Toggle the state of <flag> on <partition>. Valid flags are the same as the set command. CLI Example: .. code-block:: bash salt '*' partition.toggle /dev/sda 1 boot ''' _validate_device(device) try: int(partition) except Exception: raise CommandExecutionError( 'Invalid partition number passed to partition.toggle' ) if flag not in VALID_PARTITION_FLAGS: raise CommandExecutionError('Invalid flag passed to partition.toggle') cmd = 'parted -m -s {0} toggle {1} {2}'.format(device, partition, flag) out = __salt__['cmd.run'](cmd).splitlines() return out
[ "def", "toggle", "(", "device", ",", "partition", ",", "flag", ")", ":", "_validate_device", "(", "device", ")", "try", ":", "int", "(", "partition", ")", "except", "Exception", ":", "raise", "CommandExecutionError", "(", "'Invalid partition number passed to parti...
Toggle the state of <flag> on <partition>. Valid flags are the same as the set command. CLI Example: .. code-block:: bash salt '*' partition.toggle /dev/sda 1 boot
[ "Toggle", "the", "state", "of", "<flag", ">", "on", "<partition", ">", ".", "Valid", "flags", "are", "the", "same", "as", "the", "set", "command", "." ]
python
train
pantsbuild/pants
src/python/pants/base/exception_sink.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/base/exception_sink.py#L40-L49
def signal_handler_mapping(self): """A dict mapping (signal number) -> (a method handling the signal).""" # Could use an enum here, but we never end up doing any matching on the specific signal value, # instead just iterating over the registered signals to set handlers, so a dict is probably # better. return { signal.SIGINT: self.handle_sigint, signal.SIGQUIT: self.handle_sigquit, signal.SIGTERM: self.handle_sigterm, }
[ "def", "signal_handler_mapping", "(", "self", ")", ":", "# Could use an enum here, but we never end up doing any matching on the specific signal value,", "# instead just iterating over the registered signals to set handlers, so a dict is probably", "# better.", "return", "{", "signal", ".", ...
A dict mapping (signal number) -> (a method handling the signal).
[ "A", "dict", "mapping", "(", "signal", "number", ")", "-", ">", "(", "a", "method", "handling", "the", "signal", ")", "." ]
python
train
opereto/pyopereto
pyopereto/client.py
https://github.com/opereto/pyopereto/blob/16ca987738a7e1b82b52b0b099794a74ed557223/pyopereto/client.py#L1197-L1222
def search_process_log(self, pid, filter={}, start=0, limit=1000): ''' search_process_log(self, pid, filter={}, start=0, limit=1000) Search in process logs :Parameters: * *pid* (`string`) -- Identifier of an existing process * *start* (`int`) -- start index to retrieve from. Default is 0 * *limit* (`int`) -- maximum number of entities to retrieve. Default is 100 * *filter* (`object`) -- free text search pattern (checks in process log data) :return: Count of records found and list of search results or empty list :Example: .. code-block:: python filter = {'generic': 'my product param'} search_result = opereto_client.search_globals(filter=filter) if search_result['total'] > 0 print(search_result['list']) ''' pid = self._get_pid(pid) request_data = {'start': start, 'limit': limit, 'filter': filter} return self._call_rest_api('post', '/processes/' + pid + '/log/search', data=request_data, error='Failed to search in process log')
[ "def", "search_process_log", "(", "self", ",", "pid", ",", "filter", "=", "{", "}", ",", "start", "=", "0", ",", "limit", "=", "1000", ")", ":", "pid", "=", "self", ".", "_get_pid", "(", "pid", ")", "request_data", "=", "{", "'start'", ":", "start"...
search_process_log(self, pid, filter={}, start=0, limit=1000) Search in process logs :Parameters: * *pid* (`string`) -- Identifier of an existing process * *start* (`int`) -- start index to retrieve from. Default is 0 * *limit* (`int`) -- maximum number of entities to retrieve. Default is 100 * *filter* (`object`) -- free text search pattern (checks in process log data) :return: Count of records found and list of search results or empty list :Example: .. code-block:: python filter = {'generic': 'my product param'} search_result = opereto_client.search_globals(filter=filter) if search_result['total'] > 0 print(search_result['list'])
[ "search_process_log", "(", "self", "pid", "filter", "=", "{}", "start", "=", "0", "limit", "=", "1000", ")" ]
python
train
zeromake/aiko
aiko/response.py
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/response.py#L261-L312
def handel_default(self) -> None: """ 处理设置到body上的数据默认 headers """ raw_body = self._body body = cast(Optional[bytes], None) default_type = 2 charset = self._charset or self._default_charset if raw_body is None: pass elif isinstance(raw_body, bytes): # body为bytes default_type = 2 body = raw_body elif isinstance(raw_body, str): # body 为字符串 default_type = 2 body = encode_str(raw_body, charset) elif isinstance(raw_body, (list, dict)): # body 为json default_type = 3 body = encode_str(json.dumps(raw_body, ensure_ascii=False), charset) elif isinstance(raw_body, RawIOBase): # body 为文件 default_type = 1 body = raw_body.read() raw_body.close() if "Content-Length" not in self._headers and \ "Transfer-Encoding" not in self._headers \ or self._headers["Transfer-Encoding"] != "chunked": if self.length is None: if body is not None: self.length = len(body) else: self.length = 0 # 设置默认 Content-Length self.set("Content-Length", str(self.length)) # print(body[0], body[1]) if body is not None and body.startswith(encode_str("<", charset)): default_type = 4 if "Content-Type" not in self._headers.keys(): type_str = self.type if type_str is None: temp = DEFAULT_TYPE.get(default_type) if temp is not None: if default_type != 1: temp += "; charset=%s" % charset type_str = temp if type_str is not None: # 设置默认 Content-Type self.set("Content-Type", type_str) self._body = body
[ "def", "handel_default", "(", "self", ")", "->", "None", ":", "raw_body", "=", "self", ".", "_body", "body", "=", "cast", "(", "Optional", "[", "bytes", "]", ",", "None", ")", "default_type", "=", "2", "charset", "=", "self", ".", "_charset", "or", "...
处理设置到body上的数据默认 headers
[ "处理设置到body上的数据默认", "headers" ]
python
train
erwan-lemonnier/dynamodb-object-store
dynadbobjectstore.py
https://github.com/erwan-lemonnier/dynamodb-object-store/blob/fd0eee1912bc9c2139541a41928ee08efb4270f8/dynadbobjectstore.py#L56-L70
def put(self, key, value, overwrite=True): """Marshall the python object given as 'value' into a string, using the to_string marshalling method passed in the constructor, and store it in the DynamoDB table under key 'key'. """ self._get_table() s = self.to_string(value) log.debug("Storing in key '%s' the object: '%s'" % (key, s)) self.table.put_item( data={ 'key': key, 'value': s, }, overwrite=overwrite )
[ "def", "put", "(", "self", ",", "key", ",", "value", ",", "overwrite", "=", "True", ")", ":", "self", ".", "_get_table", "(", ")", "s", "=", "self", ".", "to_string", "(", "value", ")", "log", ".", "debug", "(", "\"Storing in key '%s' the object: '%s'\""...
Marshall the python object given as 'value' into a string, using the to_string marshalling method passed in the constructor, and store it in the DynamoDB table under key 'key'.
[ "Marshall", "the", "python", "object", "given", "as", "value", "into", "a", "string", "using", "the", "to_string", "marshalling", "method", "passed", "in", "the", "constructor", "and", "store", "it", "in", "the", "DynamoDB", "table", "under", "key", "key", "...
python
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/pool.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/pool.py#L102-L110
def _new_session(self): """Helper for concrete methods creating session instances. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: new session instance. """ if self.labels: return self._database.session(labels=self.labels) return self._database.session()
[ "def", "_new_session", "(", "self", ")", ":", "if", "self", ".", "labels", ":", "return", "self", ".", "_database", ".", "session", "(", "labels", "=", "self", ".", "labels", ")", "return", "self", ".", "_database", ".", "session", "(", ")" ]
Helper for concrete methods creating session instances. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: new session instance.
[ "Helper", "for", "concrete", "methods", "creating", "session", "instances", "." ]
python
train
reingart/pyafipws
utils.py
https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/utils.py#L863-L869
def norm(x, encoding="latin1"): "Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular" if not isinstance(x, basestring): x = unicode(x) elif isinstance(x, str): x = x.decode(encoding, 'ignore') return unicodedata.normalize('NFKD', x).encode('ASCII', 'ignore')
[ "def", "norm", "(", "x", ",", "encoding", "=", "\"latin1\"", ")", ":", "if", "not", "isinstance", "(", "x", ",", "basestring", ")", ":", "x", "=", "unicode", "(", "x", ")", "elif", "isinstance", "(", "x", ",", "str", ")", ":", "x", "=", "x", "....
Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular
[ "Convertir", "acentos", "codificados", "en", "ISO", "8859", "-", "1", "u", "otro", "a", "ASCII", "regular" ]
python
train
sirfoga/pyhal
hal/strings/models.py
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/strings/models.py#L85-L103
def strip_bad_html(self): """Strips string of all HTML elements :return: Given string with raw HTML elements removed """ out = self.string while not String(out).is_well_formatted(): out = out.replace(":", "") \ .replace("\\'", "\'") \ .replace("\\n", "") \ .replace("\\r", "") \ .replace("\\t", "") \ .replace("\n", "") \ .replace("\r", "") \ .replace("\t", "") \ .replace(" ", " ") \ .strip() return str(out)
[ "def", "strip_bad_html", "(", "self", ")", ":", "out", "=", "self", ".", "string", "while", "not", "String", "(", "out", ")", ".", "is_well_formatted", "(", ")", ":", "out", "=", "out", ".", "replace", "(", "\":\"", ",", "\"\"", ")", ".", "replace", ...
Strips string of all HTML elements :return: Given string with raw HTML elements removed
[ "Strips", "string", "of", "all", "HTML", "elements", ":", "return", ":", "Given", "string", "with", "raw", "HTML", "elements", "removed" ]
python
train
saltstack/salt
salt/modules/archive.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/archive.py#L1351-L1363
def _trim_files(files, trim_output): ''' Trim the file list for output. ''' count = 100 if not isinstance(trim_output, bool): count = trim_output if not(isinstance(trim_output, bool) and trim_output is False) and len(files) > count: files = files[:count] files.append("List trimmed after {0} files.".format(count)) return files
[ "def", "_trim_files", "(", "files", ",", "trim_output", ")", ":", "count", "=", "100", "if", "not", "isinstance", "(", "trim_output", ",", "bool", ")", ":", "count", "=", "trim_output", "if", "not", "(", "isinstance", "(", "trim_output", ",", "bool", ")"...
Trim the file list for output.
[ "Trim", "the", "file", "list", "for", "output", "." ]
python
train
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L209-L227
def send_email_confirmation_instructions(self, user): """ Sends the confirmation instructions email for the specified user. Sends signal `confirm_instructions_sent`. :param user: The user to send the instructions to. """ token = self.security_utils_service.generate_confirmation_token(user) confirmation_link = url_for('security_controller.confirm_email', token=token, _external=True) self.send_mail( _('flask_unchained.bundles.security:email_subject.email_confirmation_instructions'), to=user.email, template='security/email/email_confirmation_instructions.html', user=user, confirmation_link=confirmation_link) confirm_instructions_sent.send(app._get_current_object(), user=user, token=token)
[ "def", "send_email_confirmation_instructions", "(", "self", ",", "user", ")", ":", "token", "=", "self", ".", "security_utils_service", ".", "generate_confirmation_token", "(", "user", ")", "confirmation_link", "=", "url_for", "(", "'security_controller.confirm_email'", ...
Sends the confirmation instructions email for the specified user. Sends signal `confirm_instructions_sent`. :param user: The user to send the instructions to.
[ "Sends", "the", "confirmation", "instructions", "email", "for", "the", "specified", "user", "." ]
python
train
twilio/twilio-python
twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py#L123-L138
def get(self, sid): """ Constructs a PayloadContext :param sid: The unique string that identifies the resource to fetch :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext """ return PayloadContext( self._version, account_sid=self._solution['account_sid'], reference_sid=self._solution['reference_sid'], add_on_result_sid=self._solution['add_on_result_sid'], sid=sid, )
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "PayloadContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "reference_sid", "=", "self", ".", "_solution", "[", "'reference_s...
Constructs a PayloadContext :param sid: The unique string that identifies the resource to fetch :returns: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext :rtype: twilio.rest.api.v2010.account.recording.add_on_result.payload.PayloadContext
[ "Constructs", "a", "PayloadContext" ]
python
train
chrisspen/burlap
burlap/common.py
https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/common.py#L1671-L1683
def get_hosts_retriever(s=None): """ Given the function name, looks up the method for dynamically retrieving host data. """ s = s or env.hosts_retriever # #assert s, 'No hosts retriever specified.' if not s: return env_hosts_retriever # module_name = '.'.join(s.split('.')[:-1]) # func_name = s.split('.')[-1] # retriever = getattr(importlib.import_module(module_name), func_name) # return retriever return str_to_callable(s) or env_hosts_retriever
[ "def", "get_hosts_retriever", "(", "s", "=", "None", ")", ":", "s", "=", "s", "or", "env", ".", "hosts_retriever", "# #assert s, 'No hosts retriever specified.'", "if", "not", "s", ":", "return", "env_hosts_retriever", "# module_name = '.'.join(s.split('.')[:-1])"...
Given the function name, looks up the method for dynamically retrieving host data.
[ "Given", "the", "function", "name", "looks", "up", "the", "method", "for", "dynamically", "retrieving", "host", "data", "." ]
python
valid
troeger/opensubmit
web/opensubmit/social/env.py
https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/web/opensubmit/social/env.py#L47-L58
def get_user_details(self, response): """ Complete with additional information from environment, as available. """ result = { 'username': response[self.ENV_USERNAME], 'email': response.get(self.ENV_EMAIL, None), 'first_name': response.get(self.ENV_FIRST_NAME, None), 'last_name': response.get(self.ENV_LAST_NAME, None) } if result['first_name'] and result['last_name']: result['fullname']=result['first_name']+' '+result['last_name'] logger.debug("Returning user details: "+str(result)) return result
[ "def", "get_user_details", "(", "self", ",", "response", ")", ":", "result", "=", "{", "'username'", ":", "response", "[", "self", ".", "ENV_USERNAME", "]", ",", "'email'", ":", "response", ".", "get", "(", "self", ".", "ENV_EMAIL", ",", "None", ")", "...
Complete with additional information from environment, as available.
[ "Complete", "with", "additional", "information", "from", "environment", "as", "available", "." ]
python
train
prompt-toolkit/pymux
pymux/utils.py
https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/utils.py#L91-L106
def get_default_shell(): """ return the path to the default shell for the current user. """ if is_windows(): return 'cmd.exe' else: import pwd import getpass if 'SHELL' in os.environ: return os.environ['SHELL'] else: username = getpass.getuser() shell = pwd.getpwnam(username).pw_shell return shell
[ "def", "get_default_shell", "(", ")", ":", "if", "is_windows", "(", ")", ":", "return", "'cmd.exe'", "else", ":", "import", "pwd", "import", "getpass", "if", "'SHELL'", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "'SHELL'", "]",...
return the path to the default shell for the current user.
[ "return", "the", "path", "to", "the", "default", "shell", "for", "the", "current", "user", "." ]
python
train
apache/incubator-mxnet
example/image-classification/symbols/resnext.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/image-classification/symbols/resnext.py#L28-L99
def residual_unit(data, num_filter, stride, dim_match, name, bottle_neck=True, num_group=32, bn_mom=0.9, workspace=256, memonger=False): """Return ResNet Unit symbol for building ResNet Parameters ---------- data : str Input data num_filter : int Number of output channels bnf : int Bottle neck channels factor with regard to num_filter stride : tuple Stride used in convolution dim_match : Boolean True means channel number between input and output is the same, otherwise means differ name : str Base name of the operators workspace : int Workspace used in convolution operator """ if bottle_neck: # the same as https://github.com/facebook/fb.resnet.torch#notes, a bit difference with origin paper conv1 = mx.sym.Convolution(data=data, num_filter=int(num_filter*0.5), kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True, workspace=workspace, name=name + '_conv1') bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn1') act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1') conv2 = mx.sym.Convolution(data=act1, num_filter=int(num_filter*0.5), num_group=num_group, kernel=(3,3), stride=stride, pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv2') bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn2') act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2') conv3 = mx.sym.Convolution(data=act2, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True, workspace=workspace, name=name + '_conv3') bn3 = mx.sym.BatchNorm(data=conv3, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3') if dim_match: shortcut = data else: shortcut_conv = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True, workspace=workspace, name=name+'_sc') shortcut = mx.sym.BatchNorm(data=shortcut_conv, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_sc_bn') if memonger: shortcut._set_attr(mirror_stage='True') eltwise = bn3 + shortcut return mx.sym.Activation(data=eltwise, act_type='relu', name=name + '_relu') else: conv1 = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(3,3), stride=stride, pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv1') bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn1') act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1') conv2 = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(3,3), stride=(1,1), pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv2') bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn2') if dim_match: shortcut = data else: shortcut_conv = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True, workspace=workspace, name=name+'_sc') shortcut = mx.sym.BatchNorm(data=shortcut_conv, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_sc_bn') if memonger: shortcut._set_attr(mirror_stage='True') eltwise = bn2 + shortcut return mx.sym.Activation(data=eltwise, act_type='relu', name=name + '_relu')
[ "def", "residual_unit", "(", "data", ",", "num_filter", ",", "stride", ",", "dim_match", ",", "name", ",", "bottle_neck", "=", "True", ",", "num_group", "=", "32", ",", "bn_mom", "=", "0.9", ",", "workspace", "=", "256", ",", "memonger", "=", "False", ...
Return ResNet Unit symbol for building ResNet Parameters ---------- data : str Input data num_filter : int Number of output channels bnf : int Bottle neck channels factor with regard to num_filter stride : tuple Stride used in convolution dim_match : Boolean True means channel number between input and output is the same, otherwise means differ name : str Base name of the operators workspace : int Workspace used in convolution operator
[ "Return", "ResNet", "Unit", "symbol", "for", "building", "ResNet", "Parameters", "----------", "data", ":", "str", "Input", "data", "num_filter", ":", "int", "Number", "of", "output", "channels", "bnf", ":", "int", "Bottle", "neck", "channels", "factor", "with...
python
train
attm2x/m2x-python
m2x/v2/devices.py
https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/devices.py#L109-L119
def update_location(self, **params): """ Method for `Update Device Location <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Location>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. :return: The API response, see M2X API docs for details :rtype: dict :raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request """ return self.api.put(self.subpath('/location'), data=params)
[ "def", "update_location", "(", "self", ",", "*", "*", "params", ")", ":", "return", "self", ".", "api", ".", "put", "(", "self", ".", "subpath", "(", "'/location'", ")", ",", "data", "=", "params", ")" ]
Method for `Update Device Location <https://m2x.att.com/developer/documentation/v2/device#Update-Device-Location>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. :return: The API response, see M2X API docs for details :rtype: dict :raises: :class:`~requests.exceptions.HTTPError` if an error occurs when sending the HTTP request
[ "Method", "for", "Update", "Device", "Location", "<https", ":", "//", "m2x", ".", "att", ".", "com", "/", "developer", "/", "documentation", "/", "v2", "/", "device#Update", "-", "Device", "-", "Location", ">", "_", "endpoint", "." ]
python
test
abseil/abseil-py
absl/logging/__init__.py
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/logging/__init__.py#L445-L448
def log_if(level, msg, condition, *args): """Logs 'msg % args' at level 'level' only if condition is fulfilled.""" if condition: log(level, msg, *args)
[ "def", "log_if", "(", "level", ",", "msg", ",", "condition", ",", "*", "args", ")", ":", "if", "condition", ":", "log", "(", "level", ",", "msg", ",", "*", "args", ")" ]
Logs 'msg % args' at level 'level' only if condition is fulfilled.
[ "Logs", "msg", "%", "args", "at", "level", "level", "only", "if", "condition", "is", "fulfilled", "." ]
python
train
erikrose/nose-progressive
noseprogressive/result.py
https://github.com/erikrose/nose-progressive/blob/42853f11290cfaac8aa3d204714b71e27cc4ec07/noseprogressive/result.py#L170-L209
def printSummary(self, start, stop): """As a final summary, print number of tests, broken down by result.""" def renderResultType(type, number, is_failure): """Return a rendering like '2 failures'. :arg type: A singular label, like "failure" :arg number: The number of tests with a result of that type :arg is_failure: Whether that type counts as a failure """ # I'd rather hope for the best with plurals than totally punt on # being Englishlike: ret = '%s %s%s' % (number, type, 's' if number != 1 else '') if is_failure and number: ret = self._term.bold(ret) return ret # Summarize the special cases: counts = [('test', self.testsRun, False), ('failure', len(self.failures), True), ('error', len(self.errors), True)] # Support custom errorclasses as well as normal failures and errors. # Lowercase any all-caps labels, but leave the rest alone in case there # are hard-to-read camelCaseWordBreaks. counts.extend([(label.lower() if label.isupper() else label, len(storage), is_failure) for (storage, label, is_failure) in self.errorClasses.values() if len(storage)]) summary = (', '.join(renderResultType(*a) for a in counts) + ' in %.1fs' % (stop - start)) # Erase progress bar. Bash doesn't clear the whole line when printing # the prompt, leaving a piece of the bar. Also, the prompt may not be # at the bottom of the terminal. self.bar.erase() self.stream.writeln() if self.wasSuccessful(): self.stream.write(self._term.bold_green('OK! ')) self.stream.writeln(summary)
[ "def", "printSummary", "(", "self", ",", "start", ",", "stop", ")", ":", "def", "renderResultType", "(", "type", ",", "number", ",", "is_failure", ")", ":", "\"\"\"Return a rendering like '2 failures'.\n\n :arg type: A singular label, like \"failure\"\n ...
As a final summary, print number of tests, broken down by result.
[ "As", "a", "final", "summary", "print", "number", "of", "tests", "broken", "down", "by", "result", "." ]
python
train
NoneGG/aredis
aredis/connection.py
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/connection.py#L180-L185
def on_connect(self, connection): "Called when the stream connects" self._stream = connection._reader self._buffer = SocketBuffer(self._stream, self._read_size) if connection.decode_responses: self.encoding = connection.encoding
[ "def", "on_connect", "(", "self", ",", "connection", ")", ":", "self", ".", "_stream", "=", "connection", ".", "_reader", "self", ".", "_buffer", "=", "SocketBuffer", "(", "self", ".", "_stream", ",", "self", ".", "_read_size", ")", "if", "connection", "...
Called when the stream connects
[ "Called", "when", "the", "stream", "connects" ]
python
train
Alignak-monitoring/alignak
alignak/scheduler.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L265-L272
def all_my_hosts_and_services(self): """Create an iterator for all my known hosts and services :return: None """ for what in (self.hosts, self.services): for item in what: yield item
[ "def", "all_my_hosts_and_services", "(", "self", ")", ":", "for", "what", "in", "(", "self", ".", "hosts", ",", "self", ".", "services", ")", ":", "for", "item", "in", "what", ":", "yield", "item" ]
Create an iterator for all my known hosts and services :return: None
[ "Create", "an", "iterator", "for", "all", "my", "known", "hosts", "and", "services" ]
python
train
mitsei/dlkit
dlkit/primordium/locale/types/heading.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/primordium/locale/types/heading.py#L15-L34
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ name = name.upper() try: return { 'authority': 'okapia.net', 'namespace': 'heading', 'identifier': name, 'domain': 'Headings', 'display_name': HEADING_TYPES[name] + ' Heading Type', 'display_label': HEADING_TYPES[name], 'description': ('The heading type for the ' + HEADING_TYPES[name] + ' heading.') } except KeyError: raise NotFound('Heading Type:' + name)
[ "def", "get_type_data", "(", "name", ")", ":", "name", "=", "name", ".", "upper", "(", ")", "try", ":", "return", "{", "'authority'", ":", "'okapia.net'", ",", "'namespace'", ":", "'heading'", ",", "'identifier'", ":", "name", ",", "'domain'", ":", "'Hea...
Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type
[ "Return", "dictionary", "representation", "of", "type", "." ]
python
train
great-expectations/great_expectations
great_expectations/dataset/sqlalchemy_dataset.py
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/sqlalchemy_dataset.py#L389-L416
def expect_table_columns_to_match_ordered_list(self, column_list, result_format=None, include_config=False, catch_exceptions=None, meta=None): """ Checks if observed columns are in the expected order. The expectations will fail if columns are out of expected order, columns are missing, or additional columns are present. On failure, details are provided on the location of the unexpected column(s). """ observed_columns = [col['name'] for col in self.columns] if observed_columns == list(column_list): return { "success": True } else: # In the case of differing column lengths between the defined expectation and the observed column set, the # max is determined to generate the column_index. number_of_columns = max(len(column_list), len(observed_columns)) column_index = range(number_of_columns) # Create a list of the mismatched details compared_lists = list(zip_longest(column_index, list(column_list), observed_columns)) mismatched = [{"Expected Column Position": i, "Expected": k, "Found": v} for i, k, v in compared_lists if k != v] return { "success": False, "details": {"mismatched": mismatched} }
[ "def", "expect_table_columns_to_match_ordered_list", "(", "self", ",", "column_list", ",", "result_format", "=", "None", ",", "include_config", "=", "False", ",", "catch_exceptions", "=", "None", ",", "meta", "=", "None", ")", ":", "observed_columns", "=", "[", ...
Checks if observed columns are in the expected order. The expectations will fail if columns are out of expected order, columns are missing, or additional columns are present. On failure, details are provided on the location of the unexpected column(s).
[ "Checks", "if", "observed", "columns", "are", "in", "the", "expected", "order", ".", "The", "expectations", "will", "fail", "if", "columns", "are", "out", "of", "expected", "order", "columns", "are", "missing", "or", "additional", "columns", "are", "present", ...
python
train
cackharot/suds-py3
suds/wsse.py
https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/wsse.py#L129-L146
def setnonce(self, text=None): """ Set I{nonce} which is arbitraty set of bytes to prevent reply attacks. @param text: The nonce text value. Generated when I{None}. @type text: str """ if text is None: s = [] s.append(self.username) s.append(self.password) s.append(Token.sysdate()) m = md5() m.update(':'.join(s).encode("utf-8")) self.nonce = m.hexdigest() else: self.nonce = text
[ "def", "setnonce", "(", "self", ",", "text", "=", "None", ")", ":", "if", "text", "is", "None", ":", "s", "=", "[", "]", "s", ".", "append", "(", "self", ".", "username", ")", "s", ".", "append", "(", "self", ".", "password", ")", "s", ".", "...
Set I{nonce} which is arbitraty set of bytes to prevent reply attacks. @param text: The nonce text value. Generated when I{None}. @type text: str
[ "Set", "I", "{", "nonce", "}", "which", "is", "arbitraty", "set", "of", "bytes", "to", "prevent", "reply", "attacks", "." ]
python
train
c0fec0de/anytree
anytree/search.py
https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/search.py#L6-L62
def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None): """ Search nodes matching `filter_` but stop at `maxlevel` or `stop`. Return tuple with matching nodes. Args: node: top node, start searching. Keyword Args: filter_: function called with every `node` as argument, `node` is returned if `True`. stop: stop iteration at `node` if `stop` function returns `True` for `node`. maxlevel (int): maximum decending in the node hierarchy. mincount (int): minimum number of nodes. maxcount (int): maximum number of nodes. Example tree: >>> from anytree import Node, RenderTree, AsciiStyle >>> f = Node("f") >>> b = Node("b", parent=f) >>> a = Node("a", parent=b) >>> d = Node("d", parent=b) >>> c = Node("c", parent=d) >>> e = Node("e", parent=d) >>> g = Node("g", parent=f) >>> i = Node("i", parent=g) >>> h = Node("h", parent=i) >>> print(RenderTree(f, style=AsciiStyle()).by_attr()) f |-- b | |-- a | +-- d | |-- c | +-- e +-- g +-- i +-- h >>> findall(f, filter_=lambda node: node.name in ("a", "b")) (Node('/f/b'), Node('/f/b/a')) >>> findall(f, filter_=lambda node: d in node.path) (Node('/f/b/d'), Node('/f/b/d/c'), Node('/f/b/d/e')) The number of matches can be limited: >>> findall(f, filter_=lambda node: d in node.path, mincount=4) # doctest: +ELLIPSIS Traceback (most recent call last): ... anytree.search.CountError: Expecting at least 4 elements, but found 3. ... Node('/f/b/d/e')) >>> findall(f, filter_=lambda node: d in node.path, maxcount=2) # doctest: +ELLIPSIS Traceback (most recent call last): ... anytree.search.CountError: Expecting 2 elements at maximum, but found 3. ... Node('/f/b/d/e')) """ return _findall(node, filter_=filter_, stop=stop, maxlevel=maxlevel, mincount=mincount, maxcount=maxcount)
[ "def", "findall", "(", "node", ",", "filter_", "=", "None", ",", "stop", "=", "None", ",", "maxlevel", "=", "None", ",", "mincount", "=", "None", ",", "maxcount", "=", "None", ")", ":", "return", "_findall", "(", "node", ",", "filter_", "=", "filter_...
Search nodes matching `filter_` but stop at `maxlevel` or `stop`. Return tuple with matching nodes. Args: node: top node, start searching. Keyword Args: filter_: function called with every `node` as argument, `node` is returned if `True`. stop: stop iteration at `node` if `stop` function returns `True` for `node`. maxlevel (int): maximum decending in the node hierarchy. mincount (int): minimum number of nodes. maxcount (int): maximum number of nodes. Example tree: >>> from anytree import Node, RenderTree, AsciiStyle >>> f = Node("f") >>> b = Node("b", parent=f) >>> a = Node("a", parent=b) >>> d = Node("d", parent=b) >>> c = Node("c", parent=d) >>> e = Node("e", parent=d) >>> g = Node("g", parent=f) >>> i = Node("i", parent=g) >>> h = Node("h", parent=i) >>> print(RenderTree(f, style=AsciiStyle()).by_attr()) f |-- b | |-- a | +-- d | |-- c | +-- e +-- g +-- i +-- h >>> findall(f, filter_=lambda node: node.name in ("a", "b")) (Node('/f/b'), Node('/f/b/a')) >>> findall(f, filter_=lambda node: d in node.path) (Node('/f/b/d'), Node('/f/b/d/c'), Node('/f/b/d/e')) The number of matches can be limited: >>> findall(f, filter_=lambda node: d in node.path, mincount=4) # doctest: +ELLIPSIS Traceback (most recent call last): ... anytree.search.CountError: Expecting at least 4 elements, but found 3. ... Node('/f/b/d/e')) >>> findall(f, filter_=lambda node: d in node.path, maxcount=2) # doctest: +ELLIPSIS Traceback (most recent call last): ... anytree.search.CountError: Expecting 2 elements at maximum, but found 3. ... Node('/f/b/d/e'))
[ "Search", "nodes", "matching", "filter_", "but", "stop", "at", "maxlevel", "or", "stop", "." ]
python
train
vimalkvn/riboplot
riboplot/ribocore.py
https://github.com/vimalkvn/riboplot/blob/914515df54eccc2e726ba71e751c3260f2066d97/riboplot/ribocore.py#L169-L218
def get_three_frame_orfs(sequence, starts=None, stops=None): """Find ORF's in frames 1, 2 and 3 for the given sequence. Positions returned are 1-based (not 0) Return format [{'start': start_position, 'stop': stop_position, 'sequence': sequence}, ] Keyword arguments: sequence -- sequence for the transcript starts -- List of codons to be considered as start (Default: ['ATG']) stops -- List of codons to be considered as stop (Default: ['TAG', 'TGA', 'TAA']) """ if not starts: starts = ['ATG'] if not stops: stops = ['TAG', 'TGA', 'TAA'] # Find ORFs in 3 frames orfs = [] for frame in range(3): start_codon = None orf = '' for position in range(frame, len(sequence), 3): codon = sequence[position:position + 3] if codon in starts: # We have found a start already, so add codon to orf and # continue. This is an internal MET if start_codon is not None: orf += codon continue # New orf start start_codon = position orf = codon else: # if sequence starts with ATG, start_codon will be 0 if start_codon is None: # We haven't found a start codon yet continue orf += codon if codon in stops: # orfs[start_codon + 1] = orf orfs.append({'start': start_codon + 1, 'stop': position + 3, 'sequence': orf}) # Reset start_codon = None orf = '' return orfs
[ "def", "get_three_frame_orfs", "(", "sequence", ",", "starts", "=", "None", ",", "stops", "=", "None", ")", ":", "if", "not", "starts", ":", "starts", "=", "[", "'ATG'", "]", "if", "not", "stops", ":", "stops", "=", "[", "'TAG'", ",", "'TGA'", ",", ...
Find ORF's in frames 1, 2 and 3 for the given sequence. Positions returned are 1-based (not 0) Return format [{'start': start_position, 'stop': stop_position, 'sequence': sequence}, ] Keyword arguments: sequence -- sequence for the transcript starts -- List of codons to be considered as start (Default: ['ATG']) stops -- List of codons to be considered as stop (Default: ['TAG', 'TGA', 'TAA'])
[ "Find", "ORF", "s", "in", "frames", "1", "2", "and", "3", "for", "the", "given", "sequence", "." ]
python
train
zhemao/funktown
funktown/lookuptree.py
https://github.com/zhemao/funktown/blob/8d5c5a8bdad2b85b33b4cea3febd820c2657c375/funktown/lookuptree.py#L92-L96
def remove(self, index): '''Return new tree with index removed.''' newtree = LookupTree() newtree.root = _remove_down(self.root, index, 0) return newtree
[ "def", "remove", "(", "self", ",", "index", ")", ":", "newtree", "=", "LookupTree", "(", ")", "newtree", ".", "root", "=", "_remove_down", "(", "self", ".", "root", ",", "index", ",", "0", ")", "return", "newtree" ]
Return new tree with index removed.
[ "Return", "new", "tree", "with", "index", "removed", "." ]
python
train
django-fluent/django-fluent-dashboard
fluent_dashboard/dashboard.py
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/dashboard.py#L80-L93
def get_application_modules(self): """ Instantiate all application modules (i.e. :class:`~admin_tools.dashboard.modules.AppList`, :class:`~fluent_dashboard.modules.AppIconList` and :class:`~fluent_dashboard.modules.CmsAppIconList`) for use in the dashboard. """ modules = [] appgroups = get_application_groups() for title, kwargs in appgroups: AppListClass = get_class(kwargs.pop('module')) # e.g. CmsAppIconlist, AppIconlist, Applist modules.append(AppListClass(title, **kwargs)) return modules
[ "def", "get_application_modules", "(", "self", ")", ":", "modules", "=", "[", "]", "appgroups", "=", "get_application_groups", "(", ")", "for", "title", ",", "kwargs", "in", "appgroups", ":", "AppListClass", "=", "get_class", "(", "kwargs", ".", "pop", "(", ...
Instantiate all application modules (i.e. :class:`~admin_tools.dashboard.modules.AppList`, :class:`~fluent_dashboard.modules.AppIconList` and :class:`~fluent_dashboard.modules.CmsAppIconList`) for use in the dashboard.
[ "Instantiate", "all", "application", "modules", "(", "i", ".", "e", ".", ":", "class", ":", "~admin_tools", ".", "dashboard", ".", "modules", ".", "AppList", ":", "class", ":", "~fluent_dashboard", ".", "modules", ".", "AppIconList", "and", ":", "class", "...
python
train
joyent/python-manta
manta/cmdln.py
https://github.com/joyent/python-manta/blob/f68ef142bdbac058c981e3b28e18d77612f5b7c6/manta/cmdln.py#L306-L376
def cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse into an argv, and dispatch (via .precmd(), .onecmd() and .postcmd()), passing them the argv. In other words, start a shell. "intro" (optional) is a introductory message to print when starting the command loop. This overrides the class "intro" attribute, if any. """ self.cmdlooping = True self.preloop() if self.use_rawinput and self.completekey: try: import readline self.old_completer = readline.get_completer() readline.set_completer(self.complete) if sys.platform == "darwin": readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind(self.completekey + ": complete") except ImportError: pass try: if intro is None: intro = self.intro if intro: intro_str = self._str(intro) self.stdout.write(intro_str + '\n') self.stop = False retval = None while not self.stop: if self.cmdqueue: argv = self.cmdqueue.pop(0) assert isinstance(argv, (list, tuple)), \ "item on 'cmdqueue' is not a sequence: %r" % argv else: if self.use_rawinput: try: line = input(self._str(self._prompt_str)) except EOFError: line = 'EOF' except KeyboardInterrupt: line = 'KeyboardInterrupt' else: self.stdout.write(self._str(self._prompt_str)) self.stdout.flush() line = self.stdin.readline() if not len(line): line = 'EOF' else: line = line[:-1] # chop '\n' argv = line2argv(line) try: argv = self.precmd(argv) retval = self.onecmd(argv) self.postcmd(argv) except: if not self.cmdexc(argv): raise retval = 1 self.lastretval = retval self.postloop() finally: if self.use_rawinput and self.completekey: try: import readline readline.set_completer(self.old_completer) except ImportError: pass self.cmdlooping = False return retval
[ "def", "cmdloop", "(", "self", ",", "intro", "=", "None", ")", ":", "self", ".", "cmdlooping", "=", "True", "self", ".", "preloop", "(", ")", "if", "self", ".", "use_rawinput", "and", "self", ".", "completekey", ":", "try", ":", "import", "readline", ...
Repeatedly issue a prompt, accept input, parse into an argv, and dispatch (via .precmd(), .onecmd() and .postcmd()), passing them the argv. In other words, start a shell. "intro" (optional) is a introductory message to print when starting the command loop. This overrides the class "intro" attribute, if any.
[ "Repeatedly", "issue", "a", "prompt", "accept", "input", "parse", "into", "an", "argv", "and", "dispatch", "(", "via", ".", "precmd", "()", ".", "onecmd", "()", "and", ".", "postcmd", "()", ")", "passing", "them", "the", "argv", ".", "In", "other", "wo...
python
train
architv/soccer-cli
soccer/request_handler.py
https://github.com/architv/soccer-cli/blob/472e9f492f7633a8e9739e228a6c31de454da88b/soccer/request_handler.py#L56-L75
def get_team_scores(self, team, time, show_upcoming, use_12_hour_format): """Queries the API and gets the particular team scores""" team_id = self.team_names.get(team, None) time_frame = 'n' if show_upcoming else 'p' if team_id: try: req = self._get('teams/{team_id}/matches?timeFrame={time_frame}{time}'.format( team_id=team_id, time_frame=time_frame, time=time)) team_scores = req.json() if len(team_scores["matches"]) == 0: click.secho("No action during past week. Change the time " "parameter to get more fixtures.", fg="red", bold=True) else: self.writer.team_scores(team_scores, time, show_upcoming, use_12_hour_format) except APIErrorException as e: click.secho(e.args[0], fg="red", bold=True) else: click.secho("Team code is not correct.", fg="red", bold=True)
[ "def", "get_team_scores", "(", "self", ",", "team", ",", "time", ",", "show_upcoming", ",", "use_12_hour_format", ")", ":", "team_id", "=", "self", ".", "team_names", ".", "get", "(", "team", ",", "None", ")", "time_frame", "=", "'n'", "if", "show_upcoming...
Queries the API and gets the particular team scores
[ "Queries", "the", "API", "and", "gets", "the", "particular", "team", "scores" ]
python
train
ergoithz/browsepy
browsepy/file.py
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L815-L825
def clean_restricted_chars(path, restricted_chars=restricted_chars): ''' Get path without restricted characters. :param path: path :return: path without restricted characters :rtype: str or unicode (depending on given path) ''' for character in restricted_chars: path = path.replace(character, '_') return path
[ "def", "clean_restricted_chars", "(", "path", ",", "restricted_chars", "=", "restricted_chars", ")", ":", "for", "character", "in", "restricted_chars", ":", "path", "=", "path", ".", "replace", "(", "character", ",", "'_'", ")", "return", "path" ]
Get path without restricted characters. :param path: path :return: path without restricted characters :rtype: str or unicode (depending on given path)
[ "Get", "path", "without", "restricted", "characters", "." ]
python
train
pyros-dev/pyzmp
pyzmp/coprocess.py
https://github.com/pyros-dev/pyzmp/blob/fac0b719b25996ce94a80ca2118f3eba5779d53d/pyzmp/coprocess.py#L356-L370
def shutdown(self, join=True, timeout=None): """ Clean shutdown of the node. :param join: optionally wait for the process to end (default : True) :return: None """ if self.is_alive(): # check if process started print("Shutdown initiated") self.exit.set() if join: self.join(timeout=timeout) # TODO : timeout before forcing terminate (SIGTERM) exitcode = self._process.exitcode if self._process else None # we return None if the process was never started return exitcode
[ "def", "shutdown", "(", "self", ",", "join", "=", "True", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "is_alive", "(", ")", ":", "# check if process started", "print", "(", "\"Shutdown initiated\"", ")", "self", ".", "exit", ".", "set", "("...
Clean shutdown of the node. :param join: optionally wait for the process to end (default : True) :return: None
[ "Clean", "shutdown", "of", "the", "node", ".", ":", "param", "join", ":", "optionally", "wait", "for", "the", "process", "to", "end", "(", "default", ":", "True", ")", ":", "return", ":", "None" ]
python
train
NuGrid/NuGridPy
nugridpy/data_plot.py
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/data_plot.py#L1441-L1460
def _clear(self, title=True, xlabel=True, ylabel=True): ''' Method for removing the title and/or xlabel and/or Ylabel. Parameters ---------- Title : boolean, optional Boolean of if title will be cleared. The default is True. xlabel : boolean, optional Boolean of if xlabel will be cleared. The default is True. ylabel : boolean, optional Boolean of if ylabel will be cleared. The default is True. ''' if title: pyl.title('') if xlabel: pyl.xlabel('') if ylabel: pyl.ylabel('')
[ "def", "_clear", "(", "self", ",", "title", "=", "True", ",", "xlabel", "=", "True", ",", "ylabel", "=", "True", ")", ":", "if", "title", ":", "pyl", ".", "title", "(", "''", ")", "if", "xlabel", ":", "pyl", ".", "xlabel", "(", "''", ")", "if",...
Method for removing the title and/or xlabel and/or Ylabel. Parameters ---------- Title : boolean, optional Boolean of if title will be cleared. The default is True. xlabel : boolean, optional Boolean of if xlabel will be cleared. The default is True. ylabel : boolean, optional Boolean of if ylabel will be cleared. The default is True.
[ "Method", "for", "removing", "the", "title", "and", "/", "or", "xlabel", "and", "/", "or", "Ylabel", "." ]
python
train
angr/pyvex
pyvex/lifting/util/instr_helper.py
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L268-L283
def put_conditional(self, cond, valiftrue, valiffalse, reg): """ Like put, except it checks a condition to decide what to put in the destination register. :param cond: The VexValue representing the logical expression for the condition (if your expression only has constants, don't use this method!) :param valiftrue: the VexValue to put in reg if cond evals as true :param validfalse: the VexValue to put in reg if cond evals as false :param reg: The integer register number to store into, or register name :return: None """ val = self.irsb_c.ite(cond.rdt , valiftrue.rdt, valiffalse.rdt) offset = self.lookup_register(self.irsb_c.irsb.arch, reg) self.irsb_c.put(val, offset)
[ "def", "put_conditional", "(", "self", ",", "cond", ",", "valiftrue", ",", "valiffalse", ",", "reg", ")", ":", "val", "=", "self", ".", "irsb_c", ".", "ite", "(", "cond", ".", "rdt", ",", "valiftrue", ".", "rdt", ",", "valiffalse", ".", "rdt", ")", ...
Like put, except it checks a condition to decide what to put in the destination register. :param cond: The VexValue representing the logical expression for the condition (if your expression only has constants, don't use this method!) :param valiftrue: the VexValue to put in reg if cond evals as true :param validfalse: the VexValue to put in reg if cond evals as false :param reg: The integer register number to store into, or register name :return: None
[ "Like", "put", "except", "it", "checks", "a", "condition", "to", "decide", "what", "to", "put", "in", "the", "destination", "register", "." ]
python
train
seleniumbase/SeleniumBase
seleniumbase/core/tour_helper.py
https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/core/tour_helper.py#L637-L809
def export_tour(tour_steps, name=None, filename="my_tour.js", url=None): """ Exports a tour as a JS file. It will include necessary resources as well, such as jQuery. You'll be able to copy the tour directly into the Console of any web browser to play the tour outside of SeleniumBase runs. """ if not name: name = "default" if name not in tour_steps: raise Exception("Tour {%s} does not exist!" % name) if not filename.endswith('.js'): raise Exception('Tour file must end in ".js"!') if not url: url = "data:," tour_type = None if "Bootstrap" in tour_steps[name][0]: tour_type = "bootstrap" elif "Hopscotch" in tour_steps[name][0]: tour_type = "hopscotch" elif "IntroJS" in tour_steps[name][0]: tour_type = "introjs" elif "Shepherd" in tour_steps[name][0]: tour_type = "shepherd" else: raise Exception('Unknown tour type!') instructions = ( '''//////// Load Tour Start Page (if not there now) ////////\n\n''' '''if (window.location.href != "%s") {\n''' ''' window.location.href="%s";\n''' '''}\n\n''' '''//////// Resources ////////\n\n''' '''function injectCSS(css_link) {''' '''var head = document.getElementsByTagName("head")[0];''' '''var link = document.createElement("link");''' '''link.rel = "stylesheet";''' '''link.type = "text/css";''' '''link.href = css_link;''' '''link.crossorigin = "anonymous";''' '''head.appendChild(link);''' '''};\n''' '''function injectJS(js_link) {''' '''var head = document.getElementsByTagName("head")[0];''' '''var script = document.createElement("script");''' '''script.src = js_link;''' '''script.defer;''' '''script.type="text/javascript";''' '''script.crossorigin = "anonymous";''' '''script.onload = function() { null };''' '''head.appendChild(script);''' '''};\n''' '''function injectStyle(css) {''' '''var head = document.getElementsByTagName("head")[0];''' '''var style = document.createElement("style");''' '''style.type = "text/css";''' '''style.appendChild(document.createTextNode(css));''' '''head.appendChild(style);''' '''};\n''' % (url, url)) if tour_type == "bootstrap": jquery_js = constants.JQuery.MIN_JS bootstrap_tour_css = constants.BootstrapTour.MIN_CSS bootstrap_tour_js = constants.BootstrapTour.MIN_JS backdrop_style = style_sheet.bt_backdrop_style backdrop_style = backdrop_style.replace('\n', '') backdrop_style = js_utils.escape_quotes_if_needed(backdrop_style) instructions += 'injectJS("%s");' % jquery_js instructions += '\n\n//////// Resources - Load 2 ////////\n\n' instructions += 'injectCSS("%s");\n' % bootstrap_tour_css instructions += 'injectStyle("%s");\n' % backdrop_style instructions += 'injectJS("%s");' % bootstrap_tour_js elif tour_type == "hopscotch": hopscotch_css = constants.Hopscotch.MIN_CSS hopscotch_js = constants.Hopscotch.MIN_JS backdrop_style = style_sheet.hops_backdrop_style backdrop_style = backdrop_style.replace('\n', '') backdrop_style = js_utils.escape_quotes_if_needed(backdrop_style) instructions += 'injectCSS("%s");\n' % hopscotch_css instructions += 'injectStyle("%s");\n' % backdrop_style instructions += 'injectJS("%s");' % hopscotch_js elif tour_type == "introjs": intro_css = constants.IntroJS.MIN_CSS intro_js = constants.IntroJS.MIN_JS instructions += 'injectCSS("%s");\n' % intro_css instructions += 'injectJS("%s");' % intro_js elif tour_type == "shepherd": jquery_js = constants.JQuery.MIN_JS shepherd_js = constants.Shepherd.MIN_JS sh_theme_arrows_css = constants.Shepherd.THEME_ARROWS_CSS sh_theme_arrows_fix_css = constants.Shepherd.THEME_ARR_FIX_CSS sh_theme_default_css = constants.Shepherd.THEME_DEFAULT_CSS sh_theme_dark_css = constants.Shepherd.THEME_DARK_CSS sh_theme_sq_css = constants.Shepherd.THEME_SQ_CSS sh_theme_sq_dark_css = constants.Shepherd.THEME_SQ_DK_CSS tether_js = constants.Tether.MIN_JS spinner_css = constants.Messenger.SPINNER_CSS backdrop_style = style_sheet.sh_backdrop_style backdrop_style = backdrop_style.replace('\n', '') backdrop_style = js_utils.escape_quotes_if_needed(backdrop_style) instructions += 'injectCSS("%s");\n' % spinner_css instructions += 'injectJS("%s");\n' % jquery_js instructions += 'injectJS("%s");' % tether_js instructions += '\n\n//////// Resources - Load 2 ////////\n\n' instructions += 'injectCSS("%s");' % sh_theme_arrows_css instructions += 'injectCSS("%s");' % sh_theme_arrows_fix_css instructions += 'injectCSS("%s");' % sh_theme_default_css instructions += 'injectCSS("%s");' % sh_theme_dark_css instructions += 'injectCSS("%s");' % sh_theme_sq_css instructions += 'injectCSS("%s");\n' % sh_theme_sq_dark_css instructions += 'injectStyle("%s");\n' % backdrop_style instructions += 'injectJS("%s");' % shepherd_js instructions += '\n\n//////// Tour Code ////////\n\n' for tour_step in tour_steps[name]: instructions += tour_step if tour_type == "bootstrap": instructions += ( """]); // Initialize the tour tour.init(); // Start the tour tour.start(); $tour = tour; $tour.restart();\n""") elif tour_type == "hopscotch": instructions += ( """] }; // Start the tour! hopscotch.startTour(tour); $tour = hopscotch;\n""") elif tour_type == "introjs": instructions += ( """] }); intro.setOption("disableInteraction", true); intro.setOption("overlayOpacity", .29); intro.setOption("scrollToElement", true); intro.setOption("keyboardNavigation", true); intro.setOption("exitOnEsc", false); intro.setOption("exitOnOverlayClick", false); intro.setOption("showStepNumbers", false); intro.setOption("showProgress", false); intro.start(); $tour = intro; }; startIntro();\n""") elif tour_type == "shepherd": instructions += ( """ tour.start(); $tour = tour;\n""") else: pass exported_tours_folder = EXPORTED_TOURS_FOLDER if exported_tours_folder.endswith("/"): exported_tours_folder = exported_tours_folder[:-1] if not os.path.exists(exported_tours_folder): try: os.makedirs(exported_tours_folder) except Exception: pass import codecs file_path = exported_tours_folder + "/" + filename out_file = codecs.open(file_path, "w+") out_file.writelines(instructions) out_file.close() print('\n>>> [%s] was saved!\n' % file_path)
[ "def", "export_tour", "(", "tour_steps", ",", "name", "=", "None", ",", "filename", "=", "\"my_tour.js\"", ",", "url", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "\"default\"", "if", "name", "not", "in", "tour_steps", ":", "raise", "...
Exports a tour as a JS file. It will include necessary resources as well, such as jQuery. You'll be able to copy the tour directly into the Console of any web browser to play the tour outside of SeleniumBase runs.
[ "Exports", "a", "tour", "as", "a", "JS", "file", ".", "It", "will", "include", "necessary", "resources", "as", "well", "such", "as", "jQuery", ".", "You", "ll", "be", "able", "to", "copy", "the", "tour", "directly", "into", "the", "Console", "of", "any...
python
train
pandas-dev/pandas
pandas/core/arrays/datetimelike.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/datetimelike.py#L680-L705
def value_counts(self, dropna=False): """ Return a Series containing counts of unique values. Parameters ---------- dropna : boolean, default True Don't include counts of NaT values. Returns ------- Series """ from pandas import Series, Index if dropna: values = self[~self.isna()]._data else: values = self._data cls = type(self) result = value_counts(values, sort=False, dropna=dropna) index = Index(cls(result.index.view('i8'), dtype=self.dtype), name=result.index.name) return Series(result.values, index=index, name=result.name)
[ "def", "value_counts", "(", "self", ",", "dropna", "=", "False", ")", ":", "from", "pandas", "import", "Series", ",", "Index", "if", "dropna", ":", "values", "=", "self", "[", "~", "self", ".", "isna", "(", ")", "]", ".", "_data", "else", ":", "val...
Return a Series containing counts of unique values. Parameters ---------- dropna : boolean, default True Don't include counts of NaT values. Returns ------- Series
[ "Return", "a", "Series", "containing", "counts", "of", "unique", "values", "." ]
python
train
jilljenn/tryalgo
tryalgo/interval_tree.py
https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/interval_tree.py#L49-L71
def intervals_containing(t, p): """Query the interval tree :param t: root of the interval tree :param p: value :returns: a list of intervals containing p :complexity: O(log n + m), where n is the number of intervals in t, and m the length of the returned list """ INF = float('inf') if t is None: return [] if p < t.center: retval = intervals_containing(t.left, p) j = bisect_right(t.by_low, (p, (INF, INF))) for i in range(j): retval.append(t.by_low[i][1]) else: retval = intervals_containing(t.right, p) i = bisect_right(t.by_high, (p, (INF, INF))) for j in range(i, len(t.by_high)): retval.append(t.by_high[j][1]) return retval
[ "def", "intervals_containing", "(", "t", ",", "p", ")", ":", "INF", "=", "float", "(", "'inf'", ")", "if", "t", "is", "None", ":", "return", "[", "]", "if", "p", "<", "t", ".", "center", ":", "retval", "=", "intervals_containing", "(", "t", ".", ...
Query the interval tree :param t: root of the interval tree :param p: value :returns: a list of intervals containing p :complexity: O(log n + m), where n is the number of intervals in t, and m the length of the returned list
[ "Query", "the", "interval", "tree" ]
python
train
glormph/msstitch
src/app/actions/prottable/info.py
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/prottable/info.py#L41-L45
def get_protein_data_pgrouped(proteindata, p_acc, headerfields): """Parses protein data for a certain protein into tsv output dictionary""" report = get_protein_data_base(proteindata, p_acc, headerfields) return get_cov_protnumbers(proteindata, p_acc, report)
[ "def", "get_protein_data_pgrouped", "(", "proteindata", ",", "p_acc", ",", "headerfields", ")", ":", "report", "=", "get_protein_data_base", "(", "proteindata", ",", "p_acc", ",", "headerfields", ")", "return", "get_cov_protnumbers", "(", "proteindata", ",", "p_acc"...
Parses protein data for a certain protein into tsv output dictionary
[ "Parses", "protein", "data", "for", "a", "certain", "protein", "into", "tsv", "output", "dictionary" ]
python
train
domainaware/parsedmarc
parsedmarc/kafkaclient.py
https://github.com/domainaware/parsedmarc/blob/ecc9fd434c23d896ccd1f35795ccc047f946ed05/parsedmarc/kafkaclient.py#L58-L69
def strip_metadata(report): """ Duplicates org_name, org_email and report_id into JSON root and removes report_metadata key to bring it more inline with Elastic output. """ report['org_name'] = report['report_metadata']['org_name'] report['org_email'] = report['report_metadata']['org_email'] report['report_id'] = report['report_metadata']['report_id'] report.pop('report_metadata') return report
[ "def", "strip_metadata", "(", "report", ")", ":", "report", "[", "'org_name'", "]", "=", "report", "[", "'report_metadata'", "]", "[", "'org_name'", "]", "report", "[", "'org_email'", "]", "=", "report", "[", "'report_metadata'", "]", "[", "'org_email'", "]"...
Duplicates org_name, org_email and report_id into JSON root and removes report_metadata key to bring it more inline with Elastic output.
[ "Duplicates", "org_name", "org_email", "and", "report_id", "into", "JSON", "root", "and", "removes", "report_metadata", "key", "to", "bring", "it", "more", "inline", "with", "Elastic", "output", "." ]
python
test
APSL/transmanager
transmanager/management/commands/export_text_for_translations.py
https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/management/commands/export_text_for_translations.py#L51-L60
def _get_main_language(): """ returns the main language :return: """ try: main_language = TransLanguage.objects.filter(main_language=True).get() return main_language.code except TransLanguage.DoesNotExist: return 'es'
[ "def", "_get_main_language", "(", ")", ":", "try", ":", "main_language", "=", "TransLanguage", ".", "objects", ".", "filter", "(", "main_language", "=", "True", ")", ".", "get", "(", ")", "return", "main_language", ".", "code", "except", "TransLanguage", "."...
returns the main language :return:
[ "returns", "the", "main", "language", ":", "return", ":" ]
python
train
python-odin/odinweb
odinweb/data_structures.py
https://github.com/python-odin/odinweb/blob/198424133584acc18cb41c8d18d91f803abc810f/odinweb/data_structures.py#L824-L848
def setlistdefault(self, key, default_list=None): # type: (Hashable, List[Any]) -> List[Any] """ Like `setdefault` but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list: >>> d = MultiValueDict({"foo": 1}) >>> d.setlistdefault("foo").extend([2, 3]) >>> d.getlist("foo") [1, 2, 3] :param key: The key to be looked up. :param default_list: An iterable of default values. It is either copied (in case it was a list) or converted into a list before returned. :return: a :class:`list` """ if key not in self: default_list = list(default_list or ()) dict.__setitem__(self, key, default_list) else: default_list = dict.__getitem__(self, key) return default_list
[ "def", "setlistdefault", "(", "self", ",", "key", ",", "default_list", "=", "None", ")", ":", "# type: (Hashable, List[Any]) -> List[Any]", "if", "key", "not", "in", "self", ":", "default_list", "=", "list", "(", "default_list", "or", "(", ")", ")", "dict", ...
Like `setdefault` but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list: >>> d = MultiValueDict({"foo": 1}) >>> d.setlistdefault("foo").extend([2, 3]) >>> d.getlist("foo") [1, 2, 3] :param key: The key to be looked up. :param default_list: An iterable of default values. It is either copied (in case it was a list) or converted into a list before returned. :return: a :class:`list`
[ "Like", "setdefault", "but", "sets", "multiple", "values", ".", "The", "list", "returned", "is", "not", "a", "copy", "but", "the", "list", "that", "is", "actually", "used", "internally", ".", "This", "means", "that", "you", "can", "put", "new", "values", ...
python
train
saltstack/salt
salt/utils/network.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L484-L496
def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value passed as arg is not a list, at least one of the calls above will return None # if one of them is none, means that we should return only one of them return ipv4_obj or ipv6_obj # one of them else: return ipv4_obj + ipv6_obj
[ "def", "ipaddr", "(", "value", ",", "options", "=", "None", ")", ":", "ipv4_obj", "=", "ipv4", "(", "value", ",", "options", "=", "options", ")", "ipv6_obj", "=", "ipv6", "(", "value", ",", "options", "=", "options", ")", "if", "ipv4_obj", "is", "Non...
Filters and returns only valid IP objects.
[ "Filters", "and", "returns", "only", "valid", "IP", "objects", "." ]
python
train
BD2KGenomics/toil-scripts
src/toil_scripts/gatk_germline/common.py
https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/gatk_germline/common.py#L10-L32
def output_file_job(job, filename, file_id, output_dir, s3_key_path=None): """ Uploads a file from the FileStore to an output directory on the local filesystem or S3. :param JobFunctionWrappingJob job: passed automatically by Toil :param str filename: basename for file :param str file_id: FileStoreID :param str output_dir: Amazon S3 URL or local path :param str s3_key_path: (OPTIONAL) Path to 32-byte key to be used for SSE-C encryption :return: """ job.fileStore.logToMaster('Writing {} to {}'.format(filename, output_dir)) work_dir = job.fileStore.getLocalTempDir() filepath = job.fileStore.readGlobalFile(file_id, os.path.join(work_dir, filename)) if urlparse(output_dir).scheme == 's3': s3am_upload(job=job, fpath=os.path.join(work_dir, filepath), s3_dir=output_dir, s3_key_path=s3_key_path) elif os.path.exists(os.path.join(output_dir, filename)): job.fileStore.logToMaster("File already exists: {}".format(filename)) else: mkdir_p(output_dir) copy_files([filepath], output_dir)
[ "def", "output_file_job", "(", "job", ",", "filename", ",", "file_id", ",", "output_dir", ",", "s3_key_path", "=", "None", ")", ":", "job", ".", "fileStore", ".", "logToMaster", "(", "'Writing {} to {}'", ".", "format", "(", "filename", ",", "output_dir", ")...
Uploads a file from the FileStore to an output directory on the local filesystem or S3. :param JobFunctionWrappingJob job: passed automatically by Toil :param str filename: basename for file :param str file_id: FileStoreID :param str output_dir: Amazon S3 URL or local path :param str s3_key_path: (OPTIONAL) Path to 32-byte key to be used for SSE-C encryption :return:
[ "Uploads", "a", "file", "from", "the", "FileStore", "to", "an", "output", "directory", "on", "the", "local", "filesystem", "or", "S3", "." ]
python
train
weso/CWR-DataApi
cwr/grammar/field/basic.py
https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/basic.py#L288-L308
def boolean(name=None): """ Creates the grammar for a Boolean (B) field, accepting only 'Y' or 'N' :param name: name for the field :return: grammar for the flag field """ if name is None: name = 'Boolean Field' # Basic field field = pp.Regex('[YN]') # Parse action field.setParseAction(lambda b: _to_boolean(b[0])) # Name field.setName(name) return field
[ "def", "boolean", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'Boolean Field'", "# Basic field", "field", "=", "pp", ".", "Regex", "(", "'[YN]'", ")", "# Parse action", "field", ".", "setParseAction", "(", "lambda", ...
Creates the grammar for a Boolean (B) field, accepting only 'Y' or 'N' :param name: name for the field :return: grammar for the flag field
[ "Creates", "the", "grammar", "for", "a", "Boolean", "(", "B", ")", "field", "accepting", "only", "Y", "or", "N" ]
python
train
markchil/gptools
gptools/kernel/matern.py
https://github.com/markchil/gptools/blob/225db52bfe6baef1516529ad22177aa2cf7b71e4/gptools/kernel/matern.py#L412-L459
def _compute_dk_dtau_on_partition(self, tau, p): """Evaluate the term inside the sum of Faa di Bruno's formula for the given partition. Overrides the version from :py:class:`gptools.kernel.core.ChainRuleKernel` in order to get the correct behavior at the origin. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. p : list of :py:class:`Array` Each element is a block of the partition representing the derivative orders to use. Returns ------- dk_dtau : :py:class:`Array`, (`M`,) The specified derivatives over the given partition at the specified locations. """ # Find the derivative order: n = len(p) y, r2l2 = self._compute_y(tau, return_r2l2=True) # Keep track of how many times a given variable has a block of length 1: n1 = 0 # Build the dy/dtau factor up iteratively: dy_dtau_factor = scipy.ones_like(y) for b in p: # If the partial derivative is exactly zero there is no sense in # continuing the computation: if (len(b) > 2) or ((len(b) == 2) and (b[0] != b[1])): return scipy.zeros_like(y) dy_dtau_factor *= self._compute_dy_dtau(tau, b, r2l2) # Count the number of blocks of length 1: if len(b) == 1: n1 += 1.0 # Compute d^(|pi|)f/dy^(|pi|) term: dk_dy = self._compute_dk_dy(y, n) if n1 > 0: mask = (y == 0.0) tau_pow = 2 * (self.nu - n) + n1 if tau_pow == 0: # In this case the limit does not exist, so it is set to NaN: dk_dy[mask] = scipy.nan elif tau_pow > 0: dk_dy[mask] = 0.0 return dk_dy * dy_dtau_factor
[ "def", "_compute_dk_dtau_on_partition", "(", "self", ",", "tau", ",", "p", ")", ":", "# Find the derivative order:", "n", "=", "len", "(", "p", ")", "y", ",", "r2l2", "=", "self", ".", "_compute_y", "(", "tau", ",", "return_r2l2", "=", "True", ")", "# Ke...
Evaluate the term inside the sum of Faa di Bruno's formula for the given partition. Overrides the version from :py:class:`gptools.kernel.core.ChainRuleKernel` in order to get the correct behavior at the origin. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. p : list of :py:class:`Array` Each element is a block of the partition representing the derivative orders to use. Returns ------- dk_dtau : :py:class:`Array`, (`M`,) The specified derivatives over the given partition at the specified locations.
[ "Evaluate", "the", "term", "inside", "the", "sum", "of", "Faa", "di", "Bruno", "s", "formula", "for", "the", "given", "partition", ".", "Overrides", "the", "version", "from", ":", "py", ":", "class", ":", "gptools", ".", "kernel", ".", "core", ".", "Ch...
python
train
zblz/naima
naima/radiative.py
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L1673-L1699
def _Fgamma(self, x, Ep): """ KAB06 Eq.58 Note: Quantities are not used in this function Parameters ---------- x : float Egamma/Eprot Ep : float Eprot [TeV] """ L = np.log(Ep) B = 1.30 + 0.14 * L + 0.011 * L ** 2 # Eq59 beta = (1.79 + 0.11 * L + 0.008 * L ** 2) ** -1 # Eq60 k = (0.801 + 0.049 * L + 0.014 * L ** 2) ** -1 # Eq61 xb = x ** beta F1 = B * (np.log(x) / x) * ((1 - xb) / (1 + k * xb * (1 - xb))) ** 4 F2 = ( 1.0 / np.log(x) - (4 * beta * xb) / (1 - xb) - (4 * k * beta * xb * (1 - 2 * xb)) / (1 + k * xb * (1 - xb)) ) return F1 * F2
[ "def", "_Fgamma", "(", "self", ",", "x", ",", "Ep", ")", ":", "L", "=", "np", ".", "log", "(", "Ep", ")", "B", "=", "1.30", "+", "0.14", "*", "L", "+", "0.011", "*", "L", "**", "2", "# Eq59", "beta", "=", "(", "1.79", "+", "0.11", "*", "L...
KAB06 Eq.58 Note: Quantities are not used in this function Parameters ---------- x : float Egamma/Eprot Ep : float Eprot [TeV]
[ "KAB06", "Eq", ".", "58" ]
python
train
google-research/batch-ppo
agents/scripts/configs.py
https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/scripts/configs.py#L29-L57
def default(): """Default configuration for PPO.""" # General algorithm = algorithms.PPO num_agents = 30 eval_episodes = 30 use_gpu = False # Environment normalize_ranges = True # Network network = networks.feed_forward_gaussian weight_summaries = dict( all=r'.*', policy=r'.*/policy/.*', value=r'.*/value/.*') policy_layers = 200, 100 value_layers = 200, 100 init_output_factor = 0.1 init_std = 0.35 # Optimization update_every = 30 update_epochs = 25 optimizer = tf.train.AdamOptimizer learning_rate = 1e-4 # Losses discount = 0.995 kl_target = 1e-2 kl_cutoff_factor = 2 kl_cutoff_coef = 1000 kl_init_penalty = 1 return locals()
[ "def", "default", "(", ")", ":", "# General", "algorithm", "=", "algorithms", ".", "PPO", "num_agents", "=", "30", "eval_episodes", "=", "30", "use_gpu", "=", "False", "# Environment", "normalize_ranges", "=", "True", "# Network", "network", "=", "networks", "...
Default configuration for PPO.
[ "Default", "configuration", "for", "PPO", "." ]
python
train
DataDog/integrations-core
kafka_consumer/datadog_checks/kafka_consumer/kafka_consumer.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/kafka_consumer/datadog_checks/kafka_consumer/kafka_consumer.py#L548-L568
def _validate_explicit_consumer_groups(cls, val): """Validate any explicitly specified consumer groups. While the check does not require specifying consumer groups, if they are specified this method should be used to validate them. val = {'consumer_group': {'topic': [0, 1]}} """ assert isinstance(val, dict) for consumer_group, topics in iteritems(val): assert isinstance(consumer_group, string_types) # topics are optional assert isinstance(topics, dict) or topics is None if topics is not None: for topic, partitions in iteritems(topics): assert isinstance(topic, string_types) # partitions are optional assert isinstance(partitions, (list, tuple)) or partitions is None if partitions is not None: for partition in partitions: assert isinstance(partition, int)
[ "def", "_validate_explicit_consumer_groups", "(", "cls", ",", "val", ")", ":", "assert", "isinstance", "(", "val", ",", "dict", ")", "for", "consumer_group", ",", "topics", "in", "iteritems", "(", "val", ")", ":", "assert", "isinstance", "(", "consumer_group",...
Validate any explicitly specified consumer groups. While the check does not require specifying consumer groups, if they are specified this method should be used to validate them. val = {'consumer_group': {'topic': [0, 1]}}
[ "Validate", "any", "explicitly", "specified", "consumer", "groups", "." ]
python
train
draios/python-sdc-client
sdcclient/_monitor.py
https://github.com/draios/python-sdc-client/blob/47f83415842048778939b90944f64386a3bcb205/sdcclient/_monitor.py#L296-L307
def get_dashboards(self): '''**Description** Return the list of dashboards available under the given user account. This includes the dashboards created by the user and the ones shared with her by other users. **Success Return Value** A dictionary containing the list of available sampling intervals. **Example** `examples/list_dashboards.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_dashboards.py>`_ ''' res = requests.get(self.url + self._dashboards_api_endpoint, headers=self.hdrs, verify=self.ssl_verify) return self._request_result(res)
[ "def", "get_dashboards", "(", "self", ")", ":", "res", "=", "requests", ".", "get", "(", "self", ".", "url", "+", "self", ".", "_dashboards_api_endpoint", ",", "headers", "=", "self", ".", "hdrs", ",", "verify", "=", "self", ".", "ssl_verify", ")", "re...
**Description** Return the list of dashboards available under the given user account. This includes the dashboards created by the user and the ones shared with her by other users. **Success Return Value** A dictionary containing the list of available sampling intervals. **Example** `examples/list_dashboards.py <https://github.com/draios/python-sdc-client/blob/master/examples/list_dashboards.py>`_
[ "**", "Description", "**", "Return", "the", "list", "of", "dashboards", "available", "under", "the", "given", "user", "account", ".", "This", "includes", "the", "dashboards", "created", "by", "the", "user", "and", "the", "ones", "shared", "with", "her", "by"...
python
test
B2W-BIT/aiologger
aiologger/logger.py
https://github.com/B2W-BIT/aiologger/blob/0b366597a8305d5577a267305e81d5e4784cd398/aiologger/logger.py#L163-L172
def debug(self, msg, *args, **kwargs) -> Task: # type: ignore """ Log msg with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. await logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) """ return self._make_log_task(logging.DEBUG, msg, args, **kwargs)
[ "def", "debug", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Task", ":", "# type: ignore", "return", "self", ".", "_make_log_task", "(", "logging", ".", "DEBUG", ",", "msg", ",", "args", ",", "*", "*", "kwargs", "...
Log msg with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. await logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
[ "Log", "msg", "with", "severity", "DEBUG", "." ]
python
train
PythonCharmers/python-future
src/future/backports/urllib/request.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L1710-L1713
def open_unknown_proxy(self, proxy, fullurl, data=None): """Overridable interface to open unknown URL type.""" type, url = splittype(fullurl) raise IOError('url error', 'invalid proxy for %s' % type, proxy)
[ "def", "open_unknown_proxy", "(", "self", ",", "proxy", ",", "fullurl", ",", "data", "=", "None", ")", ":", "type", ",", "url", "=", "splittype", "(", "fullurl", ")", "raise", "IOError", "(", "'url error'", ",", "'invalid proxy for %s'", "%", "type", ",", ...
Overridable interface to open unknown URL type.
[ "Overridable", "interface", "to", "open", "unknown", "URL", "type", "." ]
python
train
balloob/pychromecast
pychromecast/controllers/media.py
https://github.com/balloob/pychromecast/blob/831b09c4fed185a7bffe0ea330b7849d5f4e36b6/pychromecast/controllers/media.py#L252-L282
def update(self, data): """ New data will only contain the changed attributes. """ if not data.get('status', []): return status_data = data['status'][0] media_data = status_data.get('media') or {} volume_data = status_data.get('volume', {}) self.current_time = status_data.get('currentTime', self.current_time) self.content_id = media_data.get('contentId', self.content_id) self.content_type = media_data.get('contentType', self.content_type) self.duration = media_data.get('duration', self.duration) self.stream_type = media_data.get('streamType', self.stream_type) self.idle_reason = status_data.get('idleReason', self.idle_reason) self.media_session_id = status_data.get( 'mediaSessionId', self.media_session_id) self.playback_rate = status_data.get( 'playbackRate', self.playback_rate) self.player_state = status_data.get('playerState', self.player_state) self.supported_media_commands = status_data.get( 'supportedMediaCommands', self.supported_media_commands) self.volume_level = volume_data.get('level', self.volume_level) self.volume_muted = volume_data.get('muted', self.volume_muted) self.media_custom_data = media_data.get( 'customData', self.media_custom_data) self.media_metadata = media_data.get('metadata', self.media_metadata) self.subtitle_tracks = media_data.get('tracks', self.subtitle_tracks) self.current_subtitle_tracks = status_data.get( 'activeTrackIds', self.current_subtitle_tracks) self.last_updated = datetime.utcnow()
[ "def", "update", "(", "self", ",", "data", ")", ":", "if", "not", "data", ".", "get", "(", "'status'", ",", "[", "]", ")", ":", "return", "status_data", "=", "data", "[", "'status'", "]", "[", "0", "]", "media_data", "=", "status_data", ".", "get",...
New data will only contain the changed attributes.
[ "New", "data", "will", "only", "contain", "the", "changed", "attributes", "." ]
python
train
gagneurlab/concise
concise/legacy/concise.py
https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/legacy/concise.py#L1101-L1111
def load(cls, file_path): """ Load the object from a JSON file (saved with :py:func:`Concise.save`). Returns: Concise: Loaded Concise object. """ # convert back to numpy data = helper.read_json(file_path) return Concise.from_dict(data)
[ "def", "load", "(", "cls", ",", "file_path", ")", ":", "# convert back to numpy", "data", "=", "helper", ".", "read_json", "(", "file_path", ")", "return", "Concise", ".", "from_dict", "(", "data", ")" ]
Load the object from a JSON file (saved with :py:func:`Concise.save`). Returns: Concise: Loaded Concise object.
[ "Load", "the", "object", "from", "a", "JSON", "file", "(", "saved", "with", ":", "py", ":", "func", ":", "Concise", ".", "save", ")", "." ]
python
train
dpkp/kafka-python
kafka/consumer/subscription_state.py
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/consumer/subscription_state.py#L180-L191
def group_subscribe(self, topics): """Add topics to the current group subscription. This is used by the group leader to ensure that it receives metadata updates for all topics that any member of the group is subscribed to. Arguments: topics (list of str): topics to add to the group subscription """ if self._user_assignment: raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE) self._group_subscription.update(topics)
[ "def", "group_subscribe", "(", "self", ",", "topics", ")", ":", "if", "self", ".", "_user_assignment", ":", "raise", "IllegalStateError", "(", "self", ".", "_SUBSCRIPTION_EXCEPTION_MESSAGE", ")", "self", ".", "_group_subscription", ".", "update", "(", "topics", ...
Add topics to the current group subscription. This is used by the group leader to ensure that it receives metadata updates for all topics that any member of the group is subscribed to. Arguments: topics (list of str): topics to add to the group subscription
[ "Add", "topics", "to", "the", "current", "group", "subscription", "." ]
python
train
sibirrer/lenstronomy
lenstronomy/Cosmo/lens_cosmo.py
https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Cosmo/lens_cosmo.py#L156-L171
def nfw_angle2physical(self, Rs_angle, theta_Rs): """ converts the angular parameters into the physical ones for an NFW profile :param theta_Rs: observed bending angle at the scale radius in units of arcsec :param Rs: scale radius in units of arcsec :return: M200, r200, Rs_physical, c """ Rs = Rs_angle * const.arcsec * self.D_d theta_scaled = theta_Rs * self.epsilon_crit * self.D_d * const.arcsec rho0 = theta_scaled / (4 * Rs ** 2 * (1 + np.log(1. / 2.))) rho0_com = rho0 / self.h**2 * self.a_z(self.z_lens)**3 c = self.nfw_param.c_rho0(rho0_com) r200 = c * Rs M200 = self.nfw_param.M_r200(r200 * self.h / self.a_z(self.z_lens)) / self.h return rho0, Rs, c, r200, M200
[ "def", "nfw_angle2physical", "(", "self", ",", "Rs_angle", ",", "theta_Rs", ")", ":", "Rs", "=", "Rs_angle", "*", "const", ".", "arcsec", "*", "self", ".", "D_d", "theta_scaled", "=", "theta_Rs", "*", "self", ".", "epsilon_crit", "*", "self", ".", "D_d",...
converts the angular parameters into the physical ones for an NFW profile :param theta_Rs: observed bending angle at the scale radius in units of arcsec :param Rs: scale radius in units of arcsec :return: M200, r200, Rs_physical, c
[ "converts", "the", "angular", "parameters", "into", "the", "physical", "ones", "for", "an", "NFW", "profile" ]
python
train
LionelAuroux/pyrser
pyrser/dsl.py
https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L733-L745
def add_directive(self, sequence, d, s): """Add a directive in the sequence""" if d.name in meta._directives: the_class = meta._directives[d.name] sequence.parser_tree = parsing.Directive(the_class(), d.listparam, s.parser_tree) elif d.name in meta._decorators: the_class = meta._decorators[d.name] sequence.parser_tree = parsing.Decorator(the_class, d.listparam, s.parser_tree) else: raise TypeError("Unkown directive or decorator %s" % d.name) return True
[ "def", "add_directive", "(", "self", ",", "sequence", ",", "d", ",", "s", ")", ":", "if", "d", ".", "name", "in", "meta", ".", "_directives", ":", "the_class", "=", "meta", ".", "_directives", "[", "d", ".", "name", "]", "sequence", ".", "parser_tree...
Add a directive in the sequence
[ "Add", "a", "directive", "in", "the", "sequence" ]
python
test
markovmodel/PyEMMA
pyemma/coordinates/data/_base/datasource.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/datasource.py#L227-L242
def number_of_trajectories(self, stride=None): r""" Returns the number of trajectories. Parameters ---------- stride: None (default) or np.ndarray Returns ------- int : number of trajectories """ if not IteratorState.is_uniform_stride(stride): n = len(np.unique(stride[:, 0])) else: n = self.ntraj return n
[ "def", "number_of_trajectories", "(", "self", ",", "stride", "=", "None", ")", ":", "if", "not", "IteratorState", ".", "is_uniform_stride", "(", "stride", ")", ":", "n", "=", "len", "(", "np", ".", "unique", "(", "stride", "[", ":", ",", "0", "]", ")...
r""" Returns the number of trajectories. Parameters ---------- stride: None (default) or np.ndarray Returns ------- int : number of trajectories
[ "r", "Returns", "the", "number", "of", "trajectories", "." ]
python
train
yougov/vr.runners
vr/runners/base.py
https://github.com/yougov/vr.runners/blob/f43ba50a64b17ee4f07596fe225bcb38ca6652ad/vr/runners/base.py#L451-L457
def get_template(name): """ Look for 'name' in the vr.runners.templates folder. Return its contents. """ path = pkg_resources.resource_filename('vr.runners', 'templates/' + name) with open(path, 'r') as f: return f.read()
[ "def", "get_template", "(", "name", ")", ":", "path", "=", "pkg_resources", ".", "resource_filename", "(", "'vr.runners'", ",", "'templates/'", "+", "name", ")", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "return", "f", ".", "read", ...
Look for 'name' in the vr.runners.templates folder. Return its contents.
[ "Look", "for", "name", "in", "the", "vr", ".", "runners", ".", "templates", "folder", ".", "Return", "its", "contents", "." ]
python
train
brennv/namedtupled
namedtupled/integrations.py
https://github.com/brennv/namedtupled/blob/2b8e3bafd82835ef01549d7a266c34454637ff70/namedtupled/integrations.py#L36-L44
def load_env(keys=[], name='NT', use_getpass=False): """ Returns a namedtuple from a list of environment variables. If not found in shell, gets input with *input* or *getpass*. """ NT = namedtuple(name, keys) if use_getpass: values = [os.getenv(x) or getpass.getpass(x) for x in keys] else: values = [os.getenv(x) or input(x) for x in keys] return NT(*values)
[ "def", "load_env", "(", "keys", "=", "[", "]", ",", "name", "=", "'NT'", ",", "use_getpass", "=", "False", ")", ":", "NT", "=", "namedtuple", "(", "name", ",", "keys", ")", "if", "use_getpass", ":", "values", "=", "[", "os", ".", "getenv", "(", "...
Returns a namedtuple from a list of environment variables. If not found in shell, gets input with *input* or *getpass*.
[ "Returns", "a", "namedtuple", "from", "a", "list", "of", "environment", "variables", ".", "If", "not", "found", "in", "shell", "gets", "input", "with", "*", "input", "*", "or", "*", "getpass", "*", "." ]
python
train
rodynnz/xccdf
src/xccdf/models/status.py
https://github.com/rodynnz/xccdf/blob/1b9dc2f06b5cce8db2a54c5f95a8f6bcf5cb6981/src/xccdf/models/status.py#L82-L97
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) if hasattr(self, 'date'): self.xml_element.set('date', self.date) self.xml_element.text = self.text return self.xml_element
[ "def", "update_xml_element", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'xml_element'", ")", ":", "self", ".", "xml_element", "=", "etree", ".", "Element", "(", "self", ".", "name", ",", "nsmap", "=", "NSMAP", ")", "if", "hasattr...
Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element
[ "Updates", "the", "xml", "element", "contents", "to", "matches", "the", "instance", "contents", "." ]
python
train
ckan/losser
losser/cli.py
https://github.com/ckan/losser/blob/fd0832d9fa93cabe9ce9a9153dc923f2cf39cb5f/losser/cli.py#L317-L336
def main(): """Call do() and if it raises an exception then sys.exit() appropriately. This makes sure that any usage and error messages are printed correctly, and that the exit code is right. do() itself doesn't call sys.exit() because we want it to be callable from tests that check that it raises the right exception classes for different invalid inputs. """ parser = make_parser() try: output = do(parser=parser) except CommandLineExit as err: sys.exit(err.code) except CommandLineError as err: if err.message: parser.error(err.message) sys.stdout.write(output)
[ "def", "main", "(", ")", ":", "parser", "=", "make_parser", "(", ")", "try", ":", "output", "=", "do", "(", "parser", "=", "parser", ")", "except", "CommandLineExit", "as", "err", ":", "sys", ".", "exit", "(", "err", ".", "code", ")", "except", "Co...
Call do() and if it raises an exception then sys.exit() appropriately. This makes sure that any usage and error messages are printed correctly, and that the exit code is right. do() itself doesn't call sys.exit() because we want it to be callable from tests that check that it raises the right exception classes for different invalid inputs.
[ "Call", "do", "()", "and", "if", "it", "raises", "an", "exception", "then", "sys", ".", "exit", "()", "appropriately", "." ]
python
train
dbcli/athenacli
athenacli/packages/completion_engine.py
https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/completion_engine.py#L48-L121
def suggest_type(full_text, text_before_cursor): """Takes the full_text that is typed so far and also the text before the cursor to suggest completion type and scope. Returns a tuple with a type of entity ('table', 'column' etc) and a scope. A scope for a column category will be a list of tables. """ word_before_cursor = last_word(text_before_cursor, include='many_punctuations') identifier = None # here should be removed once sqlparse has been fixed try: # If we've partially typed a word then word_before_cursor won't be an empty # string. In that case we want to remove the partially typed string before # sending it to the sqlparser. Otherwise the last token will always be the # partially typed string which renders the smart completion useless because # it will always return the list of keywords as completion. if word_before_cursor: if word_before_cursor.endswith( '(') or word_before_cursor.startswith('\\'): parsed = sqlparse.parse(text_before_cursor) else: parsed = sqlparse.parse( text_before_cursor[:-len(word_before_cursor)]) # word_before_cursor may include a schema qualification, like # "schema_name.partial_name" or "schema_name.", so parse it # separately p = sqlparse.parse(word_before_cursor)[0] if p.tokens and isinstance(p.tokens[0], Identifier): identifier = p.tokens[0] else: parsed = sqlparse.parse(text_before_cursor) except (TypeError, AttributeError): return (Keyword(),) if len(parsed) > 1: # Multiple statements being edited -- isolate the current one by # cumulatively summing statement lengths to find the one that bounds the # current position current_pos = len(text_before_cursor) stmt_start, stmt_end = 0, 0 for statement in parsed: stmt_len = len(text_type(statement)) stmt_start, stmt_end = stmt_end, stmt_end + stmt_len if stmt_end >= current_pos: text_before_cursor = full_text[stmt_start:current_pos] full_text = full_text[stmt_start:] break elif parsed: # A single statement statement = parsed[0] else: # The empty string statement = None # Check for special commands and handle those separately if statement: # Be careful here because trivial whitespace is parsed as a statement, # but the statement won't have a first token tok1 = statement.token_first() if tok1 and tok1.value in ['\\', 'source']: return suggest_special(text_before_cursor) last_token = statement and statement.token_prev(len(statement.tokens))[1] or '' return suggest_based_on_last_token(last_token, text_before_cursor, full_text, identifier)
[ "def", "suggest_type", "(", "full_text", ",", "text_before_cursor", ")", ":", "word_before_cursor", "=", "last_word", "(", "text_before_cursor", ",", "include", "=", "'many_punctuations'", ")", "identifier", "=", "None", "# here should be removed once sqlparse has been fixe...
Takes the full_text that is typed so far and also the text before the cursor to suggest completion type and scope. Returns a tuple with a type of entity ('table', 'column' etc) and a scope. A scope for a column category will be a list of tables.
[ "Takes", "the", "full_text", "that", "is", "typed", "so", "far", "and", "also", "the", "text", "before", "the", "cursor", "to", "suggest", "completion", "type", "and", "scope", ".", "Returns", "a", "tuple", "with", "a", "type", "of", "entity", "(", "tabl...
python
train
chaimleib/intervaltree
intervaltree/node.py
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L100-L107
def refresh_balance(self): """ Recalculate self.balance and self.depth based on child node values. """ left_depth = self.left_node.depth if self.left_node else 0 right_depth = self.right_node.depth if self.right_node else 0 self.depth = 1 + max(left_depth, right_depth) self.balance = right_depth - left_depth
[ "def", "refresh_balance", "(", "self", ")", ":", "left_depth", "=", "self", ".", "left_node", ".", "depth", "if", "self", ".", "left_node", "else", "0", "right_depth", "=", "self", ".", "right_node", ".", "depth", "if", "self", ".", "right_node", "else", ...
Recalculate self.balance and self.depth based on child node values.
[ "Recalculate", "self", ".", "balance", "and", "self", ".", "depth", "based", "on", "child", "node", "values", "." ]
python
train
twilio/twilio-python
twilio/rest/autopilot/v1/assistant/field_type/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/autopilot/v1/assistant/field_type/__init__.py#L451-L461
def update(self, friendly_name=values.unset, unique_name=values.unset): """ Update the FieldTypeInstance :param unicode friendly_name: A string to describe the resource :param unicode unique_name: An application-defined string that uniquely identifies the resource :returns: Updated FieldTypeInstance :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance """ return self._proxy.update(friendly_name=friendly_name, unique_name=unique_name, )
[ "def", "update", "(", "self", ",", "friendly_name", "=", "values", ".", "unset", ",", "unique_name", "=", "values", ".", "unset", ")", ":", "return", "self", ".", "_proxy", ".", "update", "(", "friendly_name", "=", "friendly_name", ",", "unique_name", "=",...
Update the FieldTypeInstance :param unicode friendly_name: A string to describe the resource :param unicode unique_name: An application-defined string that uniquely identifies the resource :returns: Updated FieldTypeInstance :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance
[ "Update", "the", "FieldTypeInstance" ]
python
train
symengine/symengine.py
symengine/compatibility.py
https://github.com/symengine/symengine.py/blob/1366cf98ceaade339c5dd24ae3381a0e63ea9dad/symengine/compatibility.py#L563-L671
def ordered(seq, keys=None, default=True, warn=False): """Return an iterator of the seq where keys are used to break ties in a conservative fashion: if, after applying a key, there are no ties then no other keys will be computed. Two default keys will be applied if 1) keys are not provided or 2) the given keys don't resolve all ties (but only if `default` is True). The two keys are `_nodes` (which places smaller expressions before large) and `default_sort_key` which (if the `sort_key` for an object is defined properly) should resolve any ties. If ``warn`` is True then an error will be raised if there were no keys remaining to break ties. This can be used if it was expected that there should be no ties between items that are not identical. Examples ======== >>> from sympy.utilities.iterables import ordered >>> from sympy import count_ops >>> from sympy.abc import x, y The count_ops is not sufficient to break ties in this list and the first two items appear in their original order (i.e. the sorting is stable): >>> list(ordered([y + 2, x + 2, x**2 + y + 3], ... count_ops, default=False, warn=False)) ... [y + 2, x + 2, x**2 + y + 3] The default_sort_key allows the tie to be broken: >>> list(ordered([y + 2, x + 2, x**2 + y + 3])) ... [x + 2, y + 2, x**2 + y + 3] Here, sequences are sorted by length, then sum: >>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], [ ... lambda x: len(x), ... lambda x: sum(x)]] ... >>> list(ordered(seq, keys, default=False, warn=False)) [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]] If ``warn`` is True, an error will be raised if there were not enough keys to break ties: >>> list(ordered(seq, keys, default=False, warn=True)) Traceback (most recent call last): ... ValueError: not enough keys to break ties Notes ===== The decorated sort is one of the fastest ways to sort a sequence for which special item comparison is desired: the sequence is decorated, sorted on the basis of the decoration (e.g. making all letters lower case) and then undecorated. If one wants to break ties for items that have the same decorated value, a second key can be used. But if the second key is expensive to compute then it is inefficient to decorate all items with both keys: only those items having identical first key values need to be decorated. This function applies keys successively only when needed to break ties. By yielding an iterator, use of the tie-breaker is delayed as long as possible. This function is best used in cases when use of the first key is expected to be a good hashing function; if there are no unique hashes from application of a key then that key should not have been used. The exception, however, is that even if there are many collisions, if the first group is small and one does not need to process all items in the list then time will not be wasted sorting what one was not interested in. For example, if one were looking for the minimum in a list and there were several criteria used to define the sort order, then this function would be good at returning that quickly if the first group of candidates is small relative to the number of items being processed. """ d = defaultdict(list) if keys: if not isinstance(keys, (list, tuple)): keys = [keys] keys = list(keys) f = keys.pop(0) for a in seq: d[f(a)].append(a) else: if not default: raise ValueError('if default=False then keys must be provided') d[None].extend(seq) for k in sorted(d.keys()): if len(d[k]) > 1: if keys: d[k] = ordered(d[k], keys, default, warn) elif default: d[k] = ordered(d[k], (_nodes, default_sort_key,), default=False, warn=warn) elif warn: from sympy.utilities.iterables import uniq u = list(uniq(d[k])) if len(u) > 1: raise ValueError( 'not enough keys to break ties: %s' % u) for v in d[k]: yield v d.pop(k)
[ "def", "ordered", "(", "seq", ",", "keys", "=", "None", ",", "default", "=", "True", ",", "warn", "=", "False", ")", ":", "d", "=", "defaultdict", "(", "list", ")", "if", "keys", ":", "if", "not", "isinstance", "(", "keys", ",", "(", "list", ",",...
Return an iterator of the seq where keys are used to break ties in a conservative fashion: if, after applying a key, there are no ties then no other keys will be computed. Two default keys will be applied if 1) keys are not provided or 2) the given keys don't resolve all ties (but only if `default` is True). The two keys are `_nodes` (which places smaller expressions before large) and `default_sort_key` which (if the `sort_key` for an object is defined properly) should resolve any ties. If ``warn`` is True then an error will be raised if there were no keys remaining to break ties. This can be used if it was expected that there should be no ties between items that are not identical. Examples ======== >>> from sympy.utilities.iterables import ordered >>> from sympy import count_ops >>> from sympy.abc import x, y The count_ops is not sufficient to break ties in this list and the first two items appear in their original order (i.e. the sorting is stable): >>> list(ordered([y + 2, x + 2, x**2 + y + 3], ... count_ops, default=False, warn=False)) ... [y + 2, x + 2, x**2 + y + 3] The default_sort_key allows the tie to be broken: >>> list(ordered([y + 2, x + 2, x**2 + y + 3])) ... [x + 2, y + 2, x**2 + y + 3] Here, sequences are sorted by length, then sum: >>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], [ ... lambda x: len(x), ... lambda x: sum(x)]] ... >>> list(ordered(seq, keys, default=False, warn=False)) [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]] If ``warn`` is True, an error will be raised if there were not enough keys to break ties: >>> list(ordered(seq, keys, default=False, warn=True)) Traceback (most recent call last): ... ValueError: not enough keys to break ties Notes ===== The decorated sort is one of the fastest ways to sort a sequence for which special item comparison is desired: the sequence is decorated, sorted on the basis of the decoration (e.g. making all letters lower case) and then undecorated. If one wants to break ties for items that have the same decorated value, a second key can be used. But if the second key is expensive to compute then it is inefficient to decorate all items with both keys: only those items having identical first key values need to be decorated. This function applies keys successively only when needed to break ties. By yielding an iterator, use of the tie-breaker is delayed as long as possible. This function is best used in cases when use of the first key is expected to be a good hashing function; if there are no unique hashes from application of a key then that key should not have been used. The exception, however, is that even if there are many collisions, if the first group is small and one does not need to process all items in the list then time will not be wasted sorting what one was not interested in. For example, if one were looking for the minimum in a list and there were several criteria used to define the sort order, then this function would be good at returning that quickly if the first group of candidates is small relative to the number of items being processed.
[ "Return", "an", "iterator", "of", "the", "seq", "where", "keys", "are", "used", "to", "break", "ties", "in", "a", "conservative", "fashion", ":", "if", "after", "applying", "a", "key", "there", "are", "no", "ties", "then", "no", "other", "keys", "will", ...
python
train
rwl/godot
godot/ui/graph_editor.py
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L293-L302
def _delete_nodes(self, features): """ Removes the node corresponding to each item in 'features'. """ graph = self._graph if graph is not None: for feature in features: graph.delete_node( id(feature) ) graph.arrange_all()
[ "def", "_delete_nodes", "(", "self", ",", "features", ")", ":", "graph", "=", "self", ".", "_graph", "if", "graph", "is", "not", "None", ":", "for", "feature", "in", "features", ":", "graph", ".", "delete_node", "(", "id", "(", "feature", ")", ")", "...
Removes the node corresponding to each item in 'features'.
[ "Removes", "the", "node", "corresponding", "to", "each", "item", "in", "features", "." ]
python
test
pmacosta/peng
peng/wave_functions.py
https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1282-L1324
def ifftr(wave, npoints=None, indep_min=None, indep_max=None): r""" Return the real part of the inverse Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.ifftr :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform frequency spacing) .. [[[end]]] """ return real(ifft(wave, npoints, indep_min, indep_max))
[ "def", "ifftr", "(", "wave", ",", "npoints", "=", "None", ",", "indep_min", "=", "None", ",", "indep_max", "=", "None", ")", ":", "return", "real", "(", "ifft", "(", "wave", ",", "npoints", ",", "indep_min", ",", "indep_max", ")", ")" ]
r""" Return the real part of the inverse Fast Fourier Transform of a waveform. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :param npoints: Number of points to use in the transform. If **npoints** is less than the size of the independent variable vector the waveform is truncated; if **npoints** is greater than the size of the independent variable vector, the waveform is zero-padded :type npoints: positive integer :param indep_min: Independent vector start point of computation :type indep_min: integer or float :param indep_max: Independent vector stop point of computation :type indep_max: integer or float :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for .. peng.wave_functions.ifftr :raises: * RuntimeError (Argument \`indep_max\` is not valid) * RuntimeError (Argument \`indep_min\` is not valid) * RuntimeError (Argument \`npoints\` is not valid) * RuntimeError (Argument \`wave\` is not valid) * RuntimeError (Incongruent \`indep_min\` and \`indep_max\` arguments) * RuntimeError (Non-uniform frequency spacing) .. [[[end]]]
[ "r", "Return", "the", "real", "part", "of", "the", "inverse", "Fast", "Fourier", "Transform", "of", "a", "waveform", "." ]
python
test
h2oai/h2o-3
h2o-py/h2o/demos.py
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/demos.py#L207-L303
def _run_demo(body_fn, interactive, echo, testing): """ Execute the demo, echoing commands and pausing for user input. :param body_fn: function that contains the sequence of demo's commands. :param interactive: If True, the user will be prompted to continue the demonstration after every segment. :param echo: If True, the python commands that are executed will be displayed. :param testing: Used for pyunit testing. h2o.init() will not be called if set to True. :type body_fn: function """ import colorama from colorama import Style, Fore colorama.init() class StopExecution(Exception): """Helper class for cancelling the demo.""" assert_is_type(body_fn, type(_run_demo)) # Reformat description by removing extra spaces; then print it. if body_fn.__doc__: desc_lines = body_fn.__doc__.split("\n") while desc_lines[0].strip() == "": desc_lines = desc_lines[1:] while desc_lines[-1].strip() == "": desc_lines = desc_lines[:-1] strip_spaces = min(len(line) - len(line.lstrip(" ")) for line in desc_lines[1:] if line.strip() != "") maxlen = max(len(line) for line in desc_lines) print(Fore.CYAN) print("-" * maxlen) for line in desc_lines: print(line[strip_spaces:].rstrip()) print("-" * maxlen) print(Style.RESET_ALL, end="") # Prepare the executor function def controller(): """Print to console the next block of commands, and wait for keypress.""" try: raise RuntimeError("Catch me!") except RuntimeError: print() # Extract and print lines that will be executed next if echo: tb = sys.exc_info()[2] fr = tb.tb_frame.f_back filename = fr.f_code.co_filename linecache.checkcache(filename) line = linecache.getline(filename, fr.f_lineno, fr.f_globals).rstrip() indent_len = len(line) - len(line.lstrip(" ")) assert line[indent_len:] == "go()" i = fr.f_lineno output_lines = [] n_blank_lines = 0 while True: i += 1 line = linecache.getline(filename, i, fr.f_globals).rstrip() # Detect dedent if line[:indent_len].strip() != "": break line = line[indent_len:] if line == "go()": break style = Fore.LIGHTBLACK_EX if line.lstrip().startswith("#") else Style.BRIGHT prompt = "... " if line.startswith(" ") else ">>> " output_lines.append(Fore.CYAN + prompt + Fore.RESET + style + line + Style.RESET_ALL) del style # Otherwise exception print-outs may get messed-up... if line.strip() == "": n_blank_lines += 1 if n_blank_lines > 5: break # Just in case we hit file end or something else: n_blank_lines = 0 for line in output_lines[:-n_blank_lines]: print(line) # Prompt for user input if interactive: print("\n" + Style.DIM + "(press any key)" + Style.RESET_ALL, end="") key = _wait_for_keypress() print("\r \r", end="") if key.lower() == "q": raise StopExecution() # Replace h2o.init() with a stub when running in "test" mode _h2o_init = h2o.init if testing: h2o.init = lambda *args, **kwargs: None # Run the test try: body_fn(controller) print("\n" + Fore.CYAN + "---- End of Demo ----" + Style.RESET_ALL) except (StopExecution, KeyboardInterrupt): print("\n" + Fore.RED + "---- Demo aborted ----" + Style.RESET_ALL) # Clean-up if testing: h2o.init = _h2o_init print() colorama.deinit()
[ "def", "_run_demo", "(", "body_fn", ",", "interactive", ",", "echo", ",", "testing", ")", ":", "import", "colorama", "from", "colorama", "import", "Style", ",", "Fore", "colorama", ".", "init", "(", ")", "class", "StopExecution", "(", "Exception", ")", ":"...
Execute the demo, echoing commands and pausing for user input. :param body_fn: function that contains the sequence of demo's commands. :param interactive: If True, the user will be prompted to continue the demonstration after every segment. :param echo: If True, the python commands that are executed will be displayed. :param testing: Used for pyunit testing. h2o.init() will not be called if set to True. :type body_fn: function
[ "Execute", "the", "demo", "echoing", "commands", "and", "pausing", "for", "user", "input", "." ]
python
test
lrq3000/pyFileFixity
pyFileFixity/lib/profilers/visual/memory_profiler.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/memory_profiler.py#L483-L538
def magic_memit(self, line=''): """Measure memory usage of a Python statement Usage, in line mode: %memit [-ir<R>t<T>] statement Options: -r<R>: repeat the loop iteration <R> times and take the best result. Default: 1 -i: run the code in the current environment, without forking a new process. This is required on some MacOS versions of Accelerate if your line contains a call to `np.dot`. -t<T>: timeout after <T> seconds. Unused if `-i` is active. Default: None Examples -------- :: In [1]: import numpy as np In [2]: %memit np.zeros(1e7) maximum of 1: 76.402344 MB per loop In [3]: %memit np.ones(1e6) maximum of 1: 7.820312 MB per loop In [4]: %memit -r 10 np.empty(1e8) maximum of 10: 0.101562 MB per loop In [5]: memit -t 3 while True: pass; Subprocess timed out. Subprocess timed out. Subprocess timed out. ERROR: all subprocesses exited unsuccessfully. Try again with the `-i` option. maximum of 1: -inf MB per loop """ opts, stmt = self.parse_options(line, 'r:t:i', posix=False, strict=False) repeat = int(getattr(opts, 'r', 1)) if repeat < 1: repeat == 1 timeout = int(getattr(opts, 't', 0)) if timeout <= 0: timeout = None run_in_place = hasattr(opts, 'i') mem_usage = memory_usage((_func_exec, (stmt, self.shell.user_ns)), timeout=timeout, run_in_place=run_in_place) if mem_usage: print('maximum of %d: %f MB per loop' % (repeat, max(mem_usage))) else: print('ERROR: could not read memory usage, try with a lower interval or more iterations')
[ "def", "magic_memit", "(", "self", ",", "line", "=", "''", ")", ":", "opts", ",", "stmt", "=", "self", ".", "parse_options", "(", "line", ",", "'r:t:i'", ",", "posix", "=", "False", ",", "strict", "=", "False", ")", "repeat", "=", "int", "(", "geta...
Measure memory usage of a Python statement Usage, in line mode: %memit [-ir<R>t<T>] statement Options: -r<R>: repeat the loop iteration <R> times and take the best result. Default: 1 -i: run the code in the current environment, without forking a new process. This is required on some MacOS versions of Accelerate if your line contains a call to `np.dot`. -t<T>: timeout after <T> seconds. Unused if `-i` is active. Default: None Examples -------- :: In [1]: import numpy as np In [2]: %memit np.zeros(1e7) maximum of 1: 76.402344 MB per loop In [3]: %memit np.ones(1e6) maximum of 1: 7.820312 MB per loop In [4]: %memit -r 10 np.empty(1e8) maximum of 10: 0.101562 MB per loop In [5]: memit -t 3 while True: pass; Subprocess timed out. Subprocess timed out. Subprocess timed out. ERROR: all subprocesses exited unsuccessfully. Try again with the `-i` option. maximum of 1: -inf MB per loop
[ "Measure", "memory", "usage", "of", "a", "Python", "statement" ]
python
train
mozillazg/bustard
bustard/http.py
https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/http.py#L291-L304
def cookie_dump(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False): """ :rtype: ``Cookie.SimpleCookie`` """ cookie = SimpleCookie() cookie[key] = value for attr in ('max_age', 'expires', 'path', 'domain', 'secure', 'httponly'): attr_key = attr.replace('_', '-') attr_value = locals()[attr] if attr_value: cookie[key][attr_key] = attr_value return cookie
[ "def", "cookie_dump", "(", "key", ",", "value", "=", "''", ",", "max_age", "=", "None", ",", "expires", "=", "None", ",", "path", "=", "'/'", ",", "domain", "=", "None", ",", "secure", "=", "False", ",", "httponly", "=", "False", ")", ":", "cookie"...
:rtype: ``Cookie.SimpleCookie``
[ ":", "rtype", ":", "Cookie", ".", "SimpleCookie" ]
python
valid
duniter/duniter-python-api
duniterpy/documents/crc_pubkey.py
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/crc_pubkey.py#L45-L59
def from_pubkey(cls: Type[CRCPubkeyType], pubkey: str) -> CRCPubkeyType: """ Return CRCPubkey instance from public key string :param pubkey: Public key :return: """ hash_root = hashlib.sha256() hash_root.update(base58.b58decode(pubkey)) hash_squared = hashlib.sha256() hash_squared.update(hash_root.digest()) b58_checksum = ensure_str(base58.b58encode(hash_squared.digest())) crc = b58_checksum[:3] return cls(pubkey, crc)
[ "def", "from_pubkey", "(", "cls", ":", "Type", "[", "CRCPubkeyType", "]", ",", "pubkey", ":", "str", ")", "->", "CRCPubkeyType", ":", "hash_root", "=", "hashlib", ".", "sha256", "(", ")", "hash_root", ".", "update", "(", "base58", ".", "b58decode", "(", ...
Return CRCPubkey instance from public key string :param pubkey: Public key :return:
[ "Return", "CRCPubkey", "instance", "from", "public", "key", "string" ]
python
train
Becksteinlab/GromacsWrapper
gromacs/fileformats/convert.py
https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/convert.py#L178-L189
def _convert_fancy(self, field): """Convert to a list (sep != None) and convert list elements.""" if self.sep is False: x = self._convert_singlet(field) else: x = tuple([self._convert_singlet(s) for s in field.split(self.sep)]) if len(x) == 0: x = '' elif len(x) == 1: x = x[0] #print "%r --> %r" % (field, x) return x
[ "def", "_convert_fancy", "(", "self", ",", "field", ")", ":", "if", "self", ".", "sep", "is", "False", ":", "x", "=", "self", ".", "_convert_singlet", "(", "field", ")", "else", ":", "x", "=", "tuple", "(", "[", "self", ".", "_convert_singlet", "(", ...
Convert to a list (sep != None) and convert list elements.
[ "Convert", "to", "a", "list", "(", "sep", "!", "=", "None", ")", "and", "convert", "list", "elements", "." ]
python
valid
klen/pylama
pylama/config.py
https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/config.py#L157-L212
def parse_options(args=None, config=True, rootdir=CURDIR, **overrides): # noqa """ Parse options from command line and configuration files. :return argparse.Namespace: """ args = args or [] # Parse args from command string options = PARSER.parse_args(args) options.file_params = dict() options.linters_params = dict() # Compile options from ini if config: cfg = get_config(str(options.options), rootdir=rootdir) for opt, val in cfg.default.items(): LOGGER.info('Find option %s (%s)', opt, val) passed_value = getattr(options, opt, _Default()) if isinstance(passed_value, _Default): if opt == 'paths': val = val.split() if opt == 'skip': val = fix_pathname_sep(val) setattr(options, opt, _Default(val)) # Parse file related options for name, opts in cfg.sections.items(): if name == cfg.default_section: continue if name.startswith('pylama'): name = name[7:] if name in LINTERS: options.linters_params[name] = dict(opts) continue mask = re.compile(fnmatch.translate(fix_pathname_sep(name))) options.file_params[mask] = dict(opts) # Override options _override_options(options, **overrides) # Postprocess options for name in options.__dict__: value = getattr(options, name) if isinstance(value, _Default): setattr(options, name, process_value(name, value.value)) if options.concurrent and 'pylint' in options.linters: LOGGER.warning('Can\'t parse code asynchronously with pylint enabled.') options.concurrent = False return options
[ "def", "parse_options", "(", "args", "=", "None", ",", "config", "=", "True", ",", "rootdir", "=", "CURDIR", ",", "*", "*", "overrides", ")", ":", "# noqa", "args", "=", "args", "or", "[", "]", "# Parse args from command string", "options", "=", "PARSER", ...
Parse options from command line and configuration files. :return argparse.Namespace:
[ "Parse", "options", "from", "command", "line", "and", "configuration", "files", "." ]
python
train