_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q41900 | CommandCapsule.get_tasks_changed_since | train | def get_tasks_changed_since(self, since):
""" Returns a list of tasks that were changed recently."""
changed_tasks = []
for task in self.client.filter_tasks({'status': 'pending'}):
if task.get(
'modified',
task.get(
'entry',
... | python | {
"resource": ""
} |
q41901 | ContentManager.evergreen | train | def evergreen(self, included_channel_ids=None, excluded_channel_ids=None, **kwargs):
"""
Search containing any evergreen piece of Content.
:included_channel_ids list: Contains ids for channel ids relevant to the query.
:excluded_channel_ids list: Contains ids for channel ids excluded fr... | python | {
"resource": ""
} |
q41902 | ContentManager.evergreen_video | train | def evergreen_video(self, **kwargs):
"""Filter evergreen content to exclusively video content."""
eqs = self.evergreen(**kwargs)
eqs = eqs.filter(VideohubVideo())
return eqs | python | {
"resource": ""
} |
q41903 | ContentManager.instant_articles | train | def instant_articles(self, **kwargs):
"""
QuerySet including all published content approved for instant articles.
Instant articles are configured via FeatureType. FeatureType.instant_article = True.
"""
eqs = self.search(**kwargs).sort('-last_modified', '-published')
ret... | python | {
"resource": ""
} |
q41904 | ContentManager.sponsored | train | def sponsored(self, **kwargs):
"""Search containing any sponsored pieces of Content."""
eqs = self.search(**kwargs)
eqs = eqs.filter(AllSponsored())
published_offset = getattr(settings, "RECENT_SPONSORED_OFFSET_HOURS", None)
if published_offset:
now = timezone.now()
... | python | {
"resource": ""
} |
q41905 | ContentManager.search | train | def search(self, **kwargs):
"""
Query using ElasticSearch, returning an elasticsearch queryset.
:param kwargs: keyword arguments (optional)
* query : ES Query spec
* tags : content tags
* types : content types
* feature_types : featured types
* publi... | python | {
"resource": ""
} |
q41906 | IxnObject.get_obj_class | train | def get_obj_class(self, obj_type):
""" Returns the object class based on parent and object types.
In most cases the object class can be derived from object type alone but sometimes the
same object type name is used for different object types so the parent (or even
grandparent) type is r... | python | {
"resource": ""
} |
q41907 | IxnObject.get_child_static | train | def get_child_static(self, objType, seq_number=None):
""" Returns IxnObject representing the requested child without reading it from the IXN.
Statically build the child object reference based on the requested object type and sequence number and build
the IxnObject with this calculated object re... | python | {
"resource": ""
} |
q41908 | ConversationsAPI.list_conversations | train | def list_conversations(self, filter=None, filter_mode=None, include=None, include_all_conversation_ids=None, interleave_submissions=None, scope=None):
"""
List conversations.
Returns the list of conversations for the current user, most recent ones first.
"""
path = {}
... | python | {
"resource": ""
} |
q41909 | ConversationsAPI.create_conversation | train | def create_conversation(self, body, recipients, attachment_ids=None, context_code=None, filter=None, filter_mode=None, group_conversation=None, media_comment_id=None, media_comment_type=None, mode=None, scope=None, subject=None, user_note=None):
"""
Create a conversation.
Create a new conve... | python | {
"resource": ""
} |
q41910 | ConversationsAPI.edit_conversation | train | def edit_conversation(self, id, conversation_starred=None, conversation_subscribed=None, conversation_workflow_state=None, filter=None, filter_mode=None, scope=None):
"""
Edit a conversation.
Updates attributes for a single conversation.
"""
path = {}
data = {}
... | python | {
"resource": ""
} |
q41911 | update_preferences_by_category | train | def update_preferences_by_category(self, category, communication_channel_id, notification_preferences_frequency):
"""
Update preferences by category.
Change the preferences for multiple notifications based on the category for a single communication channel
"""
path = {}
... | python | {
"resource": ""
} |
q41912 | UsersAPI.list_users_in_account | train | def list_users_in_account(self, account_id, search_term=None):
"""
List users in account.
Retrieve the list of users associated with this account.
@example_request
curl https://<canvas>/api/v1/accounts/self/users?search_term=<search value> \
-X... | python | {
"resource": ""
} |
q41913 | UsersAPI.self_register_user | train | def self_register_user(self, user_name, account_id, user_terms_of_use, pseudonym_unique_id, communication_channel_address=None, communication_channel_type=None, user_birthdate=None, user_locale=None, user_short_name=None, user_sortable_name=None, user_time_zone=None):
"""
Self register a user.
... | python | {
"resource": ""
} |
q41914 | UsersAPI.update_user_settings | train | def update_user_settings(self, id, collapse_global_nav=None, manual_mark_as_read=None):
"""
Update user settings.
Update an existing user's settings.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id... | python | {
"resource": ""
} |
q41915 | UsersAPI.get_custom_color | train | def get_custom_color(self, id, asset_string):
"""
Get custom color.
Returns the custom colors that have been saved for a user for a given context.
The asset_string parameter should be in the format 'context_id', for example
'course_42'.
"""
path... | python | {
"resource": ""
} |
q41916 | UsersAPI.edit_user | train | def edit_user(self, id, user_avatar_token=None, user_avatar_url=None, user_email=None, user_locale=None, user_name=None, user_short_name=None, user_sortable_name=None, user_time_zone=None):
"""
Edit a user.
Modify an existing user. To modify a user's login, see the documentation for logins.... | python | {
"resource": ""
} |
q41917 | UsersAPI.merge_user_into_another_user_destination_user_id | train | def merge_user_into_another_user_destination_user_id(self, id, destination_user_id):
"""
Merge user into another user.
Merge a user into another user.
To merge users, the caller must have permissions to manage both users. This
should be considered irreversible. This will d... | python | {
"resource": ""
} |
q41918 | UsersAPI.get_user_profile | train | def get_user_profile(self, user_id):
"""
Get user profile.
Returns user profile data, including user id, name, and profile pic.
When requesting the profile for the user accessing the API, the user's
calendar feed URL will be returned as well.
"""
... | python | {
"resource": ""
} |
q41919 | UsersAPI.list_user_page_views | train | def list_user_page_views(self, user_id, end_time=None, start_time=None):
"""
List user page views.
Return the user's page view history in json format, similar to the
available CSV download. Pagination is used as described in API basics
section. Page views are returned in d... | python | {
"resource": ""
} |
q41920 | UsersAPI.list_course_nicknames | train | def list_course_nicknames(self):
"""
List course nicknames.
Returns all course nicknames you have set.
"""
path = {}
data = {}
params = {}
self.logger.debug("GET /api/v1/users/self/course_nicknames with query params: {params} and form data: {da... | python | {
"resource": ""
} |
q41921 | UsersAPI.set_course_nickname | train | def set_course_nickname(self, nickname, course_id):
"""
Set course nickname.
Set a nickname for the given course. This will replace the course's name
in output of API calls you make subsequently, as well as in selected
places in the Canvas web user interface.
"""
... | python | {
"resource": ""
} |
q41922 | SisImportsAPI.import_sis_data | train | def import_sis_data(self, account_id, add_sis_stickiness=None, attachment=None, batch_mode=None, batch_mode_term_id=None, clear_sis_stickiness=None, diffing_data_set_identifier=None, diffing_remaster_data_set=None, extension=None, import_type=None, override_sis_stickiness=None):
"""
Import SIS data.
... | python | {
"resource": ""
} |
q41923 | SisImportsAPI.abort_all_pending_sis_imports | train | def abort_all_pending_sis_imports(self, account_id):
"""
Abort all pending SIS imports.
Abort already created but not processed or processing SIS imports.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
... | python | {
"resource": ""
} |
q41924 | patch_egg_info | train | def patch_egg_info(force_hg_version=False):
"""
A hack to replace egg_info.tagged_version with a wrapped version
that will use the mercurial version if indicated.
`force_hg_version` is used for hgtools itself.
"""
from setuptools.command.egg_info import egg_info
from pkg_resources import safe_version
import fu... | python | {
"resource": ""
} |
q41925 | get_or_create | train | def get_or_create(name, value):
"""
returns the storage space defined by name
if space does not exist yet it will first be created with the
specified value
"""
if name not in storage:
storage[name] = value
return storage[name] | python | {
"resource": ""
} |
q41926 | parse_module | train | def parse_module(module):
'''Parse a module's attributes and generate a markdown document.'''
attributes = [
(name, type_)
for (name, type_) in getmembers(module)
if (isclass(type_) or isfunction(type_))
and type_.__module__ == module.__name__
and not type_.__name__.start... | python | {
"resource": ""
} |
q41927 | Retry | train | def Retry(target=None, args=[], kwargs={},
options={"retry": True, "interval": 1}):
"""
options
retry
True, infinity retries
False, no retries
Number, retries times
interval
time period for retry
return
None if no succ... | python | {
"resource": ""
} |
q41928 | Publish.create_response | train | def create_response(self, message, sign):
"""
return function for response
"""
def _response(code=200, data=None):
"""
_response
"""
resp_msg = message.to_response(code=code, data=data, sign=sign)
with self._session.session_loc... | python | {
"resource": ""
} |
q41929 | AssignmentGroupsAPI.list_assignment_groups | train | def list_assignment_groups(self, course_id, exclude_assignment_submission_types=None, grading_period_id=None, include=None, override_assignment_dates=None, scope_assignments_to_student=None):
"""
List assignment groups.
Returns the list of assignment groups for the current context. The retu... | python | {
"resource": ""
} |
q41930 | AssignmentGroupsAPI.get_assignment_group | train | def get_assignment_group(self, course_id, assignment_group_id, grading_period_id=None, include=None, override_assignment_dates=None):
"""
Get an Assignment Group.
Returns the assignment group with the given id.
"""
path = {}
data = {}
params = {}
... | python | {
"resource": ""
} |
q41931 | AssignmentGroupsAPI.create_assignment_group | train | def create_assignment_group(self, course_id, group_weight=None, integration_data=None, name=None, position=None, rules=None, sis_source_id=None):
"""
Create an Assignment Group.
Create a new assignment group for this course.
"""
path = {}
data = {}
params... | python | {
"resource": ""
} |
q41932 | AssignmentGroupsAPI.edit_assignment_group | train | def edit_assignment_group(self, course_id, assignment_group_id):
"""
Edit an Assignment Group.
Modify an existing Assignment Group.
Accepts the same parameters as Assignment Group creation
"""
path = {}
data = {}
params = {}
# REQUIRED... | python | {
"resource": ""
} |
q41933 | QuizQuestionGroupsAPI.update_question_group | train | def update_question_group(self, id, quiz_id, course_id, quiz_groups_name=None, quiz_groups_pick_count=None, quiz_groups_question_points=None):
"""
Update a question group.
Update a question group
"""
path = {}
data = {}
params = {}
# REQUIRED -... | python | {
"resource": ""
} |
q41934 | CoursesAPI.list_your_courses | train | def list_your_courses(self, enrollment_role=None, enrollment_role_id=None, enrollment_state=None, enrollment_type=None, include=None, state=None):
"""
List your courses.
Returns the list of active courses for the current user.
"""
path = {}
data = {}
para... | python | {
"resource": ""
} |
q41935 | CoursesAPI.list_courses_for_user | train | def list_courses_for_user(self, user_id, enrollment_state=None, include=None, state=None):
"""
List courses for a user.
Returns a list of active courses for this user. To view the course list for a user other than yourself, you must be either an observer of that user or an administrator.
... | python | {
"resource": ""
} |
q41936 | CoursesAPI.list_users_in_course_users | train | def list_users_in_course_users(self, course_id, enrollment_role=None, enrollment_role_id=None, enrollment_state=None, enrollment_type=None, include=None, search_term=None, user_id=None, user_ids=None):
"""
List users in course.
Returns the list of users in this course. And optionally the us... | python | {
"resource": ""
} |
q41937 | CoursesAPI.conclude_course | train | def conclude_course(self, id, event):
"""
Conclude a course.
Delete or conclude an existing course
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"] = id
# REQUIRED - event
"""T... | python | {
"resource": ""
} |
q41938 | CoursesAPI.reset_course | train | def reset_course(self, course_id):
"""
Reset a course.
Deletes the current course, and creates a new equivalent course with
no content, but all sections and users moved over.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - cour... | python | {
"resource": ""
} |
q41939 | CoursesAPI.permissions | train | def permissions(self, course_id, permissions=None):
"""
Permissions.
Returns permission information for provided course & current_user
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"... | python | {
"resource": ""
} |
q41940 | page | train | def page(title, description, element_list=None, tab_list=None):
"""
Returns a dictionary representing a new page to display elements.
This can be thought of as a simple container for displaying multiple
types of information. The ``section`` method can be used to create
separate tabs.
Args:
... | python | {
"resource": ""
} |
q41941 | tab | train | def tab(tab_name, element_list=None, section_list=None):
"""
Returns a dictionary representing a new tab to display elements.
This can be thought of as a simple container for displaying multiple
types of information.
Args:
tab_name: The title to display
element_list: The list of ele... | python | {
"resource": ""
} |
q41942 | section | train | def section(title, element_list):
"""
Returns a dictionary representing a new section. Sections
contain a list of elements that are displayed separately from
the global elements on the page.
Args:
title: The title of the section to be displayed
element_list: The list of elements to... | python | {
"resource": ""
} |
q41943 | image | train | def image(title, desc, image_name, group=None, height=None):
"""
Builds an image element. Image elements are primarily created
and then wrapped into an image gallery element. This is not required
behavior, however and it's independent usage should be allowed depending
on the behavior required.
... | python | {
"resource": ""
} |
q41944 | Execute.commands | train | def commands(self):
"""
Fetch individual SQL commands from a SQL commands containing many commands.
:return: List of commands
"""
# Retrieve all commands via split function or splitting on ';'
print('\tRetrieving commands from', self.sql_script)
print('\tUsing co... | python | {
"resource": ""
} |
q41945 | Execute.execute | train | def execute(self, commands=None, ignored_commands=('DROP', 'UNLOCK', 'LOCK'), execute_fails=True,
max_executions=MAX_EXECUTION_ATTEMPTS):
"""
Sequentially execute a list of SQL commands.
Check if commands property has already been fetched, if so use the
fetched_commands ... | python | {
"resource": ""
} |
q41946 | Execute._execute_commands | train | def _execute_commands(self, commands, fails=False):
"""Execute commands and get list of failed commands and count of successful commands"""
# Confirm that prepare_statements flag is on
if self._prep_statements:
prepared_commands = [prepare_sql(c) for c in tqdm(commands, total=len(com... | python | {
"resource": ""
} |
q41947 | Execute._execute_commands_from_dir | train | def _execute_commands_from_dir(self, directory):
"""Re-attempt to split and execute the failed commands"""
# Get file paths and contents
commands = get_commands_from_dir(directory)
# Execute failed commands again
print('\tAttempting to execute {0} failed commands'.format(len(com... | python | {
"resource": ""
} |
q41948 | Execute.dump_commands | train | def dump_commands(self, commands):
"""Dump commands wrapper for external access."""
# Get base directory
directory = os.path.join(os.path.dirname(self.sql_script), 'fails')
# Get file name to be used for folder name
fname = os.path.basename(self.sql_script.rsplit('.')[0])
... | python | {
"resource": ""
} |
q41949 | get_unresolved_variables | train | def get_unresolved_variables(f):
"""
Gets unresolved vars from file
"""
reporter = RReporter()
checkPath(f, reporter=reporter)
return dict(reporter.messages) | python | {
"resource": ""
} |
q41950 | index_modules | train | def index_modules(idx=None, path=None):
"""
Indexes objs from all modules
"""
suppress_output()
modules = defaultdict(list)
pkglist = pkgutil.walk_packages(onerror=lambda x: True)
print(pkglist)
if path:
pkglist = pkgutil.walk_packages(path, onerror=lambda x: True)
for modl, ... | python | {
"resource": ""
} |
q41951 | WebApplication.includes | train | def includes(self):
""" return includes from config """
r = dict([(k, sorted(copy.deepcopy(v).values(), key=lambda x:x.get("order",0))) for k,v in self.get_config("includes").items()])
if self.version is not None:
for k,v in r.items():
for j in v:
... | python | {
"resource": ""
} |
q41952 | WebApplication.render | train | def render(self, tmpl_name, request_env):
"""
Render the specified template and return the output.
Args:
tmpl_name (str): file name of the template
request_env (dict): request environment
Returns:
str - the rendered template
"""
retu... | python | {
"resource": ""
} |
q41953 | list_submissions_for_multiple_assignments_courses | train | def list_submissions_for_multiple_assignments_courses(self, course_id, assignment_ids=None, grading_period_id=None, grouped=None, include=None, order=None, order_direction=None, student_ids=None):
"""
List submissions for multiple assignments.
Get all existing submissions for a given set of... | python | {
"resource": ""
} |
q41954 | Filter.parse | train | def parse(self, data):
"""Parse operator and value from filter's data."""
val = data.get(self.name, missing)
if not isinstance(val, dict):
return (self.operators['$eq'], self.field.deserialize(val)),
return tuple(
(
self.operators[op],
... | python | {
"resource": ""
} |
q41955 | Filter.apply | train | def apply(self, collection, ops, **kwargs):
"""Apply the filter to collection."""
validator = lambda obj: all(op(obj, val) for (op, val) in ops) # noqa
return [o for o in collection if validator(o)] | python | {
"resource": ""
} |
q41956 | pages | train | def pages():
"""Load pages."""
p1 = Page(
url='/example1',
title='My page with default template',
description='my description',
content='hello default page',
template_name='invenio_pages/default.html',
)
p2 = Page(
url='/example2',
title='My page w... | python | {
"resource": ""
} |
q41957 | PollChoicesAPI.list_poll_choices_in_poll | train | def list_poll_choices_in_poll(self, poll_id):
"""
List poll choices in a poll.
Returns the list of PollChoices in this poll.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - poll_id
"""ID"""
path["poll_id"] = poll_id
... | python | {
"resource": ""
} |
q41958 | PollChoicesAPI.create_single_poll_choice | train | def create_single_poll_choice(self, poll_id, poll_choices_text, poll_choices_is_correct=None, poll_choices_position=None):
"""
Create a single poll choice.
Create a new poll choice for this poll
"""
path = {}
data = {}
params = {}
# REQUIRED - ... | python | {
"resource": ""
} |
q41959 | select_token | train | def select_token(request, scopes='', new=False):
"""
Presents the user with a selection of applicable tokens for the requested view.
"""
@tokens_required(scopes=scopes, new=new)
def _token_list(r, tokens):
context = {
'tokens': tokens,
'base_template': app_settings.E... | python | {
"resource": ""
} |
q41960 | PrimaryKey.get_primary_key | train | def get_primary_key(self, table):
"""Retrieve the column which is the primary key for a table."""
for column in self.get_schema(table):
if len(column) > 3 and 'pri' in column[3].lower():
return column[0] | python | {
"resource": ""
} |
q41961 | PrimaryKey.set_primary_key | train | def set_primary_key(self, table, column):
"""Create a Primary Key constraint on a specific column when the table is already created."""
self.execute('ALTER TABLE {0} ADD PRIMARY KEY ({1})'.format(wrap(table), column))
self._printer('\tAdded primary key to {0} on column {1}'.format(wrap(table), c... | python | {
"resource": ""
} |
q41962 | PrimaryKey.set_primary_keys_auto | train | def set_primary_keys_auto(self, tables=None):
"""
Create primary keys for every table in the connected database.
Checks that each table has a primary key. If a table does not have a key
then each column is analyzed to determine if it contains only unique values.
If no columns e... | python | {
"resource": ""
} |
q41963 | PrimaryKey.set_primary_key_auto | train | def set_primary_key_auto(self, table):
"""
Analysis a table and set a primary key.
Determine primary key by identifying a column with unique values
or creating a new column.
:param table: Table to alter
:return: Primary Key column
"""
# Confirm no primar... | python | {
"resource": ""
} |
q41964 | PrimaryKey.drop_primary_key | train | def drop_primary_key(self, table):
"""Drop a Primary Key constraint for a specific table."""
if self.get_primary_key(table):
self.execute('ALTER TABLE {0} DROP PRIMARY KEY'.format(wrap(table))) | python | {
"resource": ""
} |
q41965 | ForeignKey.set_foreign_key | train | def set_foreign_key(self, parent_table, parent_column, child_table, child_column):
"""Create a Foreign Key constraint on a column from a table."""
self.execute('ALTER TABLE {0} ADD FOREIGN KEY ({1}) REFERENCES {2}({3})'.format(parent_table, parent_column,
... | python | {
"resource": ""
} |
q41966 | _is_api_key_correct | train | def _is_api_key_correct(request):
"""Return whether the Geckoboard API key on the request is correct."""
api_key = getattr(settings, 'GECKOBOARD_API_KEY', None)
if api_key is None:
return True
auth = request.META.get('HTTP_AUTHORIZATION', '').split()
if len(auth) == 2:
if auth[0].low... | python | {
"resource": ""
} |
q41967 | _encrypt | train | def _encrypt(data):
"""Equivalent to OpenSSL using 256 bit AES in CBC mode"""
BS = AES.block_size
def pad(s):
n = BS - len(s) % BS
char = chr(n).encode('utf8')
return s + n * char
password = settings.GECKOBOARD_PASSWORD
salt = Random.new().read(BS - len('Salted__'))
key... | python | {
"resource": ""
} |
q41968 | _render | train | def _render(request, data, encrypted, format=None):
"""
Render the data to Geckoboard. If the `format` parameter is passed
to the widget it defines the output format. Otherwise the output
format is based on the `format` request parameter.
A `format` paramater of ``json`` or ``2`` renders JSON outpu... | python | {
"resource": ""
} |
q41969 | print_report | train | def print_report(runner_results):
"""
Print collated report with output and errors if any
"""
error_report = collections.defaultdict(list)
output_report = collections.defaultdict(list)
success_report = list()
for runner_info in runner_results:
hostname = runner_info['console']
... | python | {
"resource": ""
} |
q41970 | Runner.ipmi_method | train | def ipmi_method(self, command):
"""Use ipmitool to run commands with ipmi protocol
"""
ipmi = ipmitool(self.console, self.password, self.username)
if command == "reboot":
self.ipmi_method(command="status")
if self.output == "Chassis Power is off":
... | python | {
"resource": ""
} |
q41971 | Runner.run | train | def run(self):
"""Start thread run here
"""
try:
if self.command == "pxer":
self.ipmi_method(command="pxe")
if self.status == 0 or self.status == None:
self.command = "reboot"
else:
return
... | python | {
"resource": ""
} |
q41972 | IxnTrafficItem._create | train | def _create(self):
""" Create new object on IxNetwork.
:return: IXN object reference.
"""
if 'name' in self._data:
obj_ref = self.api.add(self.obj_parent(), self.obj_type(), name=self.obj_name())
else:
obj_ref = self.api.add(self.obj_parent(), self.obj_t... | python | {
"resource": ""
} |
q41973 | Transport.merge | train | def merge(self, *args):
"""
Merge multiple dictionary objects into one.
:param variadic args: Multiple dictionary items
:return dict
"""
values = []
for entry in args:
values = values + list(entry.items())
return dict(values) | python | {
"resource": ""
} |
q41974 | Transport.parseLegacy | train | def parseLegacy(self, response):
"""
Parse a legacy response and try and catch any errors. If we have multiple
responses we wont catch any exceptions, we will return the errors
row by row
:param dict response: The response string returned from request()
:return Returns ... | python | {
"resource": ""
} |
q41975 | Transport.parseRest | train | def parseRest(self, response):
"""
Parse a REST response. If the response contains an error field, we will
raise it as an exception.
"""
body = json.loads(response)
try:
error = body['error']['description']
code = body['error']['code']
exc... | python | {
"resource": ""
} |
q41976 | Transport.request | train | def request(self, action, data={}, headers={}, method='GET'):
"""
Run the HTTP request against the Clickatell API
:param str action: The API action
:param dict data: The request parameters
:param dict headers: The request headers (if any)
:param str method... | python | {
"resource": ""
} |
q41977 | OperationsViewSet.serialize_operations | train | def serialize_operations(self, operations):
"""Serialize a list of operations into JSON."""
serialized_ops = []
for operation in operations:
serializer = self.get_serializer_class(operation.__class__)
serialized_ops.append(serializer(operation).data)
return seria... | python | {
"resource": ""
} |
q41978 | OperationsViewSet.get | train | def get(self, request, pzone_pk):
"""Get all the operations for a given pzone."""
# attempt to get given pzone
try:
pzone = PZone.objects.get(pk=pzone_pk)
except PZone.DoesNotExist:
raise Http404("Cannot find given pzone.")
# bulid filters
filter... | python | {
"resource": ""
} |
q41979 | OperationsViewSet.post | train | def post(self, request, pzone_pk):
"""Add a new operation to the given pzone, return json of the new operation."""
# attempt to get given content list
pzone = None
try:
pzone = PZone.objects.get(pk=pzone_pk)
except PZone.DoesNotExist:
raise Http404("Canno... | python | {
"resource": ""
} |
q41980 | OperationsViewSet.delete | train | def delete(self, request, pzone_pk, operation_pk):
"""Remove an operation from the given pzone."""
# note : we're not using the pzone_pk here since it's not actually
# necessary for getting an operation by pk, but it sure makes the urls
# nicer!
# attempt to delete operatio... | python | {
"resource": ""
} |
q41981 | PZoneViewSet.perform_update | train | def perform_update(self, serializer):
"""creates a record in the `bulbs.promotion.PZoneHistory`
:param obj: the instance saved
:param created: boolean expressing if the object was newly created (`False` if updated)
"""
instance = serializer.save()
# create history object... | python | {
"resource": ""
} |
q41982 | PZoneViewSet.retrieve | train | def retrieve(self, request, *args, **kwargs):
"""Retrieve pzone as a preview or applied if no preview is provided."""
when_param = get_query_params(self.request).get("preview", None)
pk = self.kwargs["pk"]
when = None
if when_param:
try:
when = parse... | python | {
"resource": ""
} |
q41983 | EventLoop.current | train | def current(cls):
"""Get the current event loop singleton object.
"""
try:
return _tls.loop
except AttributeError:
# create loop only for main thread
if threading.current_thread().name == 'MainThread':
_tls.loop = cls()
... | python | {
"resource": ""
} |
q41984 | set_volume | train | def set_volume(percentage):
'''Set the volume.
Sets the volume to a given percentage (integer between 0 and 100).
Args:
percentage (int): The percentage (as a 0 to 100 integer) to set the volume to.
Raises:
ValueError: if the percentage is >100 or <0.
'''
if percentage > 100 or percentage < 0:
raise V... | python | {
"resource": ""
} |
q41985 | get_volume | train | def get_volume():
'''Get the volume.
Get the current volume.
Returns:
int: The current volume (percentage, between 0 and 100).
'''
if system.get_name() == 'windows':
# TODO: Implement volume for Windows. Looks like WinAPI is the
# solution...
pass
elif system.get_name() == 'mac':
volume = system.ge... | python | {
"resource": ""
} |
q41986 | increase_volume | train | def increase_volume(percentage):
'''Increase the volume.
Increase the volume by a given percentage.
Args:
percentage (int): The percentage (as an integer between 0 and 100) to increase the volume by.
Raises:
ValueError: if the percentage is >100 or <0.
'''
if percentage > 100 or percentage < 0:
raise ... | python | {
"resource": ""
} |
q41987 | mute | train | def mute():
'''Mute the volume.
Mutes the volume.
'''
# NOTE: mute != 0 volume
if system.get_name() == 'windows':
# TODO: Implement volume for Windows. Looks like WinAPI is the
# solution...
pass
elif system.get_name() == 'mac':
sp.Popen(['osascript', '-e', 'set volume output muted true']).wait()
el... | python | {
"resource": ""
} |
q41988 | unmute | train | def unmute():
'''Unmute the volume.
Unmutes the system volume.
Note:
On some systems, volume is restored to its previous level after unmute, or set to 100.
'''
if system.get_name() == 'windows':
# TODO: Implement volume for Windows. Looks like WinAPI is the
# solution...
pass
elif system.get_name() =... | python | {
"resource": ""
} |
q41989 | AuthenticationsLogAPI.query_by_login | train | def query_by_login(self, login_id, end_time=None, start_time=None):
"""
Query by login.
List authentication events for a given login.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - login_id
"""ID"""
path["login_id"] =... | python | {
"resource": ""
} |
q41990 | AuthenticationsLogAPI.query_by_account | train | def query_by_account(self, account_id, end_time=None, start_time=None):
"""
Query by account.
List authentication events for a given account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["ac... | python | {
"resource": ""
} |
q41991 | AuthenticationsLogAPI.query_by_user | train | def query_by_user(self, user_id, end_time=None, start_time=None):
"""
Query by user.
List authentication events for a given user.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_... | python | {
"resource": ""
} |
q41992 | PluginDict._sorted_keys | train | def _sorted_keys(self):
"""
Return list of keys sorted by version
Sorting is done based on :py:func:`pkg_resources.parse_version`
"""
try:
keys = self._cache['sorted_keys']
except KeyError:
keys = self._cache['sorted_keys'] = sorted(self.keys(), ... | python | {
"resource": ""
} |
q41993 | PluginDict._process_blacklist | train | def _process_blacklist(self, blacklist):
"""
Process blacklist into set of excluded versions
"""
# Assume blacklist is correct format since it is checked by PluginLoader
blacklist_cache = {}
blacklist_cache_old = self._cache.get('blacklist', {})
for entry in bl... | python | {
"resource": ""
} |
q41994 | find | train | def find(pred, items):
"""
Find the index of the first element in items for which pred returns
True
>>> find(lambda x: x > 3, range(100))
4
>>> find(lambda x: x < -3, range(100)) is None
True
"""
for i, item in enumerate(items):
if pred(item):
return i | python | {
"resource": ""
} |
q41995 | SummableVersion.reset_less_significant | train | def reset_less_significant(self, significant_version):
"""
Reset to zero all version info less significant than the
indicated version.
>>> ver = SummableVersion('3.1.2')
>>> ver.reset_less_significant(SummableVersion('0.1'))
>>> str(ver)
'3.1'
"""
def nonzero(x):
return x != 0
version_len = 3 #... | python | {
"resource": ""
} |
q41996 | VersionManagement.get_tagged_version | train | def get_tagged_version(self):
"""
Get the version of the local working set as a StrictVersion or
None if no viable tag exists. If the local working set is itself
the tagged commit and the tip and there are no local
modifications, use the tag on the parent changeset.
"""
tags = list(self.get_tags())
if '... | python | {
"resource": ""
} |
q41997 | VersionManagement.get_next_version | train | def get_next_version(self, increment=None):
"""
Return the next version based on prior tagged releases.
"""
increment = increment or self.increment
return self.infer_next_version(self.get_latest_version(), increment) | python | {
"resource": ""
} |
q41998 | AccountNotificationsAPI.create_global_notification | train | def create_global_notification(self, account_id, account_notification_end_at, account_notification_subject, account_notification_message, account_notification_start_at, account_notification_icon=None, account_notification_roles=None):
"""
Create a global notification.
Create and return a ne... | python | {
"resource": ""
} |
q41999 | adapt_persistent_instance | train | def adapt_persistent_instance(persistent_object, target_rest_class=None, attribute_filter=None):
"""
Adapts a single persistent instance to a REST model; at present this is a
common method for all persistent backends.
Refer to: https://groups.google.com/forum/#!topic/prestans-discuss/dO1yx8f60as
fo... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.