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
twitterdev/tweet_parser
tweet_parser/getter_methods/tweet_text.py
https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_text.py#L218-L261
def get_quote_or_rt_text(tweet): """ Get the quoted or retweeted text in a Tweet (this is not the text entered by the posting user) - tweet: empty string (there is no quoted or retweeted text) - quote: only the text of the quoted Tweet - retweet: the text of the retweet Args: tweet ...
[ "def", "get_quote_or_rt_text", "(", "tweet", ")", ":", "tweet_type", "=", "get_tweet_type", "(", "tweet", ")", "if", "tweet_type", "==", "\"tweet\"", ":", "return", "\"\"", "if", "tweet_type", "==", "\"quote\"", ":", "if", "is_original_format", "(", "tweet", "...
Get the quoted or retweeted text in a Tweet (this is not the text entered by the posting user) - tweet: empty string (there is no quoted or retweeted text) - quote: only the text of the quoted Tweet - retweet: the text of the retweet Args: tweet (Tweet or dict): A Tweet object or dictionary...
[ "Get", "the", "quoted", "or", "retweeted", "text", "in", "a", "Tweet", "(", "this", "is", "not", "the", "text", "entered", "by", "the", "posting", "user", ")", "-", "tweet", ":", "empty", "string", "(", "there", "is", "no", "quoted", "or", "retweeted",...
python
train
maartenbreddels/ipyvolume
ipyvolume/pylab.py
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L789-L885
def volshow( data, lighting=False, data_min=None, data_max=None, max_shape=256, tf=None, stereo=False, ambient_coefficient=0.5, diffuse_coefficient=0.8, specular_coefficient=0.5, specular_exponent=5, downscale=1, level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], ...
[ "def", "volshow", "(", "data", ",", "lighting", "=", "False", ",", "data_min", "=", "None", ",", "data_max", "=", "None", ",", "max_shape", "=", "256", ",", "tf", "=", "None", ",", "stereo", "=", "False", ",", "ambient_coefficient", "=", "0.5", ",", ...
Visualize a 3d array using volume rendering. Currently only 1 volume can be rendered. :param data: 3d numpy array :param origin: origin of the volume data, this is to match meshes which have a different origin :param domain_size: domain size is the size of the volume :param bool lighting: use lig...
[ "Visualize", "a", "3d", "array", "using", "volume", "rendering", "." ]
python
train
sosreport/sos
sos/policies/__init__.py
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L591-L599
def validate_plugin(self, plugin_class, experimental=False): """ Verifies that the plugin_class should execute under this policy """ valid_subclasses = [IndependentPlugin] + self.valid_subclasses if experimental: valid_subclasses += [ExperimentalPlugin] return...
[ "def", "validate_plugin", "(", "self", ",", "plugin_class", ",", "experimental", "=", "False", ")", ":", "valid_subclasses", "=", "[", "IndependentPlugin", "]", "+", "self", ".", "valid_subclasses", "if", "experimental", ":", "valid_subclasses", "+=", "[", "Expe...
Verifies that the plugin_class should execute under this policy
[ "Verifies", "that", "the", "plugin_class", "should", "execute", "under", "this", "policy" ]
python
train
gmr/tornado-elasticsearch
tornado_elasticsearch.py
https://github.com/gmr/tornado-elasticsearch/blob/fafe0de680277ce6faceb7449ded0b33822438d0/tornado_elasticsearch.py#L269-L282
def health(self, params=None): """Coroutine. Queries cluster Health API. Returns a 2-tuple, where first element is request status, and second element is a dictionary with response data. :param params: dictionary of query parameters, will be handed over to the underlying :cl...
[ "def", "health", "(", "self", ",", "params", "=", "None", ")", ":", "status", ",", "data", "=", "yield", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "\"/_cluster/health\"", ",", "params", "=", "params", ")", "raise", "gen", "."...
Coroutine. Queries cluster Health API. Returns a 2-tuple, where first element is request status, and second element is a dictionary with response data. :param params: dictionary of query parameters, will be handed over to the underlying :class:`~torando_elasticsearch.AsyncHTTPConne...
[ "Coroutine", ".", "Queries", "cluster", "Health", "API", "." ]
python
test
non-Jedi/gyr
gyr/matrix_objects.py
https://github.com/non-Jedi/gyr/blob/9f7bfe033b9d3bbfd3a9e8aea02e35526b53125e/gyr/matrix_objects.py#L49-L55
def user(self): """Creates a User object when requested.""" try: return self._user except AttributeError: self._user = MatrixUser(self.mxid, self.Api(identity=self.mxid)) return self._user
[ "def", "user", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_user", "except", "AttributeError", ":", "self", ".", "_user", "=", "MatrixUser", "(", "self", ".", "mxid", ",", "self", ".", "Api", "(", "identity", "=", "self", ".", "mxid", ...
Creates a User object when requested.
[ "Creates", "a", "User", "object", "when", "requested", "." ]
python
train
kislyuk/aegea
aegea/packages/github3/models.py
https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/models.py#L176-L184
def ratelimit_remaining(self): """Number of requests before GitHub imposes a ratelimit. :returns: int """ json = self._json(self._get(self._github_url + '/rate_limit'), 200) core = json.get('resources', {}).get('core', {}) self._remaining = core.get('remaining', 0) ...
[ "def", "ratelimit_remaining", "(", "self", ")", ":", "json", "=", "self", ".", "_json", "(", "self", ".", "_get", "(", "self", ".", "_github_url", "+", "'/rate_limit'", ")", ",", "200", ")", "core", "=", "json", ".", "get", "(", "'resources'", ",", "...
Number of requests before GitHub imposes a ratelimit. :returns: int
[ "Number", "of", "requests", "before", "GitHub", "imposes", "a", "ratelimit", "." ]
python
train
rytilahti/python-songpal
songpal/device.py
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L238-L243
async def get_storage_list(self) -> List[Storage]: """Return information about connected storage devices.""" return [ Storage.make(**x) for x in await self.services["system"]["getStorageList"]({}) ]
[ "async", "def", "get_storage_list", "(", "self", ")", "->", "List", "[", "Storage", "]", ":", "return", "[", "Storage", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "await", "self", ".", "services", "[", "\"system\"", "]", "[", "\"getStora...
Return information about connected storage devices.
[ "Return", "information", "about", "connected", "storage", "devices", "." ]
python
train
saltstack/salt
salt/grains/disks.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/disks.py#L29-L40
def disks(): ''' Return list of disk devices ''' if salt.utils.platform.is_freebsd(): return _freebsd_geom() elif salt.utils.platform.is_linux(): return _linux_disks() elif salt.utils.platform.is_windows(): return _windows_disks() else: log.trace('Disk grain d...
[ "def", "disks", "(", ")", ":", "if", "salt", ".", "utils", ".", "platform", ".", "is_freebsd", "(", ")", ":", "return", "_freebsd_geom", "(", ")", "elif", "salt", ".", "utils", ".", "platform", ".", "is_linux", "(", ")", ":", "return", "_linux_disks", ...
Return list of disk devices
[ "Return", "list", "of", "disk", "devices" ]
python
train
alefnula/tea
tea/shell/__init__.py
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L73-L91
def chdir(directory): """Change the current working directory. Args: directory (str): Directory to go to. """ directory = os.path.abspath(directory) logger.info("chdir -> %s" % directory) try: if not os.path.isdir(directory): logger.error( "chdir -> %...
[ "def", "chdir", "(", "directory", ")", ":", "directory", "=", "os", ".", "path", ".", "abspath", "(", "directory", ")", "logger", ".", "info", "(", "\"chdir -> %s\"", "%", "directory", ")", "try", ":", "if", "not", "os", ".", "path", ".", "isdir", "(...
Change the current working directory. Args: directory (str): Directory to go to.
[ "Change", "the", "current", "working", "directory", "." ]
python
train
AlecAivazis/graphql-over-kafka
nautilus/network/events/actionHandlers/rollCallHandler.py
https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/network/events/actionHandlers/rollCallHandler.py#L3-L12
async def roll_call_handler(service, action_type, payload, props, **kwds): """ This action handler responds to the "roll call" emitted by the api gateway when it is brought up with the normal summary produced by the service. """ # if the action type corresponds to a roll call if ...
[ "async", "def", "roll_call_handler", "(", "service", ",", "action_type", ",", "payload", ",", "props", ",", "*", "*", "kwds", ")", ":", "# if the action type corresponds to a roll call", "if", "action_type", "==", "roll_call_type", "(", ")", ":", "# then announce th...
This action handler responds to the "roll call" emitted by the api gateway when it is brought up with the normal summary produced by the service.
[ "This", "action", "handler", "responds", "to", "the", "roll", "call", "emitted", "by", "the", "api", "gateway", "when", "it", "is", "brought", "up", "with", "the", "normal", "summary", "produced", "by", "the", "service", "." ]
python
train
iotile/coretools
iotilesensorgraph/iotile/sg/output_formats/config.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/output_formats/config.py#L12-L33
def format_config(sensor_graph): """Extract the config variables from this sensor graph in ASCII format. Args: sensor_graph (SensorGraph): the sensor graph that we want to format Returns: str: The ascii output lines concatenated as a single string """ cmdfile = CommandFile("Config...
[ "def", "format_config", "(", "sensor_graph", ")", ":", "cmdfile", "=", "CommandFile", "(", "\"Config Variables\"", ",", "\"1.0\"", ")", "for", "slot", "in", "sorted", "(", "sensor_graph", ".", "config_database", ",", "key", "=", "lambda", "x", ":", "x", ".",...
Extract the config variables from this sensor graph in ASCII format. Args: sensor_graph (SensorGraph): the sensor graph that we want to format Returns: str: The ascii output lines concatenated as a single string
[ "Extract", "the", "config", "variables", "from", "this", "sensor", "graph", "in", "ASCII", "format", "." ]
python
train
google/grr
grr/core/grr_response_core/stats/stats_utils.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/stats/stats_utils.py#L158-L170
def CreateGaugeMetadata(metric_name, value_type, fields=None, docstring=None, units=None): """Helper function for creating MetricMetadata for gauge metrics.""" return rdf_stats.MetricMetadata( varname=metric_name, ...
[ "def", "CreateGaugeMetadata", "(", "metric_name", ",", "value_type", ",", "fields", "=", "None", ",", "docstring", "=", "None", ",", "units", "=", "None", ")", ":", "return", "rdf_stats", ".", "MetricMetadata", "(", "varname", "=", "metric_name", ",", "metri...
Helper function for creating MetricMetadata for gauge metrics.
[ "Helper", "function", "for", "creating", "MetricMetadata", "for", "gauge", "metrics", "." ]
python
train
gem/oq-engine
openquake/hazardlib/mfd/youngs_coppersmith_1985.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L289-L308
def _get_rate(self, mag): """ Calculate and return the annual occurrence rate for a specific bin. :param mag: Magnitude value corresponding to the center of the bin of interest. :returns: Float number, the annual occurrence rate for the :param mag value. ...
[ "def", "_get_rate", "(", "self", ",", "mag", ")", ":", "mag_lo", "=", "mag", "-", "self", ".", "bin_width", "/", "2.0", "mag_hi", "=", "mag", "+", "self", ".", "bin_width", "/", "2.0", "if", "mag", ">=", "self", ".", "min_mag", "and", "mag", "<", ...
Calculate and return the annual occurrence rate for a specific bin. :param mag: Magnitude value corresponding to the center of the bin of interest. :returns: Float number, the annual occurrence rate for the :param mag value.
[ "Calculate", "and", "return", "the", "annual", "occurrence", "rate", "for", "a", "specific", "bin", "." ]
python
train
bitesofcode/projexui
projexui/windows/xdkwindow/xdkwindow.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L552-L563
def browse( parent, filename = '' ): """ Creates a new XdkWidnow for browsing an XDK file. :param parent | <QWidget> filename | <str> """ dlg = XdkWindow(parent) dlg.show() if ( filename ): dlg.loadFil...
[ "def", "browse", "(", "parent", ",", "filename", "=", "''", ")", ":", "dlg", "=", "XdkWindow", "(", "parent", ")", "dlg", ".", "show", "(", ")", "if", "(", "filename", ")", ":", "dlg", ".", "loadFilename", "(", "filename", ")" ]
Creates a new XdkWidnow for browsing an XDK file. :param parent | <QWidget> filename | <str>
[ "Creates", "a", "new", "XdkWidnow", "for", "browsing", "an", "XDK", "file", ".", ":", "param", "parent", "|", "<QWidget", ">", "filename", "|", "<str", ">" ]
python
train
PySimpleGUI/PySimpleGUI
PySimpleGUIWeb/PySimpleGUIWeb.py
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/PySimpleGUIWeb.py#L5367-L5432
def EasyProgressMeter(title, current_value, max_value, *args, orientation=None, bar_color=(None, None), button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=None): ''' A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second function call...
[ "def", "EasyProgressMeter", "(", "title", ",", "current_value", ",", "max_value", ",", "*", "args", ",", "orientation", "=", "None", ",", "bar_color", "=", "(", "None", ",", "None", ")", ",", "button_color", "=", "None", ",", "size", "=", "DEFAULT_PROGRESS...
A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second function call before your loop. You've got enough code to write! :param title: Title will be shown on the window :param current_value: Current count of your items :param max_value: Max value your count will eve...
[ "A", "ONE", "-", "LINE", "progress", "meter", ".", "Add", "to", "your", "code", "where", "ever", "you", "need", "a", "meter", ".", "No", "need", "for", "a", "second", "function", "call", "before", "your", "loop", ".", "You", "ve", "got", "enough", "c...
python
train
ska-sa/purr
Purr/Pipe.py
https://github.com/ska-sa/purr/blob/4c848768d0485d0f88b30850d0d5372221b21b66/Purr/Pipe.py#L24-L30
def _write(self, what): """writes something to the Purr pipe""" try: open(self.pipefile, "a").write(what) except: print("Error writing to %s:" % self.pipefile) traceback.print_exc()
[ "def", "_write", "(", "self", ",", "what", ")", ":", "try", ":", "open", "(", "self", ".", "pipefile", ",", "\"a\"", ")", ".", "write", "(", "what", ")", "except", ":", "print", "(", "\"Error writing to %s:\"", "%", "self", ".", "pipefile", ")", "tra...
writes something to the Purr pipe
[ "writes", "something", "to", "the", "Purr", "pipe" ]
python
train
IBMStreams/pypi.streamsx
streamsx/spl/op.py
https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/op.py#L410-L426
def expression(value): """Create an SPL expression. Args: value: Expression as a string or another `Expression`. If value is an instance of `Expression` then a new instance is returned containing the same type and value. Returns: Expression: SPL expression from `value`....
[ "def", "expression", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Expression", ")", ":", "# Clone the expression to allow it to", "# be used in multiple contexts", "return", "Expression", "(", "value", ".", "_type", ",", "value", ".", "_value", ...
Create an SPL expression. Args: value: Expression as a string or another `Expression`. If value is an instance of `Expression` then a new instance is returned containing the same type and value. Returns: Expression: SPL expression from `value`.
[ "Create", "an", "SPL", "expression", "." ]
python
train
saltstack/salt
salt/modules/debuild_pkgbuild.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L98-L112
def _get_build_env(env): ''' Get build environment overrides dictionary to use in build process ''' env_override = '' if env is None: return env_override if not isinstance(env, dict): raise SaltInvocationError( '\'env\' must be a Python dictionary' ) for k...
[ "def", "_get_build_env", "(", "env", ")", ":", "env_override", "=", "''", "if", "env", "is", "None", ":", "return", "env_override", "if", "not", "isinstance", "(", "env", ",", "dict", ")", ":", "raise", "SaltInvocationError", "(", "'\\'env\\' must be a Python ...
Get build environment overrides dictionary to use in build process
[ "Get", "build", "environment", "overrides", "dictionary", "to", "use", "in", "build", "process" ]
python
train
decryptus/sonicprobe
sonicprobe/libs/urisup.py
https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/urisup.py#L565-L587
def uri_tree_precode_check(uri_tree, type_host = HOST_REG_NAME): """ Call this function to validate a raw URI tree before trying to encode it. """ scheme, authority, path, query, fragment = uri_tree # pylint: disable-msg=W0612 if scheme: if not valid_scheme(scheme): raise Inv...
[ "def", "uri_tree_precode_check", "(", "uri_tree", ",", "type_host", "=", "HOST_REG_NAME", ")", ":", "scheme", ",", "authority", ",", "path", ",", "query", ",", "fragment", "=", "uri_tree", "# pylint: disable-msg=W0612", "if", "scheme", ":", "if", "not", "valid_s...
Call this function to validate a raw URI tree before trying to encode it.
[ "Call", "this", "function", "to", "validate", "a", "raw", "URI", "tree", "before", "trying", "to", "encode", "it", "." ]
python
train
rduplain/jeni-python
jeni.py
https://github.com/rduplain/jeni-python/blob/feca12ce5e4f0438ae5d7bec59d61826063594f1/jeni.py#L701-L739
def handle_provider(self, provider_factory, note): """Get value from provider as requested by note.""" # Implementation in separate method to support accurate book-keeping. basenote, name = self.parse_note(note) # _handle_provider could be even shorter if # Injector.apply() work...
[ "def", "handle_provider", "(", "self", ",", "provider_factory", ",", "note", ")", ":", "# Implementation in separate method to support accurate book-keeping.", "basenote", ",", "name", "=", "self", ".", "parse_note", "(", "note", ")", "# _handle_provider could be even short...
Get value from provider as requested by note.
[ "Get", "value", "from", "provider", "as", "requested", "by", "note", "." ]
python
train
pyblish/pyblish-qml
pyblish_qml/vendor/mock.py
https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/vendor/mock.py#L243-L258
def _instance_callable(obj): """Given an object, return True if the object is callable. For classes, return True if instances would be callable.""" if not isinstance(obj, ClassTypes): # already an instance return getattr(obj, '__call__', None) is not None klass = obj # uses __bases_...
[ "def", "_instance_callable", "(", "obj", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "ClassTypes", ")", ":", "# already an instance", "return", "getattr", "(", "obj", ",", "'__call__'", ",", "None", ")", "is", "not", "None", "klass", "=", "obj", ...
Given an object, return True if the object is callable. For classes, return True if instances would be callable.
[ "Given", "an", "object", "return", "True", "if", "the", "object", "is", "callable", ".", "For", "classes", "return", "True", "if", "instances", "would", "be", "callable", "." ]
python
train
wbond/oscrypto
oscrypto/_osx/tls.py
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/tls.py#L1273-L1302
def _shutdown(self, manual): """ Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown """ if self._session_context is None: return # Ignore error during close in ca...
[ "def", "_shutdown", "(", "self", ",", "manual", ")", ":", "if", "self", ".", "_session_context", "is", "None", ":", "return", "# Ignore error during close in case other end closed already", "result", "=", "Security", ".", "SSLClose", "(", "self", ".", "_session_cont...
Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown
[ "Shuts", "down", "the", "TLS", "session", "and", "then", "shuts", "down", "the", "underlying", "socket" ]
python
valid
CalebBell/thermo
thermo/triple.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/triple.py#L125-L193
def Pt(CASRN, AvailableMethods=False, Method=None): r'''This function handles the retrieval of a chemical's triple pressure. Lookup is based on CASRNs. Will automatically select a data source to use if no Method is provided; returns None if the data is not available. Returns data from [1]_, or attempts...
[ "def", "Pt", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "Staveley_data", ".", "index", "and", "not", "np", ".", "isna...
r'''This function handles the retrieval of a chemical's triple pressure. Lookup is based on CASRNs. Will automatically select a data source to use if no Method is provided; returns None if the data is not available. Returns data from [1]_, or attempts to calculate the vapor pressure at the triple tempe...
[ "r", "This", "function", "handles", "the", "retrieval", "of", "a", "chemical", "s", "triple", "pressure", ".", "Lookup", "is", "based", "on", "CASRNs", ".", "Will", "automatically", "select", "a", "data", "source", "to", "use", "if", "no", "Method", "is", ...
python
valid
mozilla-releng/scriptworker
scriptworker/client.py
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L71-L95
def validate_task_schema(context, schema_key='schema_file'): """Validate the task definition. Args: context (scriptworker.context.Context): the scriptworker context. It must contain a task and the config pointing to the schema file schema_key: the key in `context.config` where the p...
[ "def", "validate_task_schema", "(", "context", ",", "schema_key", "=", "'schema_file'", ")", ":", "schema_path", "=", "context", ".", "config", "schema_keys", "=", "schema_key", ".", "split", "(", "'.'", ")", "for", "key", "in", "schema_keys", ":", "schema_pat...
Validate the task definition. Args: context (scriptworker.context.Context): the scriptworker context. It must contain a task and the config pointing to the schema file schema_key: the key in `context.config` where the path to the schema file is. Key can contain dots (e.g.: '...
[ "Validate", "the", "task", "definition", "." ]
python
train
square/pylink
pylink/jlink.py
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3881-L3905
def strace_configure(self, port_width): """Configures the trace port width for tracing. Note that configuration cannot occur while STRACE is running. Args: self (JLink): the ``JLink`` instance port_width (int): the trace port width to use. Returns: ``None...
[ "def", "strace_configure", "(", "self", ",", "port_width", ")", ":", "if", "port_width", "not", "in", "[", "1", ",", "2", ",", "4", "]", ":", "raise", "ValueError", "(", "'Invalid port width: %s'", "%", "str", "(", "port_width", ")", ")", "config_string", ...
Configures the trace port width for tracing. Note that configuration cannot occur while STRACE is running. Args: self (JLink): the ``JLink`` instance port_width (int): the trace port width to use. Returns: ``None`` Raises: ValueError: if ``port...
[ "Configures", "the", "trace", "port", "width", "for", "tracing", "." ]
python
train
OpenGeoVis/espatools
espatools/read.py
https://github.com/OpenGeoVis/espatools/blob/5c04daae0f035c7efcb4096bb85a26c6959ac9ea/espatools/read.py#L137-L181
def Read(self, meta_only=False, allowed=None, cast=False): """Read the ESPA XML metadata file""" if allowed is not None and not isinstance(allowed, (list, tuple)): raise RuntimeError('`allowed` must be a list of str names.') meta = xmltodict.parse( open(self.filename...
[ "def", "Read", "(", "self", ",", "meta_only", "=", "False", ",", "allowed", "=", "None", ",", "cast", "=", "False", ")", ":", "if", "allowed", "is", "not", "None", "and", "not", "isinstance", "(", "allowed", ",", "(", "list", ",", "tuple", ")", ")"...
Read the ESPA XML metadata file
[ "Read", "the", "ESPA", "XML", "metadata", "file" ]
python
train
readbeyond/aeneas
aeneas/executejob.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executejob.py#L187-L218
def execute(self): """ Execute the job, that is, execute all of its tasks. Each produced sync map will be stored inside the corresponding task object. :raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution """ ...
[ "def", "execute", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Executing job\"", ")", "if", "self", ".", "job", "is", "None", ":", "self", ".", "log_exc", "(", "u\"The job object is None\"", ",", "None", ",", "True", ",", "ExecuteJobExecutionError", ...
Execute the job, that is, execute all of its tasks. Each produced sync map will be stored inside the corresponding task object. :raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution
[ "Execute", "the", "job", "that", "is", "execute", "all", "of", "its", "tasks", "." ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L11699-L11709
def log_data_send(self, id, ofs, count, data, force_mavlink1=False): ''' Reply to LOG_REQUEST_DATA id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) count ...
[ "def", "log_data_send", "(", "self", ",", "id", ",", "ofs", ",", "count", ",", "data", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "log_data_encode", "(", "id", ",", "ofs", ",", "count", ",", "data"...
Reply to LOG_REQUEST_DATA id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) count : Number of bytes (zero for end of log) (uint8_t) data ...
[ "Reply", "to", "LOG_REQUEST_DATA" ]
python
train
materialsproject/pymatgen
pymatgen/core/spectrum.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/spectrum.py#L121-L126
def copy(self): """ Returns: Copy of Spectrum object. """ return self.__class__(self.x, self.y, *self._args, **self._kwargs)
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "x", ",", "self", ".", "y", ",", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")" ]
Returns: Copy of Spectrum object.
[ "Returns", ":", "Copy", "of", "Spectrum", "object", "." ]
python
train
alex-kostirin/pyatomac
atomac/ldtpd/core.py
https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L80-L103
def getapplist(self): """ Get all accessibility application name that are currently running @return: list of appliction name of string type on success. @rtype: list """ app_list = [] # Update apps list, before parsing the list self._update_apps() ...
[ "def", "getapplist", "(", "self", ")", ":", "app_list", "=", "[", "]", "# Update apps list, before parsing the list", "self", ".", "_update_apps", "(", ")", "for", "gui", "in", "self", ".", "_running_apps", ":", "name", "=", "gui", ".", "localizedName", "(", ...
Get all accessibility application name that are currently running @return: list of appliction name of string type on success. @rtype: list
[ "Get", "all", "accessibility", "application", "name", "that", "are", "currently", "running" ]
python
valid
ninjaaron/libaaron
libaaron/libaaron.py
https://github.com/ninjaaron/libaaron/blob/a2ee417b784ca72c89c05bddb2e3e815a6b95154/libaaron/libaaron.py#L258-L266
def pipeline(*functions, funcs=None): """like pipe, but curried: pipline(f, g, h)(*args, **kwargs) == h(g(f(*args, **kwargs))) """ if funcs: functions = funcs head, *tail = functions return lambda *args, **kwargs: pipe(head(*args, **kwargs), funcs=tail)
[ "def", "pipeline", "(", "*", "functions", ",", "funcs", "=", "None", ")", ":", "if", "funcs", ":", "functions", "=", "funcs", "head", ",", "", "*", "tail", "=", "functions", "return", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "pipe", "("...
like pipe, but curried: pipline(f, g, h)(*args, **kwargs) == h(g(f(*args, **kwargs)))
[ "like", "pipe", "but", "curried", ":" ]
python
test
apache/incubator-superset
superset/views/core.py
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2771-L2828
def search_queries(self) -> Response: """ Search for previously run sqllab queries. Used for Sqllab Query Search page /superset/sqllab#search. Custom permission can_only_search_queries_owned restricts queries to only queries run by current user. :returns: Response with ...
[ "def", "search_queries", "(", "self", ")", "->", "Response", ":", "query", "=", "db", ".", "session", ".", "query", "(", "Query", ")", "if", "security_manager", ".", "can_only_access_owned_queries", "(", ")", ":", "search_user_id", "=", "g", ".", "user", "...
Search for previously run sqllab queries. Used for Sqllab Query Search page /superset/sqllab#search. Custom permission can_only_search_queries_owned restricts queries to only queries run by current user. :returns: Response with list of sql query dicts
[ "Search", "for", "previously", "run", "sqllab", "queries", ".", "Used", "for", "Sqllab", "Query", "Search", "page", "/", "superset", "/", "sqllab#search", "." ]
python
train
major/supernova
supernova/supernova.py
https://github.com/major/supernova/blob/4a217ae53c1c05567014b047c0b6b9dea2d383b3/supernova/supernova.py#L91-L103
def handle_stderr(stderr_pipe): """ Takes stderr from the command's output and displays it AFTER the stdout is printed by run_command(). """ stderr_output = stderr_pipe.read() if len(stderr_output) > 0: click.secho("\n__ Error Output {0}".format('_'*62), fg='white', ...
[ "def", "handle_stderr", "(", "stderr_pipe", ")", ":", "stderr_output", "=", "stderr_pipe", ".", "read", "(", ")", "if", "len", "(", "stderr_output", ")", ">", "0", ":", "click", ".", "secho", "(", "\"\\n__ Error Output {0}\"", ".", "format", "(", "'_'", "*...
Takes stderr from the command's output and displays it AFTER the stdout is printed by run_command().
[ "Takes", "stderr", "from", "the", "command", "s", "output", "and", "displays", "it", "AFTER", "the", "stdout", "is", "printed", "by", "run_command", "()", "." ]
python
train
spencerahill/aospy
aospy/utils/vertcoord.py
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L167-L228
def dp_from_p(p, ps, p_top=0., p_bot=1.1e5): """Get level thickness of pressure data, incorporating surface pressure. Level edges are defined as halfway between the levels, as well as the user- specified uppermost and lowermost values. The dp of levels whose bottom pressure is less than the surface pr...
[ "def", "dp_from_p", "(", "p", ",", "ps", ",", "p_top", "=", "0.", ",", "p_bot", "=", "1.1e5", ")", ":", "p_str", "=", "get_dim_name", "(", "p", ",", "(", "internal_names", ".", "PLEVEL_STR", ",", "'plev'", ")", ")", "p_vals", "=", "to_pascal", "(", ...
Get level thickness of pressure data, incorporating surface pressure. Level edges are defined as halfway between the levels, as well as the user- specified uppermost and lowermost values. The dp of levels whose bottom pressure is less than the surface pressure is not changed by ps, since they don't in...
[ "Get", "level", "thickness", "of", "pressure", "data", "incorporating", "surface", "pressure", "." ]
python
train
NewKnowledge/punk
punk/feature_selection/pca.py
https://github.com/NewKnowledge/punk/blob/b5c96aeea74728fc64290bb0f6dabc97b827e4e9/punk/feature_selection/pca.py#L9-L61
def rank_features(self, inputs: pd.DataFrame) -> pd.DataFrame: """ Perform PCA and return a list of the indices of the most important features, ordered by contribution to first PCA component The matrix M will corres...
[ "def", "rank_features", "(", "self", ",", "inputs", ":", "pd", ".", "DataFrame", ")", "->", "pd", ".", "DataFrame", ":", "pca", "=", "PCA", "(", ")", "try", ":", "pca", ".", "fit", "(", "normalize", "(", "inputs", ".", "apply", "(", "pd", ".", "t...
Perform PCA and return a list of the indices of the most important features, ordered by contribution to first PCA component The matrix M will correspond to the absolute value of the components of the decomposiiton ...
[ "Perform", "PCA", "and", "return", "a", "list", "of", "the", "indices", "of", "the", "most", "important", "features", "ordered", "by", "contribution", "to", "first", "PCA", "component", "The", "matrix", "M", "will", "correspond", "to", "the", "absolute", "va...
python
train
dbtsai/python-mimeparse
mimeparse.py
https://github.com/dbtsai/python-mimeparse/blob/cf605c0994149b1a1936b3a8a597203fe3fbb62e/mimeparse.py#L14-L39
def parse_mime_type(mime_type): """Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed ...
[ "def", "parse_mime_type", "(", "mime_type", ")", ":", "full_type", ",", "params", "=", "cgi", ".", "parse_header", "(", "mime_type", ")", "# Java URLConnection class sends an Accept header that includes a", "# single '*'. Turn it into a legal wildcard.", "if", "full_type", "=...
Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', ...
[ "Parses", "a", "mime", "-", "type", "into", "its", "component", "parts", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L300-L308
def interrupt_then_kill(self, delay=2.0): """Send INT, wait a delay and then send KILL.""" try: self.signal(SIGINT) except Exception: self.log.debug("interrupt failed") pass self.killer = ioloop.DelayedCallback(lambda : self.signal(SIGKILL), delay*100...
[ "def", "interrupt_then_kill", "(", "self", ",", "delay", "=", "2.0", ")", ":", "try", ":", "self", ".", "signal", "(", "SIGINT", ")", "except", "Exception", ":", "self", ".", "log", ".", "debug", "(", "\"interrupt failed\"", ")", "pass", "self", ".", "...
Send INT, wait a delay and then send KILL.
[ "Send", "INT", "wait", "a", "delay", "and", "then", "send", "KILL", "." ]
python
test
wummel/dosage
dosagelib/events.py
https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/dosagelib/events.py#L310-L314
def addHandler(name, basepath=None, baseurl=None, allowDownscale=False): """Add an event handler with given name.""" if basepath is None: basepath = '.' _handlers.append(_handler_classes[name](basepath, baseurl, allowDownscale))
[ "def", "addHandler", "(", "name", ",", "basepath", "=", "None", ",", "baseurl", "=", "None", ",", "allowDownscale", "=", "False", ")", ":", "if", "basepath", "is", "None", ":", "basepath", "=", "'.'", "_handlers", ".", "append", "(", "_handler_classes", ...
Add an event handler with given name.
[ "Add", "an", "event", "handler", "with", "given", "name", "." ]
python
train
samuraisam/django-json-rpc
jsonrpc/proxy.py
https://github.com/samuraisam/django-json-rpc/blob/a88d744d960e828f3eb21265da0f10a694b8ebcf/jsonrpc/proxy.py#L28-L53
def send_payload(self, params): """Performs the actual sending action and returns the result""" data = dumps({ 'jsonrpc': self.version, 'method': self.service_name, 'params': params, 'id': str(uuid.uuid1()) }).encode('utf-8') headers = { ...
[ "def", "send_payload", "(", "self", ",", "params", ")", ":", "data", "=", "dumps", "(", "{", "'jsonrpc'", ":", "self", ".", "version", ",", "'method'", ":", "self", ".", "service_name", ",", "'params'", ":", "params", ",", "'id'", ":", "str", "(", "u...
Performs the actual sending action and returns the result
[ "Performs", "the", "actual", "sending", "action", "and", "returns", "the", "result" ]
python
train
opinkerfi/nago
nago/extensions/checkresults.py
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/checkresults.py#L31-L69
def post(hosts=None, services=None, check_existance=True, create_services=True, create_hosts=False): """ Puts a list of hosts into local instance of nagios checkresults Arguments: hosts -- list of dicts, like one obtained from get_checkresults services -- list of dicts, like...
[ "def", "post", "(", "hosts", "=", "None", ",", "services", "=", "None", ",", "check_existance", "=", "True", ",", "create_services", "=", "True", ",", "create_hosts", "=", "False", ")", ":", "nagios_config", "=", "config", "(", ")", "nagios_config", ".", ...
Puts a list of hosts into local instance of nagios checkresults Arguments: hosts -- list of dicts, like one obtained from get_checkresults services -- list of dicts, like one obtained from get_checkresults check_existance -- If True, check (and log) if objects already ...
[ "Puts", "a", "list", "of", "hosts", "into", "local", "instance", "of", "nagios", "checkresults", "Arguments", ":", "hosts", "--", "list", "of", "dicts", "like", "one", "obtained", "from", "get_checkresults", "services", "--", "list", "of", "dicts", "like", "...
python
train
slackapi/python-slackclient
slack/web/client.py
https://github.com/slackapi/python-slackclient/blob/901341c0284fd81e6d2719d6a0502308760d83e4/slack/web/client.py#L600-L603
def files_list(self, **kwargs) -> SlackResponse: """Lists & filters team files.""" self._validate_xoxp_token() return self.api_call("files.list", http_verb="GET", params=kwargs)
[ "def", "files_list", "(", "self", ",", "*", "*", "kwargs", ")", "->", "SlackResponse", ":", "self", ".", "_validate_xoxp_token", "(", ")", "return", "self", ".", "api_call", "(", "\"files.list\"", ",", "http_verb", "=", "\"GET\"", ",", "params", "=", "kwar...
Lists & filters team files.
[ "Lists", "&", "filters", "team", "files", "." ]
python
train
cnt-dev/cnt.rulebase
cnt/rulebase/const/utils.py
https://github.com/cnt-dev/cnt.rulebase/blob/d1c767c356d8ee05b23ec5b04aaac84784ee547c/cnt/rulebase/const/utils.py#L12-L24
def normalize_cjk_fullwidth_ascii(seq: str) -> str: """ Conver fullwith ASCII to halfwidth ASCII. See https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms """ def convert(char: str) -> str: code_point = ord(char) if not 0xFF01 <= code_point <= 0xFF5E: return char ...
[ "def", "normalize_cjk_fullwidth_ascii", "(", "seq", ":", "str", ")", "->", "str", ":", "def", "convert", "(", "char", ":", "str", ")", "->", "str", ":", "code_point", "=", "ord", "(", "char", ")", "if", "not", "0xFF01", "<=", "code_point", "<=", "0xFF5...
Conver fullwith ASCII to halfwidth ASCII. See https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms
[ "Conver", "fullwith", "ASCII", "to", "halfwidth", "ASCII", ".", "See", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Halfwidth_and_fullwidth_forms" ]
python
train
user-cont/conu
conu/backend/podman/backend.py
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/backend.py#L36-L52
def parse_reference(reference): """ parse provided image reference into <image_repository>:<tag> :param reference: str, e.g. (registry.fedoraproject.org/fedora:27) :return: collection (tuple or list), ("registry.fedoraproject.org/fedora", "27") """ if ":" in reference: im, tag = referen...
[ "def", "parse_reference", "(", "reference", ")", ":", "if", "\":\"", "in", "reference", ":", "im", ",", "tag", "=", "reference", ".", "rsplit", "(", "\":\"", ",", "1", ")", "if", "\"/\"", "in", "tag", ":", "# this is case when there is port in the registry URI...
parse provided image reference into <image_repository>:<tag> :param reference: str, e.g. (registry.fedoraproject.org/fedora:27) :return: collection (tuple or list), ("registry.fedoraproject.org/fedora", "27")
[ "parse", "provided", "image", "reference", "into", "<image_repository", ">", ":", "<tag", ">" ]
python
train
zarr-developers/zarr
zarr/core.py
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1117-L1210
def set_basic_selection(self, selection, value, fields=None): """Modify data for an item or region of the array. Parameters ---------- selection : tuple An integer index or slice or tuple of int/slice specifying the requested region for each dimension of the arra...
[ "def", "set_basic_selection", "(", "self", ",", "selection", ",", "value", ",", "fields", "=", "None", ")", ":", "# guard conditions", "if", "self", ".", "_read_only", ":", "err_read_only", "(", ")", "# refresh metadata", "if", "not", "self", ".", "_cache_meta...
Modify data for an item or region of the array. Parameters ---------- selection : tuple An integer index or slice or tuple of int/slice specifying the requested region for each dimension of the array. value : scalar or array-like Value to be stored in...
[ "Modify", "data", "for", "an", "item", "or", "region", "of", "the", "array", "." ]
python
train
mwickert/scikit-dsp-comm
sk_dsp_comm/rtlsdr_helper.py
https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/rtlsdr_helper.py#L305-L340
def fsk_BEP(rx_data,m,flip): """ fsk_BEP(rx_data,m,flip) Estimate the BEP of the data bits recovered by the RTL-SDR Based FSK Receiver. The reference m-sequence generated in Python was found to produce sequences running in the opposite direction relative to the m-sequence...
[ "def", "fsk_BEP", "(", "rx_data", ",", "m", ",", "flip", ")", ":", "Nbits", "=", "len", "(", "rx_data", ")", "c", "=", "dc", ".", "m_seq", "(", "m", ")", "if", "flip", "==", "1", ":", "# Flip the sequence to compenstate for mbed code difference\r", "# Firs...
fsk_BEP(rx_data,m,flip) Estimate the BEP of the data bits recovered by the RTL-SDR Based FSK Receiver. The reference m-sequence generated in Python was found to produce sequences running in the opposite direction relative to the m-sequences generated by the mbed. To allow erro...
[ "fsk_BEP", "(", "rx_data", "m", "flip", ")", "Estimate", "the", "BEP", "of", "the", "data", "bits", "recovered", "by", "the", "RTL", "-", "SDR", "Based", "FSK", "Receiver", ".", "The", "reference", "m", "-", "sequence", "generated", "in", "Python", "was"...
python
valid
ethereum/py-evm
eth/vm/logic/comparison.py
https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/comparison.py#L145-L156
def byte_op(computation: BaseComputation) -> None: """ Bitwise And """ position, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256) if position >= 32: result = 0 else: result = (value // pow(256, 31 - position)) % 256 computation.stack_push(result)
[ "def", "byte_op", "(", "computation", ":", "BaseComputation", ")", "->", "None", ":", "position", ",", "value", "=", "computation", ".", "stack_pop", "(", "num_items", "=", "2", ",", "type_hint", "=", "constants", ".", "UINT256", ")", "if", "position", ">=...
Bitwise And
[ "Bitwise", "And" ]
python
train
CiscoUcs/UcsPythonSDK
src/UcsSdk/UcsBase.py
https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L721-L757
def DownloadFile(hUcs, source, destination): """ Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to download the files from the Ucs. """ import urllib2 from sys import stdout from time import sleep httpAddress = "%s/%s" % (hUcs.Uri(),...
[ "def", "DownloadFile", "(", "hUcs", ",", "source", ",", "destination", ")", ":", "import", "urllib2", "from", "sys", "import", "stdout", "from", "time", "import", "sleep", "httpAddress", "=", "\"%s/%s\"", "%", "(", "hUcs", ".", "Uri", "(", ")", ",", "sou...
Method provides the functionality to download file from the UCS. This method is used in BackupUcs and GetTechSupport to download the files from the Ucs.
[ "Method", "provides", "the", "functionality", "to", "download", "file", "from", "the", "UCS", ".", "This", "method", "is", "used", "in", "BackupUcs", "and", "GetTechSupport", "to", "download", "the", "files", "from", "the", "Ucs", "." ]
python
train
dhermes/bezier
src/bezier/_helpers.py
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_helpers.py#L135-L159
def _contains_nd(nodes, point): r"""Predicate indicating if a point is within a bounding box. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. point (numpy.ndarray): A 1D Num...
[ "def", "_contains_nd", "(", "nodes", ",", "point", ")", ":", "min_vals", "=", "np", ".", "min", "(", "nodes", ",", "axis", "=", "1", ")", "if", "not", "np", ".", "all", "(", "min_vals", "<=", "point", ")", ":", "return", "False", "max_vals", "=", ...
r"""Predicate indicating if a point is within a bounding box. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. point (numpy.ndarray): A 1D NumPy array representing a point ...
[ "r", "Predicate", "indicating", "if", "a", "point", "is", "within", "a", "bounding", "box", "." ]
python
train
thriftrw/thriftrw-python
thriftrw/idl/parser.py
https://github.com/thriftrw/thriftrw-python/blob/4f2f71acd7a0ac716c9ea5cdcea2162aa561304a/thriftrw/idl/parser.py#L68-L74
def p_include(self, p): '''include : INCLUDE IDENTIFIER LITERAL | INCLUDE LITERAL''' if len(p) == 4: p[0] = ast.Include(name=p[2], path=p[3], lineno=p.lineno(1)) else: p[0] = ast.Include(name=None, path=p[2], lineno=p.lineno(1))
[ "def", "p_include", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "4", ":", "p", "[", "0", "]", "=", "ast", ".", "Include", "(", "name", "=", "p", "[", "2", "]", ",", "path", "=", "p", "[", "3", "]", ",", "lineno", ...
include : INCLUDE IDENTIFIER LITERAL | INCLUDE LITERAL
[ "include", ":", "INCLUDE", "IDENTIFIER", "LITERAL", "|", "INCLUDE", "LITERAL" ]
python
train
darkowlzz/pokemonNames
pokemonNames/pokemonNames.py
https://github.com/darkowlzz/pokemonNames/blob/fe4b9cf2108115c8a090193247413dcb5416fcff/pokemonNames/pokemonNames.py#L69-L90
def append_to_list(self, source, start=None, hasIndex=False): '''Appends new list to self.nameDict Argument: source -- source of new name list (filename or list) start -- starting index of new list hasIndex -- the file is already indexed ''' nfy = Numberify() ...
[ "def", "append_to_list", "(", "self", ",", "source", ",", "start", "=", "None", ",", "hasIndex", "=", "False", ")", ":", "nfy", "=", "Numberify", "(", ")", "try", ":", "if", "start", "is", "None", ":", "if", "type", "(", "source", ")", "is", "str",...
Appends new list to self.nameDict Argument: source -- source of new name list (filename or list) start -- starting index of new list hasIndex -- the file is already indexed
[ "Appends", "new", "list", "to", "self", ".", "nameDict", "Argument", ":", "source", "--", "source", "of", "new", "name", "list", "(", "filename", "or", "list", ")", "start", "--", "starting", "index", "of", "new", "list", "hasIndex", "--", "the", "file",...
python
train
rndusr/torf
torf/_torrent.py
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L258-L274
def piece_size(self): """ Piece size/length or ``None`` If set to ``None``, :attr:`calculate_piece_size` is called. If :attr:`size` returns ``None``, this also returns ``None``. Setting this property sets ``piece length`` in :attr:`metainfo`\ ``['info']``. """ ...
[ "def", "piece_size", "(", "self", ")", ":", "if", "'piece length'", "not", "in", "self", ".", "metainfo", "[", "'info'", "]", ":", "if", "self", ".", "size", "is", "None", ":", "return", "None", "else", ":", "self", ".", "calculate_piece_size", "(", ")...
Piece size/length or ``None`` If set to ``None``, :attr:`calculate_piece_size` is called. If :attr:`size` returns ``None``, this also returns ``None``. Setting this property sets ``piece length`` in :attr:`metainfo`\ ``['info']``.
[ "Piece", "size", "/", "length", "or", "None" ]
python
train
ansible/tower-cli
tower_cli/models/base.py
https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/models/base.py#L1135-L1173
def relaunch(self, pk=None, **kwargs): """Relaunch a stopped job. Fails with a non-zero exit status if the job cannot be relaunched. You must provide either a pk or parameters in the job's identity. =====API DOCS===== Relaunch a stopped job resource. :param pk: Primary...
[ "def", "relaunch", "(", "self", ",", "pk", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Search for the record if pk not given", "if", "not", "pk", ":", "existing_data", "=", "self", ".", "get", "(", "*", "*", "kwargs", ")", "pk", "=", "existing_dat...
Relaunch a stopped job. Fails with a non-zero exit status if the job cannot be relaunched. You must provide either a pk or parameters in the job's identity. =====API DOCS===== Relaunch a stopped job resource. :param pk: Primary key of the job resource to relaunch. :typ...
[ "Relaunch", "a", "stopped", "job", "." ]
python
valid
michael-lazar/rtv
rtv/packages/praw/__init__.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L1579-L1606
def set_access_credentials(self, scope, access_token, refresh_token=None, update_user=True): """Set the credentials used for OAuth2 authentication. Calling this function will overwrite any currently existing access credentials. :param scope: A set of redd...
[ "def", "set_access_credentials", "(", "self", ",", "scope", ",", "access_token", ",", "refresh_token", "=", "None", ",", "update_user", "=", "True", ")", ":", "if", "isinstance", "(", "scope", ",", "(", "list", ",", "tuple", ")", ")", ":", "scope", "=", ...
Set the credentials used for OAuth2 authentication. Calling this function will overwrite any currently existing access credentials. :param scope: A set of reddit scopes the tokens provide access to :param access_token: the access token of the authentication :param refresh_token...
[ "Set", "the", "credentials", "used", "for", "OAuth2", "authentication", "." ]
python
train
bennylope/django-organizations
organizations/backends/defaults.py
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L153-L161
def send_reminder(self, user, sender=None, **kwargs): """Sends a reminder email to the specified user""" if user.is_active: return False token = RegistrationTokenGenerator().make_token(user) kwargs.update({"token": token}) self.email_message( user, self.re...
[ "def", "send_reminder", "(", "self", ",", "user", ",", "sender", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "user", ".", "is_active", ":", "return", "False", "token", "=", "RegistrationTokenGenerator", "(", ")", ".", "make_token", "(", "user",...
Sends a reminder email to the specified user
[ "Sends", "a", "reminder", "email", "to", "the", "specified", "user" ]
python
train
lreis2415/PyGeoC
examples/ex08_raster_connectivity_analysis.py
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/examples/ex08_raster_connectivity_analysis.py#L91-L110
def draw_ID(ID, idx_array, drawID_raster): """Draw every pixel's ID After computing all given value's pixels connectivity, every pixel will have an ID. Then we need to draw these pixels' ID on the undrawed rasterfile. Args: ID: given ID value idx_array: pixels position set...
[ "def", "draw_ID", "(", "ID", ",", "idx_array", ",", "drawID_raster", ")", ":", "for", "i", "in", "range", "(", "idx_array", ".", "shape", "[", "0", "]", ")", ":", "x", "=", "idx_array", "[", "i", ",", "0", "]", "y", "=", "idx_array", "[", "i", ...
Draw every pixel's ID After computing all given value's pixels connectivity, every pixel will have an ID. Then we need to draw these pixels' ID on the undrawed rasterfile. Args: ID: given ID value idx_array: pixels position set which have the given ID value drawID_rast...
[ "Draw", "every", "pixel", "s", "ID", "After", "computing", "all", "given", "value", "s", "pixels", "connectivity", "every", "pixel", "will", "have", "an", "ID", ".", "Then", "we", "need", "to", "draw", "these", "pixels", "ID", "on", "the", "undrawed", "r...
python
train
boundary/pulse-api-cli
boundary/metric_markdown.py
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/metric_markdown.py#L116-L125
def getMetricsColumnLengths(self): """ Gets the maximum length of each column """ displayLen = 0 descLen = 0 for m in self.metrics: displayLen = max(displayLen, len(m['displayName'])) descLen = max(descLen, len(m['description'])) return (di...
[ "def", "getMetricsColumnLengths", "(", "self", ")", ":", "displayLen", "=", "0", "descLen", "=", "0", "for", "m", "in", "self", ".", "metrics", ":", "displayLen", "=", "max", "(", "displayLen", ",", "len", "(", "m", "[", "'displayName'", "]", ")", ")",...
Gets the maximum length of each column
[ "Gets", "the", "maximum", "length", "of", "each", "column" ]
python
test
lsst-sqre/lsst-projectmeta-kit
lsstprojectmeta/github/graphql.py
https://github.com/lsst-sqre/lsst-projectmeta-kit/blob/ac8d4ff65bb93d8fdeb1b46ae6eb5d7414f1ae14/lsstprojectmeta/github/graphql.py#L80-L106
def load(cls, query_name): """Load a pre-made query. These queries are distributed with lsstprojectmeta. See :file:`lsstrojectmeta/data/githubv4/README.rst` inside the package repository for details on available queries. Parameters ---------- query_name : `str` ...
[ "def", "load", "(", "cls", ",", "query_name", ")", ":", "template_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../data/githubv4'", ",", "query_name", "+", "'.graphql'", ")", "with", "o...
Load a pre-made query. These queries are distributed with lsstprojectmeta. See :file:`lsstrojectmeta/data/githubv4/README.rst` inside the package repository for details on available queries. Parameters ---------- query_name : `str` Name of the query, such as...
[ "Load", "a", "pre", "-", "made", "query", "." ]
python
valid
twilio/twilio-python
twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py#L40-L53
def calls(self): """ Access the calls :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList """ if self._calls is None: ...
[ "def", "calls", "(", "self", ")", ":", "if", "self", ".", "_calls", "is", "None", ":", "self", ".", "_calls", "=", "AuthTypeCallsList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "do...
Access the calls :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsList
[ "Access", "the", "calls" ]
python
train
Yelp/detect-secrets
detect_secrets/plugins/common/ini_file_parser.py
https://github.com/Yelp/detect-secrets/blob/473923ea71f1ac2b5ea1eacc49b98f97967e3d05/detect_secrets/plugins/common/ini_file_parser.py#L82-L153
def _get_value_and_line_offset(self, key, values): """Returns the index of the location of key, value pair in lines. :type key: str :param key: key, in config file. :type values: str :param values: values for key, in config file. This is plural, because you can have...
[ "def", "_get_value_and_line_offset", "(", "self", ",", "key", ",", "values", ")", ":", "values_list", "=", "self", ".", "_construct_values_list", "(", "values", ")", "if", "not", "values_list", ":", "return", "[", "]", "current_value_list_index", "=", "0", "ou...
Returns the index of the location of key, value pair in lines. :type key: str :param key: key, in config file. :type values: str :param values: values for key, in config file. This is plural, because you can have multiple values per key. e.g. >>> key = ...
[ "Returns", "the", "index", "of", "the", "location", "of", "key", "value", "pair", "in", "lines", "." ]
python
train
slundberg/shap
shap/benchmark/metrics.py
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/metrics.py#L324-L331
def remove_absolute_impute__r2(X, y, model_generator, method_name, num_fcounts=11): """ Remove Absolute (impute) xlabel = "Max fraction of features removed" ylabel = "1 - R^2" transform = "one_minus" sort_order = 9 """ return __run_measure(measures.remove_impute, X, y, model_generator, metho...
[ "def", "remove_absolute_impute__r2", "(", "X", ",", "y", ",", "model_generator", ",", "method_name", ",", "num_fcounts", "=", "11", ")", ":", "return", "__run_measure", "(", "measures", ".", "remove_impute", ",", "X", ",", "y", ",", "model_generator", ",", "...
Remove Absolute (impute) xlabel = "Max fraction of features removed" ylabel = "1 - R^2" transform = "one_minus" sort_order = 9
[ "Remove", "Absolute", "(", "impute", ")", "xlabel", "=", "Max", "fraction", "of", "features", "removed", "ylabel", "=", "1", "-", "R^2", "transform", "=", "one_minus", "sort_order", "=", "9" ]
python
train
ShadowBlip/Neteria
neteria/core.py
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L324-L360
def send_datagram(self, message, address, message_type="unicast"): """Sends a UDP datagram packet to the requested address. Datagrams can be sent as a "unicast", "multicast", or "broadcast" message. Unicast messages are messages that will be sent to a single host, multicast messages wil...
[ "def", "send_datagram", "(", "self", ",", "message", ",", "address", ",", "message_type", "=", "\"unicast\"", ")", ":", "if", "self", ".", "bufsize", "is", "not", "0", "and", "len", "(", "message", ")", ">", "self", ".", "bufsize", ":", "raise", "Excep...
Sends a UDP datagram packet to the requested address. Datagrams can be sent as a "unicast", "multicast", or "broadcast" message. Unicast messages are messages that will be sent to a single host, multicast messages will be delivered to all hosts listening for multicast messages, and broa...
[ "Sends", "a", "UDP", "datagram", "packet", "to", "the", "requested", "address", "." ]
python
train
Nekroze/partpy
partpy/sourcestring.py
https://github.com/Nekroze/partpy/blob/dbb7d2fb285464fc43d85bc31f5af46192d301f6/partpy/sourcestring.py#L212-L233
def get_current_line(self): """Return a SourceLine of the current line.""" if not self.has_space(): return None pos = self.pos - self.col string = self.string end = self.length output = [] while pos < len(string) and string[pos] != '\n': ...
[ "def", "get_current_line", "(", "self", ")", ":", "if", "not", "self", ".", "has_space", "(", ")", ":", "return", "None", "pos", "=", "self", ".", "pos", "-", "self", ".", "col", "string", "=", "self", ".", "string", "end", "=", "self", ".", "lengt...
Return a SourceLine of the current line.
[ "Return", "a", "SourceLine", "of", "the", "current", "line", "." ]
python
train
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L350-L355
def newLine(self) : """Appends an empty line at the end of the CSV and returns it""" l = CSVEntry(self) if self.keepInMemory : self.lines.append(l) return l
[ "def", "newLine", "(", "self", ")", ":", "l", "=", "CSVEntry", "(", "self", ")", "if", "self", ".", "keepInMemory", ":", "self", ".", "lines", ".", "append", "(", "l", ")", "return", "l" ]
Appends an empty line at the end of the CSV and returns it
[ "Appends", "an", "empty", "line", "at", "the", "end", "of", "the", "CSV", "and", "returns", "it" ]
python
train
lemieuxl/pyGenClean
pyGenClean/Ethnicity/find_outliers.py
https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/Ethnicity/find_outliers.py#L620-L649
def checkArgs(args): """Checks the arguments and options. :param args: a :py:class:`argparse.Namespace` object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is rai...
[ "def", "checkArgs", "(", "args", ")", ":", "# Checking the input files", "if", "not", "os", ".", "path", ".", "isfile", "(", "args", ".", "mds", ")", ":", "msg", "=", "\"{}: no such file\"", ".", "format", "(", "args", ".", "mds", ")", "raise", "ProgramE...
Checks the arguments and options. :param args: a :py:class:`argparse.Namespace` object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:...
[ "Checks", "the", "arguments", "and", "options", "." ]
python
train
newfies-dialer/python-msspeak
msspeak/command_line.py
https://github.com/newfies-dialer/python-msspeak/blob/106475122be73df152865c4fe6e9388caf974085/msspeak/command_line.py#L40-L51
def validate_options(subscription_key, text): """ Perform sanity checks on threshold values """ if not subscription_key or len(subscription_key) == 0: print 'Error: Warning the option subscription_key should contain a string.' print USAGE sys.exit(3) if not text or len(text) ...
[ "def", "validate_options", "(", "subscription_key", ",", "text", ")", ":", "if", "not", "subscription_key", "or", "len", "(", "subscription_key", ")", "==", "0", ":", "print", "'Error: Warning the option subscription_key should contain a string.'", "print", "USAGE", "sy...
Perform sanity checks on threshold values
[ "Perform", "sanity", "checks", "on", "threshold", "values" ]
python
train
instaloader/instaloader
instaloader/instaloader.py
https://github.com/instaloader/instaloader/blob/87d877e650cd8020b04b8b51be120599a441fd5b/instaloader/instaloader.py#L94-L102
def format_field(self, value, format_spec): """Override :meth:`string.Formatter.format_field` to have our default format_spec for :class:`datetime.Datetime` objects, and to let None yield an empty string rather than ``None``.""" if isinstance(value, datetime) and not format_spec: ...
[ "def", "format_field", "(", "self", ",", "value", ",", "format_spec", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ")", "and", "not", "format_spec", ":", "return", "super", "(", ")", ".", "format_field", "(", "value", ",", "'%Y-%m-%d_%H-%M-...
Override :meth:`string.Formatter.format_field` to have our default format_spec for :class:`datetime.Datetime` objects, and to let None yield an empty string rather than ``None``.
[ "Override", ":", "meth", ":", "string", ".", "Formatter", ".", "format_field", "to", "have", "our", "default", "format_spec", "for", ":", "class", ":", "datetime", ".", "Datetime", "objects", "and", "to", "let", "None", "yield", "an", "empty", "string", "r...
python
train
sony/nnabla
python/src/nnabla/models/imagenet/base.py
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/models/imagenet/base.py#L49-L67
def _load_nnp(self, rel_name, rel_url): ''' Args: rel_name: relative path to where donwloaded nnp is saved. rel_url: relative url path to where nnp is downloaded from. ''' from nnabla.utils.download import download path_nnp = os.path.join(...
[ "def", "_load_nnp", "(", "self", ",", "rel_name", ",", "rel_url", ")", ":", "from", "nnabla", ".", "utils", ".", "download", "import", "download", "path_nnp", "=", "os", ".", "path", ".", "join", "(", "get_model_home", "(", ")", ",", "'imagenet/{}'", "."...
Args: rel_name: relative path to where donwloaded nnp is saved. rel_url: relative url path to where nnp is downloaded from.
[ "Args", ":", "rel_name", ":", "relative", "path", "to", "where", "donwloaded", "nnp", "is", "saved", ".", "rel_url", ":", "relative", "url", "path", "to", "where", "nnp", "is", "downloaded", "from", "." ]
python
train
gem/oq-engine
openquake/hmtk/plotting/mapping.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/mapping.py#L337-L361
def add_source_model( self, model, area_border='k-', border_width=1.0, point_marker='ks', point_size=2.0, overlay=False, min_depth=0., max_depth=None, alpha=1.0): """ Adds a source model to the map :param model: Source model of mixed typologies as...
[ "def", "add_source_model", "(", "self", ",", "model", ",", "area_border", "=", "'k-'", ",", "border_width", "=", "1.0", ",", "point_marker", "=", "'ks'", ",", "point_size", "=", "2.0", ",", "overlay", "=", "False", ",", "min_depth", "=", "0.", ",", "max_...
Adds a source model to the map :param model: Source model of mixed typologies as instance of :class: openquake.hmtk.sources.source_model.mtkSourceModel
[ "Adds", "a", "source", "model", "to", "the", "map" ]
python
train
kgori/treeCl
treeCl/tree.py
https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/tree.py#L1012-L1034
def randomise_branch_lengths( self, i=(1, 1), l=(1, 1), distribution_func=random.gammavariate, inplace=False, ): """ Replaces branch lengths with values drawn from the specified distribution_func. Parameters of the distribution are given in...
[ "def", "randomise_branch_lengths", "(", "self", ",", "i", "=", "(", "1", ",", "1", ")", ",", "l", "=", "(", "1", ",", "1", ")", ",", "distribution_func", "=", "random", ".", "gammavariate", ",", "inplace", "=", "False", ",", ")", ":", "if", "not", ...
Replaces branch lengths with values drawn from the specified distribution_func. Parameters of the distribution are given in the tuples i and l, for interior and leaf nodes respectively.
[ "Replaces", "branch", "lengths", "with", "values", "drawn", "from", "the", "specified", "distribution_func", ".", "Parameters", "of", "the", "distribution", "are", "given", "in", "the", "tuples", "i", "and", "l", "for", "interior", "and", "leaf", "nodes", "res...
python
train
raiden-network/raiden
raiden/raiden_service.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L911-L936
def _initialize_messages_queues(self, chain_state: ChainState): """Initialize all the message queues with the transport. Note: All messages from the state queues must be pushed to the transport before it's started. This is necessary to avoid a race where the transpor...
[ "def", "_initialize_messages_queues", "(", "self", ",", "chain_state", ":", "ChainState", ")", ":", "assert", "not", "self", ".", "transport", ",", "f'Transport is running. node:{self!r}'", "assert", "self", ".", "alarm", ".", "is_primed", "(", ")", ",", "f'AlarmT...
Initialize all the message queues with the transport. Note: All messages from the state queues must be pushed to the transport before it's started. This is necessary to avoid a race where the transport processes network messages too quickly, queueing new messages...
[ "Initialize", "all", "the", "message", "queues", "with", "the", "transport", "." ]
python
train
stanfordnlp/stanza
stanza/monitoring/summary.py
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/monitoring/summary.py#L168-L179
def flush(self): ''' Force all queued events to be written to the events file. The queue will automatically be flushed at regular time intervals, when it grows too large, and at program exit (with the usual caveats of `atexit`: this won't happen if the program is killed with a ...
[ "def", "flush", "(", "self", ")", ":", "if", "self", ".", "queue", ":", "with", "open", "(", "self", ".", "filename", ",", "'ab'", ")", "as", "outfile", ":", "write_events", "(", "outfile", ",", "self", ".", "queue", ")", "del", "self", ".", "queue...
Force all queued events to be written to the events file. The queue will automatically be flushed at regular time intervals, when it grows too large, and at program exit (with the usual caveats of `atexit`: this won't happen if the program is killed with a signal or `os._exit()`).
[ "Force", "all", "queued", "events", "to", "be", "written", "to", "the", "events", "file", ".", "The", "queue", "will", "automatically", "be", "flushed", "at", "regular", "time", "intervals", "when", "it", "grows", "too", "large", "and", "at", "program", "e...
python
train
mwouts/jupytext
jupytext/formats.py
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/formats.py#L279-L299
def divine_format(text): """Guess the format of the notebook, based on its content #148""" try: nbformat.reads(text, as_version=4) return 'ipynb' except nbformat.reader.NotJSONError: pass lines = text.splitlines() for comment in ['', '#'] + _COMMENT_CHARS: metadata, ...
[ "def", "divine_format", "(", "text", ")", ":", "try", ":", "nbformat", ".", "reads", "(", "text", ",", "as_version", "=", "4", ")", "return", "'ipynb'", "except", "nbformat", ".", "reader", ".", "NotJSONError", ":", "pass", "lines", "=", "text", ".", "...
Guess the format of the notebook, based on its content #148
[ "Guess", "the", "format", "of", "the", "notebook", "based", "on", "its", "content", "#148" ]
python
train
lepture/flask-oauthlib
flask_oauthlib/provider/oauth2.py
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L98-L116
def error_uri(self): """The error page URI. When something turns error, it will redirect to this error page. You can configure the error page URI with Flask config:: OAUTH2_PROVIDER_ERROR_URI = '/error' You can also define the error page by a named endpoint:: ...
[ "def", "error_uri", "(", "self", ")", ":", "error_uri", "=", "self", ".", "app", ".", "config", ".", "get", "(", "'OAUTH2_PROVIDER_ERROR_URI'", ")", "if", "error_uri", ":", "return", "error_uri", "error_endpoint", "=", "self", ".", "app", ".", "config", "....
The error page URI. When something turns error, it will redirect to this error page. You can configure the error page URI with Flask config:: OAUTH2_PROVIDER_ERROR_URI = '/error' You can also define the error page by a named endpoint:: OAUTH2_PROVIDER_ERROR_ENDPOINT =...
[ "The", "error", "page", "URI", "." ]
python
test
nion-software/nionswift
nion/swift/model/DisplayItem.py
https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/swift/model/DisplayItem.py#L980-L998
def snapshot(self): """Return a new library item which is a copy of this one with any dynamic behavior made static.""" display_item = self.__class__() display_item.display_type = self.display_type # metadata display_item._set_persistent_property_value("title", self._get_persisten...
[ "def", "snapshot", "(", "self", ")", ":", "display_item", "=", "self", ".", "__class__", "(", ")", "display_item", ".", "display_type", "=", "self", ".", "display_type", "# metadata", "display_item", ".", "_set_persistent_property_value", "(", "\"title\"", ",", ...
Return a new library item which is a copy of this one with any dynamic behavior made static.
[ "Return", "a", "new", "library", "item", "which", "is", "a", "copy", "of", "this", "one", "with", "any", "dynamic", "behavior", "made", "static", "." ]
python
train
gc3-uzh-ch/elasticluster
elasticluster/providers/openstack.py
https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/openstack.py#L622-L636
def get_ips(self, instance_id): """Retrieves all IP addresses associated to a given instance. :return: tuple (IPs) """ self._init_os_api() instance = self._load_instance(instance_id) try: ip_addrs = set([self.floating_ip]) except AttributeError: ...
[ "def", "get_ips", "(", "self", ",", "instance_id", ")", ":", "self", ".", "_init_os_api", "(", ")", "instance", "=", "self", ".", "_load_instance", "(", "instance_id", ")", "try", ":", "ip_addrs", "=", "set", "(", "[", "self", ".", "floating_ip", "]", ...
Retrieves all IP addresses associated to a given instance. :return: tuple (IPs)
[ "Retrieves", "all", "IP", "addresses", "associated", "to", "a", "given", "instance", "." ]
python
train
rootpy/rootpy
rootpy/plotting/hist.py
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1904-L1922
def ravel(self, name=None): """ Convert 2D histogram into 1D histogram with the y-axis repeated along the x-axis, similar to NumPy's ravel(). """ nbinsx = self.nbins(0) nbinsy = self.nbins(1) left_edge = self.xedgesl(1) right_edge = self.xedgesh(nbinsx) ...
[ "def", "ravel", "(", "self", ",", "name", "=", "None", ")", ":", "nbinsx", "=", "self", ".", "nbins", "(", "0", ")", "nbinsy", "=", "self", ".", "nbins", "(", "1", ")", "left_edge", "=", "self", ".", "xedgesl", "(", "1", ")", "right_edge", "=", ...
Convert 2D histogram into 1D histogram with the y-axis repeated along the x-axis, similar to NumPy's ravel().
[ "Convert", "2D", "histogram", "into", "1D", "histogram", "with", "the", "y", "-", "axis", "repeated", "along", "the", "x", "-", "axis", "similar", "to", "NumPy", "s", "ravel", "()", "." ]
python
train
ValvePython/steam
steam/guard.py
https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/guard.py#L421-L444
def generate_twofactor_code_for_time(shared_secret, timestamp): """Generate Steam 2FA code for timestamp :param shared_secret: authenticator shared secret :type shared_secret: bytes :param timestamp: timestamp to use, if left out uses current time :type timestamp: int :return: steam two factor ...
[ "def", "generate_twofactor_code_for_time", "(", "shared_secret", ",", "timestamp", ")", ":", "hmac", "=", "hmac_sha1", "(", "bytes", "(", "shared_secret", ")", ",", "struct", ".", "pack", "(", "'>Q'", ",", "int", "(", "timestamp", ")", "//", "30", ")", ")"...
Generate Steam 2FA code for timestamp :param shared_secret: authenticator shared secret :type shared_secret: bytes :param timestamp: timestamp to use, if left out uses current time :type timestamp: int :return: steam two factor code :rtype: str
[ "Generate", "Steam", "2FA", "code", "for", "timestamp" ]
python
train
KelSolaar/Umbra
umbra/components/addons/trace_ui/trace_ui.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/addons/trace_ui/trace_ui.py#L487-L497
def __view_remove_actions(self): """ Removes the View actions. """ trace_modules_action = "Actions|Umbra|Components|addons.trace_ui|Trace Module(s)" untrace_modules_action = "Actions|Umbra|Components|addons.trace_ui|Untrace Module(s)" for action in (trace_modules_action...
[ "def", "__view_remove_actions", "(", "self", ")", ":", "trace_modules_action", "=", "\"Actions|Umbra|Components|addons.trace_ui|Trace Module(s)\"", "untrace_modules_action", "=", "\"Actions|Umbra|Components|addons.trace_ui|Untrace Module(s)\"", "for", "action", "in", "(", "trace_modu...
Removes the View actions.
[ "Removes", "the", "View", "actions", "." ]
python
train
Fizzadar/pyinfra
pyinfra/api/inventory.py
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/inventory.py#L325-L333
def get_deploy_data(self): ''' Gets any default data attached to the current deploy, if any. ''' if self.state and self.state.deploy_data: return self.state.deploy_data return {}
[ "def", "get_deploy_data", "(", "self", ")", ":", "if", "self", ".", "state", "and", "self", ".", "state", ".", "deploy_data", ":", "return", "self", ".", "state", ".", "deploy_data", "return", "{", "}" ]
Gets any default data attached to the current deploy, if any.
[ "Gets", "any", "default", "data", "attached", "to", "the", "current", "deploy", "if", "any", "." ]
python
train
BlueBrain/hpcbench
hpcbench/toolbox/env.py
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/env.py#L35-L54
def expandvars(s, vars=None): """Perform variable substitution on the given string Supported syntax: * $VARIABLE * ${VARIABLE} * ${#VARIABLE} * ${VARIABLE:-default} :param s: message to expand :type s: str :param vars: dictionary of variables. Default is ``os.environ`` :type v...
[ "def", "expandvars", "(", "s", ",", "vars", "=", "None", ")", ":", "tpl", "=", "TemplateWithDefaults", "(", "s", ")", "return", "tpl", ".", "substitute", "(", "vars", "or", "os", ".", "environ", ")" ]
Perform variable substitution on the given string Supported syntax: * $VARIABLE * ${VARIABLE} * ${#VARIABLE} * ${VARIABLE:-default} :param s: message to expand :type s: str :param vars: dictionary of variables. Default is ``os.environ`` :type vars: dict :return: expanded stri...
[ "Perform", "variable", "substitution", "on", "the", "given", "string" ]
python
train
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/records.py
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/records.py#L160-L171
def __write_record(self, record_type, data): """Write single physical record.""" length = len(data) crc = crc32c.crc_update(crc32c.CRC_INIT, [record_type]) crc = crc32c.crc_update(crc, data) crc = crc32c.crc_finalize(crc) self.__writer.write( struct.pack(_HEADER_FORMAT, _mask_crc(crc),...
[ "def", "__write_record", "(", "self", ",", "record_type", ",", "data", ")", ":", "length", "=", "len", "(", "data", ")", "crc", "=", "crc32c", ".", "crc_update", "(", "crc32c", ".", "CRC_INIT", ",", "[", "record_type", "]", ")", "crc", "=", "crc32c", ...
Write single physical record.
[ "Write", "single", "physical", "record", "." ]
python
train
tanghaibao/jcvi
jcvi/compara/quota.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/quota.py#L102-L131
def make_range(clusters, extend=0): """ Convert to interval ends from a list of anchors extend modifies the xmax, ymax boundary of the box, which can be positive or negative very useful when we want to make the range as fuzzy as we specify """ eclusters = [] for cluster in clusters: ...
[ "def", "make_range", "(", "clusters", ",", "extend", "=", "0", ")", ":", "eclusters", "=", "[", "]", "for", "cluster", "in", "clusters", ":", "xlist", ",", "ylist", ",", "scores", "=", "zip", "(", "*", "cluster", ")", "score", "=", "_score", "(", "...
Convert to interval ends from a list of anchors extend modifies the xmax, ymax boundary of the box, which can be positive or negative very useful when we want to make the range as fuzzy as we specify
[ "Convert", "to", "interval", "ends", "from", "a", "list", "of", "anchors", "extend", "modifies", "the", "xmax", "ymax", "boundary", "of", "the", "box", "which", "can", "be", "positive", "or", "negative", "very", "useful", "when", "we", "want", "to", "make"...
python
train
akaszynski/pymeshfix
pymeshfix/meshfix.py
https://github.com/akaszynski/pymeshfix/blob/51873b25d8d46168479989a528db8456af6748f4/pymeshfix/meshfix.py#L37-L74
def load_arrays(self, v, f): """Loads triangular mesh from vertex and face numpy arrays. Both vertex and face arrays should be 2D arrays with each vertex containing XYZ data and each face containing three points. Parameters ---------- v : np.ndarray ...
[ "def", "load_arrays", "(", "self", ",", "v", ",", "f", ")", ":", "# Check inputs", "if", "not", "isinstance", "(", "v", ",", "np", ".", "ndarray", ")", ":", "try", ":", "v", "=", "np", ".", "asarray", "(", "v", ",", "np", ".", "float", ")", "if...
Loads triangular mesh from vertex and face numpy arrays. Both vertex and face arrays should be 2D arrays with each vertex containing XYZ data and each face containing three points. Parameters ---------- v : np.ndarray n x 3 vertex array. f : np.ndar...
[ "Loads", "triangular", "mesh", "from", "vertex", "and", "face", "numpy", "arrays", "." ]
python
train
materialsproject/pymatgen
pymatgen/core/structure.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L134-L139
def group_by_types(self): """Iterate over species grouped by type""" for t in self.types_of_specie: for site in self: if site.specie == t: yield site
[ "def", "group_by_types", "(", "self", ")", ":", "for", "t", "in", "self", ".", "types_of_specie", ":", "for", "site", "in", "self", ":", "if", "site", ".", "specie", "==", "t", ":", "yield", "site" ]
Iterate over species grouped by type
[ "Iterate", "over", "species", "grouped", "by", "type" ]
python
train
iotile/coretools
iotilegateway/iotilegateway/supervisor/client.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L394-L406
async def register_agent(self, short_name): """Register to act as the RPC agent for this service. After this call succeeds, all requests to send RPCs to this service will be routed through this agent. Args: short_name (str): A unique short name for this service that functio...
[ "async", "def", "register_agent", "(", "self", ",", "short_name", ")", ":", "await", "self", ".", "send_command", "(", "OPERATIONS", ".", "CMD_SET_AGENT", ",", "{", "'name'", ":", "short_name", "}", ",", "MESSAGES", ".", "SetAgentResponse", ")" ]
Register to act as the RPC agent for this service. After this call succeeds, all requests to send RPCs to this service will be routed through this agent. Args: short_name (str): A unique short name for this service that functions as an id
[ "Register", "to", "act", "as", "the", "RPC", "agent", "for", "this", "service", "." ]
python
train
dbader/schedule
schedule/__init__.py
https://github.com/dbader/schedule/blob/5d2653c28b1029f1e9ddc85cd9ef26c29a79fcea/schedule/__init__.py#L96-L110
def run_all(self, delay_seconds=0): """ Run all jobs regardless if they are scheduled to run or not. A delay of `delay` seconds is added between each job. This helps distribute system load generated by the jobs more evenly over time. :param delay_seconds: A delay added ...
[ "def", "run_all", "(", "self", ",", "delay_seconds", "=", "0", ")", ":", "logger", ".", "info", "(", "'Running *all* %i jobs with %is delay inbetween'", ",", "len", "(", "self", ".", "jobs", ")", ",", "delay_seconds", ")", "for", "job", "in", "self", ".", ...
Run all jobs regardless if they are scheduled to run or not. A delay of `delay` seconds is added between each job. This helps distribute system load generated by the jobs more evenly over time. :param delay_seconds: A delay added between every executed job
[ "Run", "all", "jobs", "regardless", "if", "they", "are", "scheduled", "to", "run", "or", "not", "." ]
python
train
tnkteja/myhelp
virtualEnvironment/lib/python2.7/site-packages/pip/req/req_install.py
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/req/req_install.py#L235-L264
def correct_build_location(self): """If the build location was a temporary directory, this will move it to a new more permanent location""" if self.source_dir is not None: return assert self.req is not None assert self._temp_build_dir old_location = self._temp...
[ "def", "correct_build_location", "(", "self", ")", ":", "if", "self", ".", "source_dir", "is", "not", "None", ":", "return", "assert", "self", ".", "req", "is", "not", "None", "assert", "self", ".", "_temp_build_dir", "old_location", "=", "self", ".", "_te...
If the build location was a temporary directory, this will move it to a new more permanent location
[ "If", "the", "build", "location", "was", "a", "temporary", "directory", "this", "will", "move", "it", "to", "a", "new", "more", "permanent", "location" ]
python
test
kensho-technologies/graphql-compiler
graphql_compiler/compiler/directive_helpers.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/directive_helpers.py#L132-L137
def validate_vertex_directives(directives): """Validate the directives that appear at a vertex field.""" for directive_name in six.iterkeys(directives): if directive_name in PROPERTY_ONLY_DIRECTIVES: raise GraphQLCompilationError( u'Found property-only directive {} set on ver...
[ "def", "validate_vertex_directives", "(", "directives", ")", ":", "for", "directive_name", "in", "six", ".", "iterkeys", "(", "directives", ")", ":", "if", "directive_name", "in", "PROPERTY_ONLY_DIRECTIVES", ":", "raise", "GraphQLCompilationError", "(", "u'Found prope...
Validate the directives that appear at a vertex field.
[ "Validate", "the", "directives", "that", "appear", "at", "a", "vertex", "field", "." ]
python
train
pyroscope/pyrobase
src/pyrobase/fmt.py
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/fmt.py#L146-L185
def to_utf8(text): """ Enforce UTF8 encoding. """ # return empty/false stuff unaltered if not text: if isinstance(text, string_types): text = "" return text try: # Is it a unicode string, or pure ascii? return text.encode("utf8") except UnicodeDecodeE...
[ "def", "to_utf8", "(", "text", ")", ":", "# return empty/false stuff unaltered", "if", "not", "text", ":", "if", "isinstance", "(", "text", ",", "string_types", ")", ":", "text", "=", "\"\"", "return", "text", "try", ":", "# Is it a unicode string, or pure ascii?"...
Enforce UTF8 encoding.
[ "Enforce", "UTF8", "encoding", "." ]
python
train
asciimoo/exrex
exrex.py
https://github.com/asciimoo/exrex/blob/69733409042b526da584c675907a316ad708a8d4/exrex.py#L294-L382
def sre_to_string(sre_obj, paren=True): """sre_parse object to string :param sre_obj: Output of sre_parse.parse() :type sre_obj: list :rtype: str """ ret = u'' for i in sre_obj: if i[0] == sre_parse.IN: prefix = '' if len(i[1]) and i[1][0][0] == sre_parse.NEG...
[ "def", "sre_to_string", "(", "sre_obj", ",", "paren", "=", "True", ")", ":", "ret", "=", "u''", "for", "i", "in", "sre_obj", ":", "if", "i", "[", "0", "]", "==", "sre_parse", ".", "IN", ":", "prefix", "=", "''", "if", "len", "(", "i", "[", "1",...
sre_parse object to string :param sre_obj: Output of sre_parse.parse() :type sre_obj: list :rtype: str
[ "sre_parse", "object", "to", "string" ]
python
valid
CityOfZion/neo-python
neo/Implementations/Notifications/LevelDB/NotificationDB.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Implementations/Notifications/LevelDB/NotificationDB.py#L121-L213
def on_persist_completed(self, block): """ Called when a block has been persisted to disk. Used as a hook to persist notification data. Args: block (neo.Core.Block): the currently persisting block """ if len(self._events_to_write): addr_db = self.db.pref...
[ "def", "on_persist_completed", "(", "self", ",", "block", ")", ":", "if", "len", "(", "self", ".", "_events_to_write", ")", ":", "addr_db", "=", "self", ".", "db", ".", "prefixed_db", "(", "NotificationPrefix", ".", "PREFIX_ADDR", ")", "block_db", "=", "se...
Called when a block has been persisted to disk. Used as a hook to persist notification data. Args: block (neo.Core.Block): the currently persisting block
[ "Called", "when", "a", "block", "has", "been", "persisted", "to", "disk", ".", "Used", "as", "a", "hook", "to", "persist", "notification", "data", ".", "Args", ":", "block", "(", "neo", ".", "Core", ".", "Block", ")", ":", "the", "currently", "persisti...
python
train
ramrod-project/database-brain
schema/brain/queries/writes.py
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/writes.py#L20-L29
def waiting_filter(lte_time, conn=None): """ generates a filter for status==waiting and time older than lte_time """ if RBO.index_list().contains(IDX_OUTPUT_JOB_ID).run(conn): return (r.row[START_FIELD] <= lte_time) else: return ((r.row[STATUS_FIELD] == WAITING) & (r....
[ "def", "waiting_filter", "(", "lte_time", ",", "conn", "=", "None", ")", ":", "if", "RBO", ".", "index_list", "(", ")", ".", "contains", "(", "IDX_OUTPUT_JOB_ID", ")", ".", "run", "(", "conn", ")", ":", "return", "(", "r", ".", "row", "[", "START_FIE...
generates a filter for status==waiting and time older than lte_time
[ "generates", "a", "filter", "for", "status", "==", "waiting", "and", "time", "older", "than", "lte_time" ]
python
train
dwavesystems/dwave-system
dwave/system/cache/cache_manager.py
https://github.com/dwavesystems/dwave-system/blob/86a1698f15ccd8b0ece0ed868ee49292d3f67f5b/dwave/system/cache/cache_manager.py#L34-L60
def cache_file(app_name=APPNAME, app_author=APPAUTHOR, filename=DATABASENAME): """Returns the filename (including path) for the data cache. The path will depend on the operating system, certain environmental variables and whether it is being run inside a virtual environment. See `homebase <https://gith...
[ "def", "cache_file", "(", "app_name", "=", "APPNAME", ",", "app_author", "=", "APPAUTHOR", ",", "filename", "=", "DATABASENAME", ")", ":", "user_data_dir", "=", "homebase", ".", "user_data_dir", "(", "app_name", "=", "app_name", ",", "app_author", "=", "app_au...
Returns the filename (including path) for the data cache. The path will depend on the operating system, certain environmental variables and whether it is being run inside a virtual environment. See `homebase <https://github.com/dwavesystems/homebase>`_. Args: app_name (str, optional): The appl...
[ "Returns", "the", "filename", "(", "including", "path", ")", "for", "the", "data", "cache", "." ]
python
train
sergiocorreia/panflute
panflute/tools.py
https://github.com/sergiocorreia/panflute/blob/65c2d570c26a190deb600cab5e2ad8a828a3302e/panflute/tools.py#L277-L297
def shell(args, wait=True, msg=None): """ Execute the external command and get its exitcode, stdout and stderr. """ # Fix Windows error if passed a string if isinstance(args, str): args = shlex.split(args, posix=(os.name != "nt")) if os.name == "nt": args = [arg.replace(...
[ "def", "shell", "(", "args", ",", "wait", "=", "True", ",", "msg", "=", "None", ")", ":", "# Fix Windows error if passed a string", "if", "isinstance", "(", "args", ",", "str", ")", ":", "args", "=", "shlex", ".", "split", "(", "args", ",", "posix", "=...
Execute the external command and get its exitcode, stdout and stderr.
[ "Execute", "the", "external", "command", "and", "get", "its", "exitcode", "stdout", "and", "stderr", "." ]
python
train
michael-lazar/rtv
rtv/packages/praw/objects.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/objects.py#L1294-L1318
def mark_as_nsfw(self, unmark_nsfw=False): """Mark as Not Safe For Work. Requires that the currently authenticated user is the author of the submission, has the modposts oauth scope or has user/password authentication as a mod of the subreddit. :returns: The json response from ...
[ "def", "mark_as_nsfw", "(", "self", ",", "unmark_nsfw", "=", "False", ")", ":", "def", "mark_as_nsfw_helper", "(", "self", ")", ":", "# pylint: disable=W0613", "# It is necessary to have the 'self' argument as it's needed in", "# restrict_access to determine what class the decora...
Mark as Not Safe For Work. Requires that the currently authenticated user is the author of the submission, has the modposts oauth scope or has user/password authentication as a mod of the subreddit. :returns: The json response from the server.
[ "Mark", "as", "Not", "Safe", "For", "Work", "." ]
python
train
bokeh/bokeh
bokeh/embed/util.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/util.py#L67-L168
def OutputDocumentFor(objs, apply_theme=None, always_new=False): ''' Find or create a (possibly temporary) Document to use for serializing Bokeh content. Typical usage is similar to: .. code-block:: python with OutputDocumentFor(models): (docs_json, [render_item]) = standalone_do...
[ "def", "OutputDocumentFor", "(", "objs", ",", "apply_theme", "=", "None", ",", "always_new", "=", "False", ")", ":", "# Note: Comms handling relies on the fact that the new_doc returned", "# has models with the same IDs as they were started with", "if", "not", "isinstance", "("...
Find or create a (possibly temporary) Document to use for serializing Bokeh content. Typical usage is similar to: .. code-block:: python with OutputDocumentFor(models): (docs_json, [render_item]) = standalone_docs_json_and_render_items(models) Inside the context manager, the mod...
[ "Find", "or", "create", "a", "(", "possibly", "temporary", ")", "Document", "to", "use", "for", "serializing", "Bokeh", "content", "." ]
python
train
automl/HpBandSter
hpbandster/optimizers/config_generators/lcnet.py
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/config_generators/lcnet.py#L63-L103
def get_config(self, budget): """ function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled...
[ "def", "get_config", "(", "self", ",", "budget", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "if", "not", "self", ".", "is_trained", ":", "c", "=", "self", ".", "config_space", ".", "sample_configuration", "(", ")", ".", "get_array", "(", ...
function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should r...
[ "function", "to", "sample", "a", "new", "configuration" ]
python
train
baccuslab/shannon
shannon/discrete.py
https://github.com/baccuslab/shannon/blob/38abb4d9e53208ffd1c4149ef9fdf3abceccac48/shannon/discrete.py#L71-L113
def combine_symbols(*args): ''' Combine different symbols into a 'super'-symbol args can be an iterable of iterables that support hashing see example for 2D ndarray input usage: 1) combine two symbols, each a number into just one symbol x = numpy.random.randint(0,4,1000) y...
[ "def", "combine_symbols", "(", "*", "args", ")", ":", "for", "arg", "in", "args", ":", "if", "len", "(", "arg", ")", "!=", "len", "(", "args", "[", "0", "]", ")", ":", "raise", "ValueError", "(", "\"combine_symbols got inputs with different sizes\"", ")", ...
Combine different symbols into a 'super'-symbol args can be an iterable of iterables that support hashing see example for 2D ndarray input usage: 1) combine two symbols, each a number into just one symbol x = numpy.random.randint(0,4,1000) y = numpy.random.randint(0,2,1000) ...
[ "Combine", "different", "symbols", "into", "a", "super", "-", "symbol" ]
python
train
open511/open511
open511/utils/schedule.py
https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L53-L56
def intervals(self, range_start=datetime.datetime.min, range_end=datetime.datetime.max): """Returns a list of tuples of start/end datetimes for when the schedule is active during the provided range.""" raise NotImplementedError
[ "def", "intervals", "(", "self", ",", "range_start", "=", "datetime", ".", "datetime", ".", "min", ",", "range_end", "=", "datetime", ".", "datetime", ".", "max", ")", ":", "raise", "NotImplementedError" ]
Returns a list of tuples of start/end datetimes for when the schedule is active during the provided range.
[ "Returns", "a", "list", "of", "tuples", "of", "start", "/", "end", "datetimes", "for", "when", "the", "schedule", "is", "active", "during", "the", "provided", "range", "." ]
python
valid
tk0miya/tk.phpautodoc
src/phply/phpparse.py
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phpparse.py#L851-L853
def p_reference_variable_array_offset(p): 'reference_variable : reference_variable LBRACKET dim_offset RBRACKET' p[0] = ast.ArrayOffset(p[1], p[3], lineno=p.lineno(2))
[ "def", "p_reference_variable_array_offset", "(", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "ArrayOffset", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "2", ")", ")" ]
reference_variable : reference_variable LBRACKET dim_offset RBRACKET
[ "reference_variable", ":", "reference_variable", "LBRACKET", "dim_offset", "RBRACKET" ]
python
train