_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q42200
same_page_choosen
train
def same_page_choosen(form, field): """Check that we are not trying to assign list page itself as a child.""" if form._obj is not None: if field.data.id == form._obj.list_id: raise ValidationError( _('You cannot assign list page itself as a child.'))
python
{ "resource": "" }
q42201
cols_str
train
def cols_str(columns): """Concatenate list of columns into a string.""" cols = "" for c in columns: cols = cols + wrap(c) + ', ' return cols[:-2]
python
{ "resource": "" }
q42202
join_cols
train
def join_cols(cols): """Join list of columns into a string for a SQL query""" return ", ".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols
python
{ "resource": "" }
q42203
create_order_classes
train
def create_order_classes(model_label, order_field_names): """ Create order model and admin class. Add order model to order.models module and register admin class. Connect ordered_objects manager to related model. """ # Seperate model_label into parts. labels = resolve_labels(model_label) ...
python
{ "resource": "" }
q42204
create_order_objects
train
def create_order_objects(model, order_fields): """ Create order items for objects already present in the database. """ for rel in model._meta.get_all_related_objects(): rel_model = rel.model if rel_model.__module__ == 'order.models': objs = model.objects.all() va...
python
{ "resource": "" }
q42205
is_orderable
train
def is_orderable(cls): """ Checks if the provided class is specified as an orderable in settings.ORDERABLE_MODELS. If it is return its settings. """ if not getattr(settings, 'ORDERABLE_MODELS', None): return False labels = resolve_labels(cls) if labels['app_model'] in settings.ORDER...
python
{ "resource": "" }
q42206
resolve_labels
train
def resolve_labels(model_label): """ Seperate model_label into parts. Returns dictionary with app, model and app_model strings. """ labels = {} # Resolve app label. labels['app'] = model_label.split('.')[0] # Resolve model label labels['model'] = model_label.split('.')[-1] # R...
python
{ "resource": "" }
q42207
ContentViewSet.get_serializer_class
train
def get_serializer_class(self): """gets the class type of the serializer :return: `rest_framework.Serializer` """ klass = None lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field if lookup_url_kwarg in self.kwargs: # Looks like this is a detail... ...
python
{ "resource": "" }
q42208
ContentViewSet.publish
train
def publish(self, request, **kwargs): """sets the `published` value of the `Content` :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ content = self.get_object() if "published" in g...
python
{ "resource": "" }
q42209
ContentViewSet.trash
train
def trash(self, request, **kwargs): """Psuedo-deletes a `Content` instance and removes it from the ElasticSearch index Content is not actually deleted, merely hidden by deleted from ES index.import :param request: a WSGI request object :param kwargs: keyword arguments (optional) ...
python
{ "resource": "" }
q42210
ContentViewSet.contributions
train
def contributions(self, request, **kwargs): """gets or adds contributions :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ # Check if the contribution app is installed if Contributio...
python
{ "resource": "" }
q42211
ContentViewSet.create_token
train
def create_token(self, request, **kwargs): """Create a new obfuscated url info to use for accessing unpublished content. :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ data = { ...
python
{ "resource": "" }
q42212
ContentViewSet.list_tokens
train
def list_tokens(self, request, **kwargs): """List all tokens for this content instance. :param request: a WSGI request object :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ # no date checking is done here to make it more obvi...
python
{ "resource": "" }
q42213
LogEntryViewSet.get_queryset
train
def get_queryset(self): """creates the base queryset object for the serializer :return: an instance of `django.db.models.QuerySet` """ qs = LogEntry.objects.all() content_id = get_query_params(self.request).get("content", None) if content_id: qs = qs.filter(o...
python
{ "resource": "" }
q42214
AuthorViewSet.get_queryset
train
def get_queryset(self): """created the base queryset object for the serializer limited to users within the authors groups and having `is_staff` :return: `django.db.models.QuerySet` """ author_filter = getattr(settings, "BULBS_AUTHOR_FILTER", {"is_staff": True}) queryset ...
python
{ "resource": "" }
q42215
MeViewSet.retrieve
train
def retrieve(self, request, *args, **kwargs): """gets basic information about the user :param request: a WSGI request object :param args: inline arguments (optional) :param kwargs: keyword arguments (optional) :return: `rest_framework.response.Response` """ data ...
python
{ "resource": "" }
q42216
ContentTypeViewSet.list
train
def list(self, request): """Search the doctypes for this model.""" query = get_query_params(request).get("search", "") results = [] base = self.model.get_base_class() doctypes = indexable_registry.families[base] for doctype, klass in doctypes.items(): name = k...
python
{ "resource": "" }
q42217
CourseAuditLogAPI.query_by_course
train
def query_by_course(self, course_id, end_time=None, start_time=None): """ Query by course. List course change events for a given course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_i...
python
{ "resource": "" }
q42218
vary_radius
train
def vary_radius(dt): """Vary the disc radius over time""" global time time += dt disc.inner_radius = disc.outer_radius = 2.5 + math.sin(time / 2.0) * 1.5
python
{ "resource": "" }
q42219
to_str
train
def to_str(delta, extended=False): """Format a datetime.timedelta to a duration string""" total_seconds = delta.total_seconds() sign = "-" if total_seconds < 0 else "" nanoseconds = abs(total_seconds * _second_size) if total_seconds < 1: result_str = _to_str_small(nanoseconds, extended) ...
python
{ "resource": "" }
q42220
Alter.create_database
train
def create_database(self, name): """Create a new database.""" statement = "CREATE DATABASE {0} DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci".format(wrap(name)) return self.execute(statement)
python
{ "resource": "" }
q42221
Alter.create_table
train
def create_table(self, name, data, columns=None, add_pk=True): """Generate and execute a create table query by parsing a 2D dataset""" # TODO: Issue occurs when bool values exist in data # Remove if the table exists if name in self.tables: self.drop(name) # Set heade...
python
{ "resource": "" }
q42222
Notification._get_notification
train
def _get_notification(self, email, token): ''' Consulta o status do pagamento ''' url = u'{notification_url}{notification_code}?email={email}&token={token}'.format( notification_url=self.notification_url, notification_code=self.notification_code, email=email, ...
python
{ "resource": "" }
q42223
Notification.items
train
def items(self): ''' Lista dos items do pagamento ''' if type(self.transaction['items']['item']) == list: return self.transaction['items']['item'] else: return [self.transaction['items']['item'],]
python
{ "resource": "" }
q42224
PollsAPI.create_single_poll
train
def create_single_poll(self, polls_question, polls_description=None): """ Create a single poll. Create a new poll for the current user """ path = {} data = {} params = {} # REQUIRED - polls[question] """The title of the poll.""" ...
python
{ "resource": "" }
q42225
content_deleted
train
def content_deleted(sender, instance=None, **kwargs): """removes content from the ES index when deleted from DB """ if getattr(instance, "_index", True): cls = instance.get_real_instance_class() index = cls.search_objects.mapping.index doc_type = cls.search_objects.mapping.doc_type ...
python
{ "resource": "" }
q42226
Content.thumbnail
train
def thumbnail(self): """Read-only attribute that provides the value of the thumbnail to display. """ # check if there is a valid thumbnail override if self.thumbnail_override.id is not None: return self.thumbnail_override # otherwise, just try to grab the first image...
python
{ "resource": "" }
q42227
Content.first_image
train
def first_image(self): """Ready-only attribute that provides the value of the first non-none image that's not the thumbnail override field. """ # loop through image fields and grab the first non-none one for model_field in self._meta.fields: if isinstance(model_field,...
python
{ "resource": "" }
q42228
Content.get_absolute_url
train
def get_absolute_url(self): """produces a url to link directly to this instance, given the URL config :return: `str` """ try: url = reverse("content-detail-view", kwargs={"pk": self.pk, "slug": self.slug}) except NoReverseMatch: url = None return ...
python
{ "resource": "" }
q42229
Content.ordered_tags
train
def ordered_tags(self): """gets the related tags :return: `list` of `Tag` instances """ tags = list(self.tags.all()) return sorted( tags, key=lambda tag: ((type(tag) != Tag) * 100000) + tag.count(), reverse=True )
python
{ "resource": "" }
q42230
Content.save
train
def save(self, *args, **kwargs): """creates the slug, queues up for indexing and saves the instance :param args: inline arguments (optional) :param kwargs: keyword arguments :return: `bulbs.content.Content` """ if not self.slug: self.slug = slugify(self.build...
python
{ "resource": "" }
q42231
LogEntryManager.log
train
def log(self, user, content, message): """creates a new log record :param user: user :param content: content instance :param message: change information """ return self.create( user=user, content_type=ContentType.objects.get_for_model(content), ...
python
{ "resource": "" }
q42232
ObfuscatedUrlInfo.save
train
def save(self, *args, **kwargs): """sets uuid for url :param args: inline arguments (optional) :param kwargs: keyword arguments (optional) :return: `super.save()` """ if not self.id: # this is a totally new instance, create uuid value self.url_uuid = str(uui...
python
{ "resource": "" }
q42233
splaylist.write_playlist_file
train
def write_playlist_file(self, localdir): """ Check if playlist exists in local directory. """ path = "{0}/playlists".format(localdir) if not os.path.exists(path): os.makedirs(path) filepath = "{0}/{1}".format(path, self.gen_filename()) playlist = open(filepath, "w") ...
python
{ "resource": "" }
q42234
Model._create_instance_attributes
train
def _create_instance_attributes(self, arguments): """ Copies class level attribute templates and makes instance placeholders This step is required for direct uses of Model classes. This creates a copy of attribute_names ignores methods and private variables. DataCollection types...
python
{ "resource": "" }
q42235
Model.get_attribute_keys
train
def get_attribute_keys(self): """ Returns a list of managed attributes for the Model class Implemented for use with data adapters, can be used to quickly make a list of the attribute names in a prestans model """ _attribute_keys = list() for attribute_name, typ...
python
{ "resource": "" }
q42236
Model.as_serializable
train
def as_serializable(self, attribute_filter=None, minified=False): """ Returns a dictionary with attributes and pure python representation of the data instances. If an attribute filter is provided as_serializable will respect the visibility. The response is used by serializers to...
python
{ "resource": "" }
q42237
EnrollmentsAPI.enroll_user_courses
train
def enroll_user_courses(self, course_id, enrollment_type, enrollment_user_id, enrollment_associated_user_id=None, enrollment_course_section_id=None, enrollment_enrollment_state=None, enrollment_limit_privileges_to_course_section=None, enrollment_notify=None, enrollment_role=None, enrollment_role_id=None, enrollment_sel...
python
{ "resource": "" }
q42238
EnrollmentsAPI.conclude_deactivate_or_delete_enrollment
train
def conclude_deactivate_or_delete_enrollment(self, id, course_id, task=None): """ Conclude, deactivate, or delete an enrollment. Conclude, deactivate, or delete an enrollment. If the +task+ argument isn't given, the enrollment will be concluded. """ path = {} ...
python
{ "resource": "" }
q42239
filter_ints_based_on_vlan
train
def filter_ints_based_on_vlan(interfaces, vlan, count=1): """ Filter list of interfaces based on VLAN presence or absence criteria. :param interfaces: list of interfaces to filter. :param vlan: boolean indicating whether to filter interfaces with or without VLAN. :param vlan: number of expected VLANs (...
python
{ "resource": "" }
q42240
IxnInterface._create
train
def _create(self, **attributes): """ Create new interface on IxNetwork. Set enabled and description (==name). :return: interface object reference. """ attributes['enabled'] = True if 'name' in self._data: attributes['description'] = self._data['name'] ...
python
{ "resource": "" }
q42241
DatabaseSchemaEditor._constraint_names
train
def _constraint_names(self, model, column_names=None, unique=None, primary_key=None, index=None, foreign_key=None, check=None): """ Returns all constraint names matching the columns and conditions """ column_names = list(column_names) i...
python
{ "resource": "" }
q42242
login_required
train
def login_required(http_method_handler): """ provides a decorator for RESTRequestHandler methods to check for authenticated users RESTRequestHandler subclass must have a auth_context instance, refer to prestans.auth for the parent class definition. If decorator is used and no auth_context is provi...
python
{ "resource": "" }
q42243
role_required
train
def role_required(role_name=None): """ Authenticates a HTTP method handler based on a provided role With a little help from Peter Cole's Blog http://mrcoles.com/blog/3-decorator-examples-and-awesome-python/ """ def _role_required(http_method_handler): @wraps(http_method_handler) ...
python
{ "resource": "" }
q42244
access_required
train
def access_required(config=None): """ Authenticates a HTTP method handler based on a custom set of arguments """ def _access_required(http_method_handler): def secure_http_method_handler(self, *args, **kwargs): # authentication context must be set if not self.__provide...
python
{ "resource": "" }
q42245
gen_cmake_command
train
def gen_cmake_command(config): """ Generate CMake command. """ from autocmake.extract import extract_list s = [] s.append("\n\ndef gen_cmake_command(options, arguments):") s.append(' """') s.append(" Generate CMake command based on options and arguments.") s.append(' """') ...
python
{ "resource": "" }
q42246
gen_setup
train
def gen_setup(config, default_build_type, relative_path, setup_script_name): """ Generate setup script. """ from autocmake.extract import extract_list s = [] s.append('#!/usr/bin/env python') s.append('\n{0}'.format(autogenerated_notice())) s.append('\nimport os') s.append('import s...
python
{ "resource": "" }
q42247
gen_cmakelists
train
def gen_cmakelists(project_name, project_language, min_cmake_version, default_build_type, relative_path, modules): """ Generate CMakeLists.txt. """ import os s = [] s.append(autogenerated_notice()) s.append('\n# set minimum cmake version') s.append('cmake_minimum_required(VERSION {0} ...
python
{ "resource": "" }
q42248
align_options
train
def align_options(options): """ Indents flags and aligns help texts. """ l = 0 for opt in options: if len(opt[0]) > l: l = len(opt[0]) s = [] for opt in options: s.append(' {0}{1} {2}'.format(opt[0], ' ' * (l - len(opt[0])), opt[1])) return '\n'.join(s)
python
{ "resource": "" }
q42249
format_exception
train
def format_exception(etype, value, tback, limit=None): """ Python 2 compatible version of traceback.format_exception Accepts negative limits like the Python 3 version """ rtn = ['Traceback (most recent call last):\n'] if limit is None or limit >= 0: rtn.extend(traceback.format_tb(tback...
python
{ "resource": "" }
q42250
PluginLoader.load_modules
train
def load_modules(self): """ Locate and import modules from locations specified during initialization. Locations include: - Program's standard library (``library``) - `Entry points <Entry point_>`_ (``entry_point``) - Specified modules (``modules``) ...
python
{ "resource": "" }
q42251
PluginLoader.plugins
train
def plugins(self): """ Newest version of all plugins in the group filtered by ``blacklist`` Returns: dict: Nested dictionary of plugins accessible through dot-notation. Plugins are returned in a nested dictionary, but can also be accessed through dot-notion. Just as...
python
{ "resource": "" }
q42252
PluginLoader.plugins_all
train
def plugins_all(self): """ All resulting versions of all plugins in the group filtered by ``blacklist`` Returns: dict: Nested dictionary of plugins accessible through dot-notation. Similar to :py:attr:`plugins`, but lowest level is a regular dictionary of all unfilt...
python
{ "resource": "" }
q42253
Insert.insert_uniques
train
def insert_uniques(self, table, columns, values): """ Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted """ # Rows that...
python
{ "resource": "" }
q42254
Insert.insert
train
def insert(self, table, columns, values, execute=True): """Insert a single row into a table.""" # TODO: Cant accept lists? # Concatenate statement cols, vals = get_col_val_str(columns) statement = "INSERT INTO {0} ({1}) VALUES ({2})".format(wrap(table), cols, vals) # Exe...
python
{ "resource": "" }
q42255
Insert.insert_many
train
def insert_many(self, table, columns, values, limit=MAX_ROWS_PER_QUERY, execute=True): """ Insert multiple rows into a table. If only one row is found, self.insert method will be used. """ # Make values a list of lists if it is a flat list if not isinstance(values[0], (l...
python
{ "resource": "" }
q42256
QuizzesAPI.list_quizzes_in_course
train
def list_quizzes_in_course(self, course_id, search_term=None): """ List quizzes in a course. Returns the list of Quizzes in this course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_i...
python
{ "resource": "" }
q42257
QuizzesAPI.create_quiz
train
def create_quiz(self, course_id, quiz_title, quiz_access_code=None, quiz_allowed_attempts=None, quiz_assignment_group_id=None, quiz_cant_go_back=None, quiz_description=None, quiz_due_at=None, quiz_hide_correct_answers_at=None, quiz_hide_results=None, quiz_ip_filter=None, quiz_lock_at=None, quiz_one_question_at_a_time=N...
python
{ "resource": "" }
q42258
QuizzesAPI.validate_quiz_access_code
train
def validate_quiz_access_code(self, id, course_id, access_code): """ Validate quiz access code. Accepts an access code and returns a boolean indicating whether that access code is correct """ path = {} data = {} params = {} # REQUIRED - PATH - ...
python
{ "resource": "" }
q42259
run_suite
train
def run_suite(case, config, summary): """ Run the full suite of validation tests """ m = _load_case_module(case, config) result = m.run(case, config) summary[case] = _summarize_result(m, result) _print_summary(m, case, summary) if result['Type'] == 'Book': for name, page in six.iter...
python
{ "resource": "" }
q42260
ArgParserFactory._add_generate_sub_commands
train
def _add_generate_sub_commands(self): """ Sub commands for generating models for usage by clients. Currently supports Google Closure. """ gen_parser = self._subparsers_handle.add_parser( name="gen", help="generate client side model stubs, filters" ...
python
{ "resource": "" }
q42261
CommandDispatcher._dispatch_gen
train
def _dispatch_gen(self): """ Process the generate subset of commands. """ if not os.path.isdir(self._args.output): raise exception.Base("%s is not a writeable directory" % self._args.output) if not os.path.isfile(self._args.models_definition): if not sel...
python
{ "resource": "" }
q42262
SearchParty.search
train
def search(self): """Return a search using the combined query of all associated special coverage objects.""" # Retrieve all Or filters pertinent to the special coverage query. should_filters = [ es_filter.Terms(pk=self.query.get("included_ids", [])), es_filter.Terms(pk=se...
python
{ "resource": "" }
q42263
SearchParty.get_group_filters
train
def get_group_filters(self): """Return es OR filters to include all special coverage group conditions.""" group_filters = [] field_map = { "feature-type": "feature_type.slug", "tag": "tags.slug", "content-type": "_type" } for group_set in self....
python
{ "resource": "" }
q42264
SearchParty.query
train
def query(self): """Group the self.special_coverages queries and memoize them.""" if not self._query: self._query.update({ "excluded_ids": [], "included_ids": [], "pinned_ids": [], "groups": [], }) for sp...
python
{ "resource": "" }
q42265
sam2rnf
train
def sam2rnf(args): """Convert SAM to RNF-based FASTQ with respect to argparse parameters. Args: args (...): Arguments parsed by argparse """ rnftools.mishmash.Source.recode_sam_reads( sam_fn=args.sam_fn, fastq_rnf_fo=args.fq_fo, fai_fo=args.fai_fo, genome_id=args.genome_id,...
python
{ "resource": "" }
q42266
add_sam2rnf_parser
train
def add_sam2rnf_parser(subparsers, subcommand, help, description, simulator_name=None): """Add another parser for a SAM2RNF-like command. Args: subparsers (subparsers): File name of the genome from which read tuples are created (FASTA file). simulator_name (str): Name of the simulator used in comments. """ ...
python
{ "resource": "" }
q42267
list_roles
train
def list_roles(self, account_id, show_inherited=None, state=None): """ List roles. List the roles available to an account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """The id of the account to retrieve roles fo...
python
{ "resource": "" }
q42268
get_single_role
train
def get_single_role(self, id, role_id, account_id, role=None): """ Get a single role. Retrieve information about a single role """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # RE...
python
{ "resource": "" }
q42269
Operations.execute_script
train
def execute_script(self, sql_script=None, commands=None, split_algo='sql_split', prep_statements=False, dump_fails=True, execute_fails=True, ignored_commands=('DROP', 'UNLOCK', 'LOCK')): """Wrapper method for SQLScript class.""" ss = Execute(sql_script, split_algo, prep_statements...
python
{ "resource": "" }
q42270
Operations.script
train
def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True): """Wrapper method providing access to the SQLScript class's methods and properties.""" return Execute(sql_script, split_algo, prep_statements, dump_fails, self)
python
{ "resource": "" }
q42271
OAuthAuthentication.obtain_token
train
def obtain_token(self, redirect_url: str, state: str) -> str: """ Exchange the code that was obtained using `authorize_url` for an authorization token. The code is extracted from the URL that redirected the user back to your site. Example: >>> auth = OAuthAuthentication('htt...
python
{ "resource": "" }
q42272
sql_column_type
train
def sql_column_type(column_data, prefer_varchar=False, prefer_int=False): """ Retrieve the best fit data type for a column of a MySQL table. Accepts a iterable of values ONLY for the column whose data type is in question. :param column_data: Iterable of values from a MySQL table column :param ...
python
{ "resource": "" }
q42273
ValueType.get_sql
train
def get_sql(self): """Retrieve the data type for a data record.""" test_method = [ self.is_time, self.is_date, self.is_datetime, self.is_decimal, self.is_year, self.is_tinyint, self.is_smallint, self.is_mediu...
python
{ "resource": "" }
q42274
ValueType.get_type_len
train
def get_type_len(self): """Retrieve the type and length for a data record.""" # Check types and set type/len self.get_sql() return self.type, self.len, self.len_decimal
python
{ "resource": "" }
q42275
SectionsAPI.create_course_section
train
def create_course_section(self, course_id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None, enable_sis_reactivation=None): """ Create course section. Creates a n...
python
{ "resource": "" }
q42276
SectionsAPI.edit_section
train
def edit_section(self, id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None): """ Edit a section. Modify an existing section. """ path = {} ...
python
{ "resource": "" }
q42277
Connector.change_db
train
def change_db(self, db, user=None): """Change connect database.""" # Get original config and change database key config = self._config config['database'] = db if user: config['user'] = user self.database = db # Close current database connection ...
python
{ "resource": "" }
q42278
Connector.execute
train
def execute(self, command): """Execute a single SQL query without returning a result.""" self._cursor.execute(command) self._commit() return True
python
{ "resource": "" }
q42279
Connector.executemany
train
def executemany(self, command, params=None, max_attempts=5): """Execute multiple SQL queries without returning a result.""" attempts = 0 while attempts < max_attempts: try: # Execute statement self._cursor.executemany(command, params) s...
python
{ "resource": "" }
q42280
Connector._connect
train
def _connect(self, config): """Establish a connection with a MySQL database.""" if 'connection_timeout' not in self._config: self._config['connection_timeout'] = 480 try: self._cnx = connect(**config) self._cursor = self._cnx.cursor() self._printer...
python
{ "resource": "" }
q42281
Connector._fetch
train
def _fetch(self, statement, commit, max_attempts=5): """ Execute a SQL query and return a result. Recursively disconnect and reconnect to the database if an error occurs. """ if self._auto_reconnect: attempts = 0 while attempts < max_attempts: ...
python
{ "resource": "" }
q42282
resize
train
def resize(widthWindow, heightWindow): """Initial settings for the OpenGL state machine, clear color, window size, etc""" glEnable(GL_BLEND) glEnable(GL_POINT_SMOOTH) glShadeModel(GL_SMOOTH)# Enables Smooth Shading glBlendFunc(GL_SRC_ALPHA,GL_ONE)#Type Of Blending To Perform glHint(GL_PERSPECTIVE_CORRECTION_HINT,...
python
{ "resource": "" }
q42283
Bumper.set_bumper_color
train
def set_bumper_color(self, particle, group, bumper, collision_point, collision_normal): """Set bumper color to the color of the particle that collided with it""" self.color = tuple(particle.color)[:3]
python
{ "resource": "" }
q42284
RabaQuery.reset
train
def reset(self, rabaClass, namespace = None) : """rabaClass can either be a raba class of a string of a raba class name. In the latter case you must provide the namespace argument. If it's a Raba Class the argument is ignored. If you fear cicular imports use strings""" if type(rabaClass) is types.StringType : ...
python
{ "resource": "" }
q42285
RabaQuery.addFilter
train
def addFilter(self, *lstFilters, **dctFilters) : "add a new filter to the query" dstF = {} if len(lstFilters) > 0 : if type(lstFilters[0]) is types.DictType : dstF = lstFilters[0] lstFilters = lstFilters[1:] if len(dctFilters) > 0 : dstF = dict(dstF, **dctFilters) filts = {} for k, v in dst...
python
{ "resource": "" }
q42286
RabaQuery.count
train
def count(self, sqlTail = '') : "Compile filters and counts the number of results. You can use sqlTail to add things such as order by" sql, sqlValues = self.getSQLQuery(count = True) return int(self.con.execute('%s %s'% (sql, sqlTail), sqlValues).fetchone()[0])
python
{ "resource": "" }
q42287
Schema.show_schema
train
def show_schema(self, tables=None): """Print schema information.""" tables = tables if tables else self.tables for t in tables: self._printer('\t{0}'.format(t)) for col in self.get_schema(t, True): self._printer('\t\t{0:30} {1:15} {2:10} {3:10} {4:10} {5:1...
python
{ "resource": "" }
q42288
Schema.get_schema_dict
train
def get_schema_dict(self, table): """ Retrieve the database schema in key, value pairs for easier references and comparisons. """ # Retrieve schema in list form schema = self.get_schema(table, with_headers=True) # Pop headers from first item in list heade...
python
{ "resource": "" }
q42289
Schema.get_schema
train
def get_schema(self, table, with_headers=False): """Retrieve the database schema for a particular table.""" f = self.fetch('desc ' + wrap(table)) if not isinstance(f[0], list): f = [f] # Replace None with '' schema = [['' if col is None else col for col in row] for r...
python
{ "resource": "" }
q42290
Schema.add_column
train
def add_column(self, table, name='ID', data_type='int(11)', after_col=None, null=False, primary_key=False): """Add a column to an existing table.""" location = 'AFTER {0}'.format(after_col) if after_col else 'FIRST' null_ = 'NULL' if null else 'NOT NULL' comment = "COMMENT 'Column auto c...
python
{ "resource": "" }
q42291
Schema.drop_column
train
def drop_column(self, table, name): """Remove a column to an existing table.""" try: self.execute('ALTER TABLE {0} DROP COLUMN {1}'.format(wrap(table), name)) self._printer('\tDropped column {0} from {1}'.format(name, table)) except ProgrammingError: self._pri...
python
{ "resource": "" }
q42292
Schema.drop_index
train
def drop_index(self, table, column): """Drop an index from a table.""" self.execute('ALTER TABLE {0} DROP INDEX {1}'.format(wrap(table), column)) self._printer('\tDropped index from column {0}'.format(column))
python
{ "resource": "" }
q42293
Schema.add_comment
train
def add_comment(self, table, column, comment): """Add a comment to an existing column in a table.""" col_def = self.get_column_definition(table, column) query = "ALTER TABLE {0} MODIFY COLUMN {1} {2} COMMENT '{3}'".format(table, column, col_def, comment) self.execute(query) self....
python
{ "resource": "" }
q42294
ModulesAPI.list_modules
train
def list_modules(self, course_id, include=None, search_term=None, student_id=None): """ List modules. List the modules in a course """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = ...
python
{ "resource": "" }
q42295
ModulesAPI.create_module
train
def create_module(self, course_id, module_name, module_position=None, module_prerequisite_module_ids=None, module_publish_final_grade=None, module_require_sequential_progress=None, module_unlock_at=None): """ Create a module. Create and return a new module """ path = {} ...
python
{ "resource": "" }
q42296
ModulesAPI.create_module_item
train
def create_module_item(self, course_id, module_id, module_item_type, module_item_content_id, module_item_completion_requirement_min_score=None, module_item_completion_requirement_type=None, module_item_external_url=None, module_item_indent=None, module_item_new_tab=None, module_item_page_url=None, module_item_position=...
python
{ "resource": "" }
q42297
ModulesAPI.update_module_item
train
def update_module_item(self, id, course_id, module_id, module_item_completion_requirement_min_score=None, module_item_completion_requirement_type=None, module_item_external_url=None, module_item_indent=None, module_item_module_id=None, module_item_new_tab=None, module_item_position=None, module_item_published=None, mod...
python
{ "resource": "" }
q42298
ModulesAPI.select_mastery_path
train
def select_mastery_path(self, id, course_id, module_id, assignment_set_id=None, student_id=None): """ Select a mastery path. Select a mastery path when module item includes several possible paths. Requires Mastery Paths feature to be enabled. Returns a compound document w...
python
{ "resource": "" }
q42299
ModulesAPI.get_module_item_sequence
train
def get_module_item_sequence(self, course_id, asset_id=None, asset_type=None): """ Get module item sequence. Given an asset in a course, find the ModuleItem it belongs to, and also the previous and next Module Items in the course sequence. """ path = {} d...
python
{ "resource": "" }