_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q30000 | HiveServer2Cursor.execute | train | def execute(self, operation, parameters=None, configuration=None):
"""Synchronously execute a SQL query.
Blocks until results are available.
Parameters
----------
operation : str
The SQL query to execute.
parameters : str, optional
Parameters to ... | python | {
"resource": ""
} |
q30001 | HiveServer2Cursor.execute_async | train | def execute_async(self, operation, parameters=None, configuration=None):
"""Asynchronously execute a SQL query.
Immediately returns after query is sent to the HS2 server. Poll with
`is_executing`. A call to `fetch*` will block.
Parameters
----------
operation : str
... | python | {
"resource": ""
} |
q30002 | HiveServer2Cursor._get_sleep_interval | train | def _get_sleep_interval(self, start_time):
"""Returns a step function of time to sleep in seconds before polling
again. Maximum sleep is 1s, minimum is 0.1s"""
elapsed = time.time() - start_time
if elapsed < 0.05:
return | python | {
"resource": ""
} |
q30003 | HiveServer2Cursor.fetchcbatch | train | def fetchcbatch(self):
'''Return a CBatch object of any data currently in the buffer or
if no data currently in buffer then fetch a batch'''
if not self._last_operation.is_columnar:
raise NotSupportedError("Server does not support columnar "
"fe... | python | {
"resource": ""
} |
q30004 | HiveServer2Cursor.fetchcolumnar | train | def fetchcolumnar(self):
"""Executes a fetchall operation returning a list of CBatches"""
self._wait_to_finish()
if not self._last_operation.is_columnar:
raise NotSupportedError("Server does not support columnar "
"fetching")
batches = []
... | python | {
"resource": ""
} |
q30005 | Client.setOption | train | def setOption(self, key, value):
"""
Sets an option
Parameters:
- key
- value
| python | {
"resource": ""
} |
q30006 | Client.fetch | train | def fetch(self, query_id, start_over, fetch_size):
"""
Get the results of a query. This is non-blocking. Caller should check
Results.ready to determine if the results are in yet. The call requests
the batch size of fetch.
Parameters:
- query_id
| python | {
"resource": ""
} |
q30007 | ImpalaDDLCompiler.post_create_table | train | def post_create_table(self, table):
"""Build table-level CREATE options."""
table_opts = []
if 'impala_partition_by' in table.kwargs:
table_opts.append('PARTITION BY %s' % table.kwargs.get('impala_partition_by'))
if 'impala_stored_as' in table.kwargs:
table_opt... | python | {
"resource": ""
} |
q30008 | _get_table_schema_hack | train | def _get_table_schema_hack(cursor, table):
"""Get the schema of table by talking to Impala
table must be a string (incl possible db name)
"""
# get the schema of the query result via a LIMIT 0 hack
cursor.execute('SELECT * FROM %s | python | {
"resource": ""
} |
q30009 | respond | train | def respond(request, code):
"""
Responds to the request with the given response code.
If ``next`` is in the form, it will redirect instead.
"""
redirect = request.GET.get('next', request.POST.get('next'))
if | python | {
"resource": ""
} |
q30010 | follow_unfollow | train | def follow_unfollow(request, content_type_id, object_id, flag, do_follow=True, actor_only=True):
"""
Creates or deletes the follow relationship between ``request.user`` and the
actor defined by ``content_type_id``, ``object_id``.
"""
ctype = get_object_or_404(ContentType, pk=content_type_id)
ins... | python | {
"resource": ""
} |
q30011 | followers | train | def followers(request, content_type_id, object_id, flag):
"""
Creates a listing of ``User``s that follow the actor defined by
``content_type_id``, ``object_id``.
"""
ctype = get_object_or_404(ContentType, pk=content_type_id)
| python | {
"resource": ""
} |
q30012 | ActionManager.public | train | def public(self, *args, **kwargs):
"""
Only return public actions
"""
| python | {
"resource": ""
} |
q30013 | ActionManager.actor | train | def actor(self, obj, **kwargs):
"""
Stream of most recent actions where obj is the actor.
Keyword arguments will be passed to Action.objects.filter
| python | {
"resource": ""
} |
q30014 | ActionManager.target | train | def target(self, obj, **kwargs):
"""
Stream of most recent actions where obj is the target.
Keyword arguments will be passed to Action.objects.filter
| python | {
"resource": ""
} |
q30015 | ActionManager.action_object | train | def action_object(self, obj, **kwargs):
"""
Stream of most recent actions where obj is the action_object.
Keyword arguments will be passed to Action.objects.filter
| python | {
"resource": ""
} |
q30016 | ActionManager.model_actions | train | def model_actions(self, model, **kwargs):
"""
Stream of most recent actions by any particular model
"""
check(model)
ctype = ContentType.objects.get_for_model(model)
return self.public(
| python | {
"resource": ""
} |
q30017 | ActionManager.any | train | def any(self, obj, **kwargs):
"""
Stream of most recent actions where obj is the actor OR target OR action_object.
"""
check(obj)
ctype = ContentType.objects.get_for_model(obj)
return self.public(
Q(
actor_content_type=ctype,
ac... | python | {
"resource": ""
} |
q30018 | ActionManager.user | train | def user(self, obj, with_user_activity=False, follow_flag=None, **kwargs):
"""Create a stream of the most recent actions by objects that the user is following."""
q = Q()
qs = self.public()
if not obj:
return qs.none()
check(obj)
if with_user_activity:
... | python | {
"resource": ""
} |
q30019 | FollowManager.for_object | train | def for_object(self, instance, flag=''):
"""
Filter to a specific instance.
"""
check(instance)
content_type = ContentType.objects.get_for_model(instance).pk
| python | {
"resource": ""
} |
q30020 | FollowManager.is_following | train | def is_following(self, user, instance, flag=''):
"""
Check if a user is following an instance.
"""
if not user or user.is_anonymous:
return False
queryset = self.for_object(instance)
| python | {
"resource": ""
} |
q30021 | setup_generic_relations | train | def setup_generic_relations(model_class):
"""
Set up GenericRelations for actionable models.
"""
Action = apps.get_model('actstream', 'action')
if Action is None:
raise RegistrationError(
'Unable get actstream.Action. Potential circular imports '
'in initialisation. ... | python | {
"resource": ""
} |
q30022 | stream | train | def stream(func):
"""
Stream decorator to be applied to methods of an ``ActionManager`` subclass
Syntax::
from actstream.decorators import stream
from actstream.managers import ActionManager
class MyManager(ActionManager):
@stream
def foobar(self, ...):
... | python | {
"resource": ""
} |
q30023 | follow_url | train | def follow_url(parser, token):
"""
Renders the URL of the follow view for a particular actor instance
::
<a href="{% follow_url other_user %}">
{% if request.user|is_following:other_user %}
stop following
{% else %}
follow
{% endi... | python | {
"resource": ""
} |
q30024 | follow_all_url | train | def follow_all_url(parser, token):
"""
Renders the URL to follow an object as both actor and target
::
<a href="{% follow_all_url other_user %}">
{% if request.user|is_following:other_user %}
stop following
{% else %}
follow
{% en... | python | {
"resource": ""
} |
q30025 | actor_url | train | def actor_url(parser, token):
"""
Renders the URL for a particular actor instance
::
<a href="{% actor_url request.user %}">View your actions</a>
<a href="{% actor_url another_user %}">{{ another_user | python | {
"resource": ""
} |
q30026 | AsNode.handle_token | train | def handle_token(cls, parser, token):
"""
Class method to parse and return a Node.
"""
tag_error = "Accepted formats {%% %(tagname)s %(args)s %%} or " \
"{%% %(tagname)s %(args)s as [var] %%}"
bits = token.split_contents()
args_count = len(bits) - 1
... | python | {
"resource": ""
} |
q30027 | follow | train | def follow(user, obj, send_action=True, actor_only=True, flag='', **kwargs):
"""
Creates a relationship allowing the object's activities to appear in the
user's stream.
Returns the created ``Follow`` instance.
If ``send_action`` is ``True`` (the default) then a
``<user> started following <obje... | python | {
"resource": ""
} |
q30028 | unfollow | train | def unfollow(user, obj, send_action=False, flag=''):
"""
Removes a "follow" relationship.
Set ``send_action`` to ``True`` (``False is default) to also send a
``<user> stopped following <object>`` action signal.
Pass a string value to ``flag`` to determine which type of "follow" relationship you wa... | python | {
"resource": ""
} |
q30029 | is_following | train | def is_following(user, obj, flag=''):
"""
Checks if a "follow" relationship exists.
Returns True if exists, False otherwise.
Pass a string value to ``flag`` to determine which type of "follow" relationship you want to check.
Example::
is_following(request.user, group)
is_followin... | python | {
"resource": ""
} |
q30030 | action_handler | train | def action_handler(verb, **kwargs):
"""
Handler function to create Action instance upon action signal call.
"""
kwargs.pop('signal', None)
actor = kwargs.pop('sender')
# We must store the unstranslated string
# If verb is an ugettext_lazyed string, fetch the original string
if hasattr(v... | python | {
"resource": ""
} |
q30031 | AbstractActivityStream.items | train | def items(self, *args, **kwargs):
"""
Returns a queryset of Actions to use based on the stream method and object.
""" | python | {
"resource": ""
} |
q30032 | AbstractActivityStream.get_uri | train | def get_uri(self, action, obj=None, date=None):
"""
Returns an RFC3987 IRI ID for the given object, action and date.
"""
if date is None:
| python | {
"resource": ""
} |
q30033 | AbstractActivityStream.get_url | train | def get_url(self, action, obj=None, domain=True):
"""
Returns an RFC3987 IRI for a HTML representation of the given object, action.
If domain is true, the current site's domain will be added.
"""
if not obj:
url = reverse('actstream_detail', None, (action.pk,))
... | python | {
"resource": ""
} |
q30034 | AbstractActivityStream.format | train | def format(self, action):
"""
Returns a formatted dictionary for the given action.
"""
item = {
'id': self.get_uri(action),
'url': self.get_url(action),
'verb': action.verb,
'published': rfc3339_date(action.timestamp),
'actor': ... | python | {
"resource": ""
} |
q30035 | AbstractActivityStream.format_item | train | def format_item(self, action, item_type='actor'):
"""
Returns a formatted dictionary for an individual item based on the action and item_type.
"""
obj = getattr(action, item_type)
return {
'id': self.get_uri(action, obj),
| python | {
"resource": ""
} |
q30036 | ActivityStreamsBaseFeed.item_extra_kwargs | train | def item_extra_kwargs(self, action):
"""
Returns an extra keyword arguments dictionary that is used with
the `add_item` call of the feed generator.
Add the 'content' field of the 'Entry' item, to be used by the custom
feed generator.
"""
| python | {
"resource": ""
} |
q30037 | Statement._principals | train | def _principals(self):
"""Extracts all principals from IAM statement.
Should handle these cases:
"Principal": "value"
"Principal": ["value"]
"Principal": { "AWS": "value" }
"Principal": { "AWS": ["value", "value"] }
"Principal": { "Service": "value" }
"Pr... | python | {
"resource": ""
} |
q30038 | extract_audioclip_samples | train | def extract_audioclip_samples(d) -> dict:
"""
Extract all the sample data from an AudioClip and
convert it from FSB5 if needed.
"""
ret = {}
if not d.data:
# eg. StreamedResource not available
return {}
try:
from fsb5 import FSB5
except ImportError as e:
raise RuntimeError("python-fsb5 is required to ... | python | {
"resource": ""
} |
q30039 | use_kwargs | train | def use_kwargs(args, locations=None, inherit=None, apply=None, **kwargs):
"""Inject keyword arguments from the specified webargs arguments into the
decorated view function.
Usage:
.. code-block:: python
from marshmallow import fields
@use_kwargs({'name': fields.Str(), 'category': fie... | python | {
"resource": ""
} |
q30040 | marshal_with | train | def marshal_with(schema, code='default', description='', inherit=None, apply=None):
"""Marshal the return value of the decorated view function using the
specified schema.
Usage:
.. code-block:: python
class PetSchema(Schema):
class Meta:
fields = ('name', 'category... | python | {
"resource": ""
} |
q30041 | doc | train | def doc(inherit=None, **kwargs):
"""Annotate the decorated view function or class with the specified Swagger
attributes.
Usage:
.. code-block:: python
@doc(tags=['pet'], description='a pet store')
def get_pet(pet_id):
return Pet.query.filter(Pet.id == pet_id).one()
:p... | python | {
"resource": ""
} |
q30042 | wrap_with | train | def wrap_with(wrapper_cls):
"""Use a custom `Wrapper` to apply annotations to the decorated function.
:param wrapper_cls: Custom `Wrapper` subclass
"""
def wrapper(func):
| python | {
"resource": ""
} |
q30043 | get_available_FIELD_transitions | train | def get_available_FIELD_transitions(instance, field):
"""
List of transitions available in current model state
with all conditions met
"""
curr_state = field.get_state(instance)
transitions = field.transitions[instance.__class__]
for name, transition in transitions.items():
| python | {
"resource": ""
} |
q30044 | get_available_user_FIELD_transitions | train | def get_available_user_FIELD_transitions(instance, user, field):
"""
List of transitions available in current model state
with all conditions met and user have rights on it
"""
| python | {
"resource": ""
} |
q30045 | transition | train | def transition(field, source='*', target=None, on_error=None, conditions=[], permission=None, custom={}):
"""
Method decorator to mark allowed transitions.
Set target to None if current state needs to be validated and
has not changed after the function call.
"""
def inner_transition(func):
... | python | {
"resource": ""
} |
q30046 | can_proceed | train | def can_proceed(bound_method, check_conditions=True):
"""
Returns True if model in state allows to call bound_method
Set ``check_conditions`` argument to ``False`` to skip checking
conditions.
"""
if not hasattr(bound_method, '_django_fsm'):
im_func = getattr(bound_method, 'im_func', ge... | python | {
"resource": ""
} |
q30047 | has_transition_perm | train | def has_transition_perm(bound_method, user):
"""
Returns True if model in state allows to call bound_method and user have rights on it
"""
if not hasattr(bound_method, '_django_fsm'):
im_func = getattr(bound_method, 'im_func', getattr(bound_method, '__func__'))
raise TypeError('%s method... | python | {
"resource": ""
} |
q30048 | FSMMeta.has_transition | train | def has_transition(self, state):
"""
Lookup if any transition exists from current model state using current method
"""
if state in self.transitions:
return True
if '*' in self.transitions:
| python | {
"resource": ""
} |
q30049 | FSMMeta.conditions_met | train | def conditions_met(self, instance, state):
"""
Check if all conditions have been met
"""
transition = self.get_transition(state)
if transition is None:
return False
elif | python | {
"resource": ""
} |
q30050 | Silverstripe._convert_to_folder | train | def _convert_to_folder(self, packages):
"""
Silverstripe's page contains a list of composer packages. This
function converts those to folder names. These may be different due
to installer-name.
Implemented exponential backoff in order to prevent packager from
... | python | {
"resource": ""
} |
q30051 | BasePluginInternal._general_init | train | def _general_init(self, opts, out=None):
"""
Initializes a variety of variables depending on user input.
@return: a tuple containing a boolean value indicating whether
progressbars should be hidden, functionality and enabled
functionality.
"""
se... | python | {
"resource": ""
} |
q30052 | BasePluginInternal.url_scan | train | def url_scan(self, url, opts, functionality, enabled_functionality, hide_progressbar):
"""
This is the main function called whenever a URL needs to be scanned.
This is called when a user specifies an individual CMS, or after CMS
identification has taken place. This function is called for... | python | {
"resource": ""
} |
q30053 | BasePluginInternal._determine_redirect | train | def _determine_redirect(self, url, verb, timeout=15, headers={}):
"""
Internal redirect function, focuses on HTTP and worries less about
application-y stuff.
@param url: the url to check
@param verb: the verb, e.g. head, or get.
@param timeout: the time, in seconds, that ... | python | {
"resource": ""
} |
q30054 | BasePluginInternal.enumerate_version_changelog | train | def enumerate_version_changelog(self, url, versions_estimated, timeout=15,
headers={}):
"""
If we have a changelog in store for this CMS, this function will be
called, and a changelog will be used for narrowing down which version is
installed. If the changelog's version is ou... | python | {
"resource": ""
} |
q30055 | BasePluginInternal._enumerate_plugin_if | train | def _enumerate_plugin_if(self, found_list, verb, threads, imu_list,
hide_progressbar, timeout=15, headers={}):
"""
Finds interesting urls within a plugin folder which respond with 200 OK.
@param found_list: as returned in self.enumerate. E.g. [{'name':
'this_exists', 'url... | python | {
"resource": ""
} |
q30056 | BasePluginInternal.cms_identify | train | def cms_identify(self, url, timeout=15, headers={}):
"""
Function called when attempting to determine if a URL is identified
as being this particular CMS.
@param url: the URL to attempt to identify.
@param timeout: number of seconds before a timeout occurs on a http
c... | python | {
"resource": ""
} |
q30057 | BasePluginInternal.resume_forward | train | def resume_forward(self, fh, resume, file_location, error_log):
"""
Forwards `fh` n lines, where n lines is the amount of lines we should
skip in order to resume our previous scan, if resume is required by the
user.
@param fh: fh to advance.
| python | {
"resource": ""
} |
q30058 | StandardOutput.result | train | def result(self, result, functionality):
"""
For the final result of the scan.
@param result: as returned by BasePluginInternal.url_scan
@param functionality: functionality as returned by
BasePluginInternal._general_init
"""
for enumerate in result:
... | python | {
"resource": ""
} |
q30059 | StandardOutput.warn | train | def warn(self, msg, whitespace_strp=True):
"""
For things that have gone seriously wrong but don't merit a program
halt.
Outputs to stderr, so JsonOutput does not need to override.
@param msg: warning to output.
@param whitespace_strp: whether to strip whitespace. | python | {
"resource": ""
} |
q30060 | RequestsLogger._print | train | def _print(self, method, *args, **kwargs):
"""
Output format affects integration tests.
@see: IntegrationTests.mock_output
"""
sess_method = getattr(self._session, method)
try:
headers = kwargs['headers']
except KeyError:
headers = {}
... | python | {
"resource": ""
} |
q30061 | repair_url | train | def repair_url(url):
"""
Fixes URL.
@param url: url to repair.
@param out: instance of StandardOutput as defined in this lib.
@return: Newline characters are stripped from the URL string.
If the url string parameter does not start with http, it prepends http://
If the url string para... | python | {
"resource": ""
} |
q30062 | exc_handle | train | def exc_handle(url, out, testing):
"""
Handle exception. If of a determinate subset, it is stored into a file as a
single type. Otherwise, full stack is stored. Furthermore, if testing, stack
is always shown.
@param url: url which was being scanned when exception was thrown.
@param out: Output o... | python | {
"resource": ""
} |
q30063 | tail | train | def tail(f, window=20):
"""
Returns the last `window` lines of file `f` as a list.
@param window: the number of lines.
"""
if window == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = window + 1
block = -1
data = []
while size > 0 and bytes > 0:
... | python | {
"resource": ""
} |
q30064 | process_host_line | train | def process_host_line(line):
"""
Processes a line and determines whether it is a tab-delimited CSV of
url and host.
Strips all strings.
@param line: the line to analyse.
@param opts: the options dictionary to modify.
@return: a tuple containing url, and host header if any change is
... | python | {
"resource": ""
} |
q30065 | instances_get | train | def instances_get(opts, plugins, url_file_input, out):
"""
Creates and returns an ordered dictionary containing instances for all available
scanning plugins, sort of ordered by popularity.
@param opts: options as returned by self._options.
@param plugins: plugins as returned by plugins_util.plugins_... | python | {
"resource": ""
} |
q30066 | instance_get | train | def instance_get(plugin, opts, url_file_input, out):
"""
Return an instance dictionary for an individual plugin.
@see Scan._instances_get.
"""
inst = plugin()
hp, func, enabled_func = inst._general_init(opts, out)
name = inst._meta.label
kwargs = {
'hide_progressbar': hp,
... | python | {
"resource": ""
} |
q30067 | result_anything_found | train | def result_anything_found(result):
"""
Interim solution for the fact that sometimes determine_scanning_method can
legitimately return a valid scanning method, but it results that the site
does not belong to a particular CMS.
@param result: the result as passed to Output.result()
@return: whether... | python | {
"resource": ""
} |
q30068 | VersionsFile.update | train | def update(self, sums):
"""
Update self.et with the sums as returned by VersionsX.sums_get
@param sums: {'version': {'file1':'hash1'}}
"""
for version in sums:
hashes = sums[version]
for filename in hashes:
hsh = hashes[filename]
... | python | {
"resource": ""
} |
q30069 | github_tags_newer | train | def github_tags_newer(github_repo, versions_file, update_majors):
"""
Get new tags from a github repository. Cannot use github API because it
doesn't support chronological ordering of tags.
@param github_repo: the github repository, e.g. 'drupal/drupal/'.
@param versions_file: the file path where th... | python | {
"resource": ""
} |
q30070 | _check_newer_major | train | def _check_newer_major(current_highest, versions):
"""
Utility function for checking whether a new version exists and is not going
to be updated. This is undesirable because it could result in new versions
existing and not being updated. Raising is prefering to adding the new
version manually becaus... | python | {
"resource": ""
} |
q30071 | _newer_tags_get | train | def _newer_tags_get(current_highest, versions):
"""
Returns versions from versions which are greater than than the highest
version in each major. If a newer major is present in versions which is
not present on current_highest, an exception will be raised.
@param current_highest: as returned by Versi... | python | {
"resource": ""
} |
q30072 | github_repo_new | train | def github_repo_new(repo_url, plugin_name, versions_file, update_majors):
"""
Convenience method which creates GitRepo and returns the created
instance, as well as a VersionsFile and tags which need to be updated.
@param repo_url: the github repository path, e.g. 'drupal/drupal/'
@param plugin_name:... | python | {
"resource": ""
} |
q30073 | hashes_get | train | def hashes_get(versions_file, base_path):
"""
Gets hashes for currently checked out version.
@param versions_file: a common.VersionsFile instance to check against.
@param base_path: where to look for files. e.g. './.update-workspace/silverstripe/'
@return: checksums {'file1': 'hash1'}
"""
fi... | python | {
"resource": ""
} |
q30074 | file_mtime | train | def file_mtime(file_path):
"""
Returns the file modified time. This is with regards to the last
modification the file has had in the droopescan repo, rather than actual
file modification time in the filesystem.
@param file_path: file path relative to the executable.
@return datetime.datetime obj... | python | {
"resource": ""
} |
q30075 | modules_get | train | def modules_get(url_tpl, per_page, css, max_modules=2000, pagination_type=PT.normal):
"""
Gets a list of modules. Note that this function can also be used to get
themes.
@param url_tpl: a string such as
https://drupal.org/project/project_module?page=%s. %s will be replaced with
the page number.
... | python | {
"resource": ""
} |
q30076 | GitRepo.init | train | def init(self):
"""
Performs a clone or a fetch, depending on whether the repository has
| python | {
"resource": ""
} |
q30077 | GitRepo.clone | train | def clone(self):
"""
Clones a directory based on the clone_url and plugin_name given to the
constructor. The clone will be located at self.path.
"""
base_dir = '/'.join(self.path.split('/')[:-2])
try:
os.makedirs(base_dir, 0o700)
except OSError:
| python | {
"resource": ""
} |
q30078 | GitRepo.tags_newer | train | def tags_newer(self, versions_file, majors):
"""
Checks this git repo tags for newer versions.
@param versions_file: a common.VersionsFile instance to
check against.
@param majors: a list of major branches to check. E.g. ['6', '7']
@raise RuntimeError: no newer tags w... | python | {
"resource": ""
} |
q30079 | get_rfu | train | def get_rfu():
"""
Returns a list of al "regular file urls" for all plugins.
"""
global _rfu
if _rfu:
return _rfu
plugins = plugins_base_get()
rfu = []
for plugin in plugins:
if isinstance(plugin.regular_file_url, str):
| python | {
"resource": ""
} |
q30080 | plugin_get_rfu | train | def plugin_get_rfu(plugin):
"""
Returns "regular file urls" for a particular plugin.
@param plugin: plugin class.
"""
if isinstance(plugin.regular_file_url, str):
| python | {
"resource": ""
} |
q30081 | plugin_get | train | def plugin_get(name):
"""
Return plugin class.
@param name: the cms label.
"""
plugins = plugins_base_get()
for plugin in plugins:
if | python | {
"resource": ""
} |
q30082 | PhoneNumberField.get_prep_value | train | def get_prep_value(self, value):
"""
Perform preliminary non-db specific value checks and conversions.
"""
if value:
if not isinstance(value, PhoneNumber):
value = to_python(value)
if value.is_valid():
format_string = getattr(settin... | python | {
"resource": ""
} |
q30083 | unique_to_each | train | def unique_to_each(*iterables):
"""Return the elements from each of the input iterables that aren't in the
other input iterables.
For example, suppose you have a set of packages, each with a set of
dependencies::
{'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}}
If you remov... | python | {
"resource": ""
} |
q30084 | interleave_longest | train | def interleave_longest(*iterables):
"""Return a new iterable yielding from each iterable in turn,
skipping any that are exhausted.
>>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8]))
[1, 4, 6, 2, 5, 7, 3, 8]
This function produces the same output as :func:`roundrobin`, but may
p... | python | {
"resource": ""
} |
q30085 | unique_everseen | train | def unique_everseen(iterable, key=None):
"""
Yield unique elements, preserving order.
>>> list(unique_everseen('AAAABBBCCDAABBB'))
['A', 'B', 'C', 'D']
>>> list(unique_everseen('ABBCcAD', str.lower))
['A', 'B', 'C', 'D']
Sequences with a mix of hashable and unhashable items... | python | {
"resource": ""
} |
q30086 | unique_justseen | train | def unique_justseen(iterable, key=None):
"""Yields elements in order, ignoring serial duplicates
>>> list(unique_justseen('AAAABBBCCDAABBB'))
| python | {
"resource": ""
} |
q30087 | random_product | train | def random_product(*args, **kwds):
"""Draw an item at random from each of the input iterables.
>>> random_product('abc', range(4), 'XYZ') # doctest:+SKIP
('c', 3, 'Z')
If *repeat* is provided as a keyword argument, that many items will be
drawn from each iterable.
>>> random_prod... | python | {
"resource": ""
} |
q30088 | run | train | def run(input, conf, filepath=None):
"""Lints a YAML source.
Returns a generator of LintProblem objects.
:param input: buffer, string or stream to read from
:param conf: yamllint configuration object
"""
if conf.is_file_ignored(filepath):
return ()
if isinstance(input, (type(b''),... | python | {
"resource": ""
} |
q30089 | get_line_indent | train | def get_line_indent(token):
"""Finds the indent of the line the token starts in."""
start = token.start_mark.buffer.rfind('\n', 0,
| python | {
"resource": ""
} |
q30090 | get_real_end_line | train | def get_real_end_line(token):
"""Finds the line on which the token really ends.
With pyyaml, scalar tokens often end on a next line.
"""
end_line = token.end_mark.line + 1
if not isinstance(token, yaml.ScalarToken):
return end_line
pos = token.end_mark.pointer - 1
while (pos >= to... | python | {
"resource": ""
} |
q30091 | comments_between_tokens | train | def comments_between_tokens(token1, token2):
"""Find all comments between two tokens"""
if token2 is None:
buf = token1.end_mark.buffer[token1.end_mark.pointer:]
elif (token1.end_mark.line == token2.start_mark.line and
not isinstance(token1, yaml.StreamStartToken) and
not isinsta... | python | {
"resource": ""
} |
q30092 | token_or_comment_or_line_generator | train | def token_or_comment_or_line_generator(buffer):
"""Generator that mixes tokens and lines, ordering them by line number"""
tok_or_com_gen = token_or_comment_generator(buffer)
line_gen = line_generator(buffer)
tok_or_com = next(tok_or_com_gen, None)
line = next(line_gen, None)
while tok_or_com i... | python | {
"resource": ""
} |
q30093 | ExportMigrations | train | def ExportMigrations():
"""Exports counts of unapplied migrations.
This is meant to be called during app startup, ideally by
django_prometheus.apps.AppConfig.
"""
# Import MigrationExecutor lazily. MigrationExecutor checks at
# import time that the apps are ready, and they are not when
# d... | python | {
"resource": ""
} |
q30094 | ExportingCursorWrapper | train | def ExportingCursorWrapper(cursor_class, alias, vendor):
"""Returns a CursorWrapper class that knows its database's alias and
vendor name.
"""
class CursorWrapper(cursor_class):
"""Extends the base CursorWrapper to count events."""
def execute(self, *args, **kwargs):
execut... | python | {
"resource": ""
} |
q30095 | ExportModelOperationsMixin | train | def ExportModelOperationsMixin(model_name):
"""Returns a mixin for models to export counters for lifecycle operations.
Usage:
class User(ExportModelOperationsMixin('user'), Model):
...
"""
# Force create the labels for this model in the counters. This
# is not necessary but it avoid... | python | {
"resource": ""
} |
q30096 | SetupPrometheusEndpointOnPort | train | def SetupPrometheusEndpointOnPort(port, addr=''):
"""Exports Prometheus metrics on an HTTPServer running in its own thread.
The server runs on the given port and is by default listenning on
all interfaces. This HTTPServer is fully independent of Django and
its stack. This offers the advantage that even... | python | {
"resource": ""
} |
q30097 | SetupPrometheusEndpointOnPortRange | train | def SetupPrometheusEndpointOnPortRange(port_range, addr=''):
"""Like SetupPrometheusEndpointOnPort, but tries several ports.
This is useful when you're running Django as a WSGI application
with multiple processes and you want Prometheus to discover all
workers. Each worker will grab a port and you can ... | python | {
"resource": ""
} |
q30098 | SetupPrometheusExportsFromConfig | train | def SetupPrometheusExportsFromConfig():
"""Exports metrics so Prometheus can collect them."""
port = getattr(settings, 'PROMETHEUS_METRICS_EXPORT_PORT', None)
port_range = getattr(
settings, 'PROMETHEUS_METRICS_EXPORT_PORT_RANGE', None)
addr = getattr(settings, | python | {
"resource": ""
} |
q30099 | _get_path | train | def _get_path(share_name=None, directory_name=None, file_name=None):
'''
Creates the path to access a file resource.
share_name:
Name of share.
directory_name:
The path to the directory.
file_name:
Name of file.
'''
if share_name and directory_name and file_name:
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.