_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q42000
ModelAdapter.adapt_persistent_to_rest
train
def adapt_persistent_to_rest(self, persistent_object, attribute_filter=None): """ adapts a persistent model to a rest model by inspecting """ # convert filter to immutable if it isn't already if isinstance(attribute_filter, parser.AttributeFilter): attribute_filter = ...
python
{ "resource": "" }
q42001
Solr._send_solr_command
train
def _send_solr_command(self, core_url, json_command): """ Sends JSON string to Solr instance """ # Check document language and dispatch to correct core url = _get_url(core_url, "update") try: response = self.req_session.post(url, data=json_command, headers={'...
python
{ "resource": "" }
q42002
Solr.add
train
def add(self, documents, boost=None): """ Adds documents to Solr index documents - Single item or list of items to add """ if not isinstance(documents, list): documents = [documents] documents = [{'doc': d} for d in documents] if boost: fo...
python
{ "resource": "" }
q42003
Solr._addFlushBatch
train
def _addFlushBatch(self): """ Sends all waiting documents to Solr """ if len(self._add_batch) > 0: language_batches = {} # Create command JSONs for each of language endpoints for lang in self.endpoints: # Append documents with language...
python
{ "resource": "" }
q42004
Solr.deleteAll
train
def deleteAll(self): """ Deletes whole Solr index. Use with care. """ for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{\"delete\": { \"query\" : \"*:*\"}}")
python
{ "resource": "" }
q42005
Solr.delete
train
def delete(self, id): """ Deletes document with ID on all Solr cores """ for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{\"delete\" : { \"id\" : \"%s\"}}" % (id,))
python
{ "resource": "" }
q42006
Solr.commit
train
def commit(self): """ Flushes all pending changes and commits Solr changes """ self._addFlushBatch() for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{ \"commit\":{} }")
python
{ "resource": "" }
q42007
Solr._get_shards
train
def _get_shards(self): """ Returns comma separated list of configured Solr cores """ if self._shards is None: endpoints = [] for endpoint in self.endpoints: # We need to remove and http:// prefixes from URLs url = urlparse.urlparse(...
python
{ "resource": "" }
q42008
Solr._parse_response
train
def _parse_response(self, results): """ Parses result dictionary into a SolrResults object """ dict_response = results.get("response") result_obj = SolrResults() result_obj.query_time = results.get("responseHeader").get("QTime", None) result_obj.results_count = d...
python
{ "resource": "" }
q42009
Solr.query
train
def query(self, query, filters=None, columns=None, sort=None, start=0, rows=30): """ Queries Solr and returns results query - Text query to search for filters - dictionary of filters to apply when searching in form of { "field":"filter_value" } columns - columns to return, list ...
python
{ "resource": "" }
q42010
Solr.more_like_this
train
def more_like_this(self, query, fields, columns=None, start=0, rows=30): """ Retrieves "more like this" results for a passed query document query - query for a document on which to base similar documents fields - fields on which to base similarity estimation (either comma delimited stri...
python
{ "resource": "" }
q42011
run_suite
train
def run_suite(case, config, summary): """ Run the full suite of numerics tests """ m = importlib.import_module(config['module']) m.set_up() config["name"] = case analysis_data = {} bundle = livvkit.numerics_model_module model_dir = os.path.join(livvkit.model_dir, config['data_dir'], case) ...
python
{ "resource": "" }
q42012
ParticleSystem.run_ahead
train
def run_ahead(self, time, framerate): """Run the particle system for the specified time frame at the specified framerate to move time forward as quickly as possible. Useful for "warming up" the particle system to reach a steady-state before anything is drawn or to simply "skip ahead" in ...
python
{ "resource": "" }
q42013
Panel.create_gp
train
def create_gp(self): """ Create GnuPlot file. """ nb_bams = len(self.bams) gp_parts = [ textwrap.dedent( """\ set log x set log x2 #set format x "10^{{%L}}" set format x2 "10^{{%L}}" set x2tics unset xtics """ ), ...
python
{ "resource": "" }
q42014
Panel.create_graphics
train
def create_graphics(self): """Create images related to this panel.""" if len(self._svg_fns) > 0: rnftools.utils.shell('"{}" "{}"'.format("gnuplot", self._gp_fn)) if self.render_pdf_method is not None: for svg_fn in self._svg_fns: pdf_fn = re....
python
{ "resource": "" }
q42015
Panel.create_tar
train
def create_tar(self): """Create a tar file with all the files.""" def add_file_to_tar(tar, orig_fn, new_fn, func=None): tf = tarfile.TarInfo(name=new_fn) with open(orig_fn) as f: tfs = f.read() if func is not None: tfs = func(tfs) ...
python
{ "resource": "" }
q42016
merge_dicts
train
def merge_dicts(dict1, dict2): """ Merge two dictionaries and return the result """ tmp = dict1.copy() tmp.update(dict2) return tmp
python
{ "resource": "" }
q42017
parse_gptl
train
def parse_gptl(file_path, var_list): """ Read a GPTL timing file and extract some data. Args: file_path: the path to the GPTL timing file var_list: a list of strings to look for in the file Returns: A dict containing key-value pairs of the livvkit and the times associat...
python
{ "resource": "" }
q42018
find_file
train
def find_file(search_dir, file_pattern): """ Search for a file in a directory, and return the first match. If the file is not found return an empty string Args: search_dir: The root directory to search in file_pattern: A unix-style wildcard pattern representing the file to f...
python
{ "resource": "" }
q42019
create_page_from_template
train
def create_page_from_template(template_file, output_path): """ Copy the correct html template file to the output directory """ mkdir_p(os.path.dirname(output_path)) shutil.copy(os.path.join(livvkit.resource_dir, template_file), output_path)
python
{ "resource": "" }
q42020
read_json
train
def read_json(file_path): """ Read in a json file and return a dictionary representation """ try: with open(file_path, 'r') as f: config = json_tricks.load(f) except ValueError: print(' '+'!'*58) print(' Woops! Looks the JSON syntax is not valid in:') print(...
python
{ "resource": "" }
q42021
write_json
train
def write_json(data, path, file_name): """ Write out data to a json file. Args: data: A dictionary representation of the data to write out path: The directory to output the file in file_name: The name of the file to write out """ if os.path.exists(path) and not os.path.isdir...
python
{ "resource": "" }
q42022
collect_cases
train
def collect_cases(data_dir): """ Find all cases and subcases of a particular run type """ cases = {} for root, dirs, files in os.walk(data_dir): if not dirs: split_case = os.path.relpath(root, data_dir).split(os.path.sep) if split_case[0] not in cases: cases[s...
python
{ "resource": "" }
q42023
setup_output
train
def setup_output(cssd=None, jsd=None, imgd=None): """ Set up the directory structure for the output. Copies old run data into a timestamped directory and sets up the new directory """ # Check if we need to back up an old run if os.path.isdir(livvkit.index_dir): print("------------------...
python
{ "resource": "" }
q42024
prepare_query_params
train
def prepare_query_params(**kwargs): """ Prepares given parameters to be used in querystring. """ return [ (sub_key, sub_value) for key, value in kwargs.items() for sub_key, sub_value in expand(value, key) if sub_value is not None ]
python
{ "resource": "" }
q42025
TagCache.count
train
def count(cls, slug): """get the number of objects in the cache for a given slug :param slug: cache key :return: `int` """ from .models import Content # Gets the count for a tag, hopefully form an in-memory cache. cnt = cls._cache.get(slug) if cnt is None...
python
{ "resource": "" }
q42026
Text.is_varchar
train
def is_varchar(self): """Determine if a data record is of the type VARCHAR.""" dt = DATA_TYPES['varchar'] if type(self.data) is dt['type'] and len(self.data) < dt['max']: self.type = 'VARCHAR' self.len = len(self.data) return True
python
{ "resource": "" }
q42027
Controls.bind_key_name
train
def bind_key_name(self, function, object_name): """Bind a key to an object name""" for funcname, name in self.name_map.items(): if funcname == function: self.name_map[ funcname] = object_name
python
{ "resource": "" }
q42028
Controls.configure_keys
train
def configure_keys(self): """Configure key map""" self.active_functions = set() self.key2func = {} for funcname, key in self.key_map.items(): self.key2func[key] = getattr(self, funcname)
python
{ "resource": "" }
q42029
_parse_module_list
train
def _parse_module_list(module_list): '''Loop through all the modules and parse them.''' for module_meta in module_list: name = module_meta['module'] # Import & parse module module = import_module(name) output = parse_module(module) # Assign to meta.content modul...
python
{ "resource": "" }
q42030
_build_module_list
train
def _build_module_list(source_module, index_filename, ignore_modules): '''Builds a list of python modules in the current directory.''' out = [] dirs_with_init = set() module_prefix = '' if source_module == '.' else source_module for root, _, filenames in walk('.'): root = root[2:] m...
python
{ "resource": "" }
q42031
_write_docs
train
def _write_docs(module_list, output_dir): '''Write the document meta to our output location.''' for module_meta in module_list: directory = module_meta['directory'] # Ensure target directory if directory and not path.isdir(directory): makedirs(directory) # Write the ...
python
{ "resource": "" }
q42032
main
train
def main(): '''Main in a function in case you place a build.py for pydocs inside the root directory.''' options = ''' pydocs Usage: pydocs SOURCE OUTPUT_DIR pydocs SOURCE OUTPUT_DIR [--json] [--index NAME] [--ignore FILE,NAMES] pydocs --help Options...
python
{ "resource": "" }
q42033
IxnStatisticsView.read_stats
train
def read_stats(self): """ Reads the statistics view from IXN and saves it in statistics dictionary. """ captions, rows = self._get_pages() name_caption_index = captions.index(self.name_caption) captions.pop(name_caption_index) self.captions = captions self.statistics = O...
python
{ "resource": "" }
q42034
check_cmake_exists
train
def check_cmake_exists(cmake_command): """ Check whether CMake is installed. If not, print informative error message and quits. """ from subprocess import Popen, PIPE p = Popen( '{0} --version'.format(cmake_command), shell=True, stdin=PIPE, stdout=PIPE) if no...
python
{ "resource": "" }
q42035
setup_build_path
train
def setup_build_path(build_path): """ Create build directory. If this already exists, print informative error message and quit. """ if os.path.isdir(build_path): fname = os.path.join(build_path, 'CMakeCache.txt') if os.path.exists(fname): sys.stderr.write('aborting setup\...
python
{ "resource": "" }
q42036
run_cmake
train
def run_cmake(command, build_path, default_build_path): """ Execute CMake command. """ from subprocess import Popen, PIPE from shutil import rmtree topdir = os.getcwd() p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout_coded, stderr_coded = p.communicate() ...
python
{ "resource": "" }
q42037
print_build_help
train
def print_build_help(build_path, default_build_path): """ Print help text after configuration step is done. """ print(' configure step is done') print(' now you need to compile the sources:') if (build_path == default_build_path): print(' $ cd build') else: print(' $ ...
python
{ "resource": "" }
q42038
save_setup_command
train
def save_setup_command(argv, build_path): """ Save setup command to a file. """ file_name = os.path.join(build_path, 'setup_command') with open(file_name, 'w') as f: f.write(' '.join(argv[:]) + '\n')
python
{ "resource": "" }
q42039
configure
train
def configure(root_directory, build_path, cmake_command, only_show): """ Main configure function. """ default_build_path = os.path.join(root_directory, 'build') # check that CMake is available, if not stop check_cmake_exists('cmake') # deal with build path if build_path is None: ...
python
{ "resource": "" }
q42040
PollSessionsAPI.create_single_poll_session
train
def create_single_poll_session(self, poll_id, poll_sessions_course_id, poll_sessions_course_section_id=None, poll_sessions_has_public_results=None): """ Create a single poll session. Create a new poll session for this poll """ path = {} data = {} params =...
python
{ "resource": "" }
q42041
MercurialInProcManager._invoke
train
def _invoke(self, *params): """ Run the self.exe command in-process with the supplied params. """ cmd = [self.exe, '-R', self.location] + list(params) with reentry.in_process_context(cmd) as result: sys.modules['mercurial.dispatch'].run() stdout = result.stdio.stdout.getvalue() stderr = result.stdio.st...
python
{ "resource": "" }
q42042
RabaPupa.getDctDescription
train
def getDctDescription(self) : "returns a dict describing the object" return {'type' : RabaFields.RABA_FIELD_TYPE_IS_RABA_OBJECT, 'className' : self._rabaClass.__name__, 'raba_id' : self.raba_id, 'raba_namespace' : self._raba_namespace}
python
{ "resource": "" }
q42043
Raba.dropIndex
train
def dropIndex(cls, fields) : "removes an index created with ensureIndex " con = RabaConnection(cls._raba_namespace) rlf, ff = cls._parseIndex(fields) for name in rlf : con.dropIndex(name, 'anchor_raba_id') con.dropIndex(cls.__name__, ff) con.commit()
python
{ "resource": "" }
q42044
Raba.getIndexes
train
def getIndexes(cls) : "returns a list of the indexes of a class" con = RabaConnection(cls._raba_namespace) idxs = [] for idx in con.getIndexes(rabaOnly = True) : if idx[2] == cls.__name__ : idxs.append(idx) else : for k in cls.columns : if RabaFields.isRabaListField(getattr(cls, k)) and idx[2...
python
{ "resource": "" }
q42045
Raba.flushIndexes
train
def flushIndexes(cls) : "drops all indexes for a class" con = RabaConnection(cls._raba_namespace) for idx in cls.getIndexes() : con.dropIndexByName(idx[1])
python
{ "resource": "" }
q42046
Raba.getFields
train
def getFields(cls) : """returns a set of the available fields. In order to be able ti securely loop of the fields, "raba_id" and "json" are not included in the set""" s = set(cls.columns.keys()) s.remove('json') s.remove('raba_id') return s
python
{ "resource": "" }
q42047
RabaListPupa._attachToObject
train
def _attachToObject(self, anchorObj, relationName) : "dummy fct for compatibility reasons, a RabaListPupa is attached by default" #MutableSequence.__getattribute__(self, "develop")() self.develop() self._attachToObject(anchorObj, relationName)
python
{ "resource": "" }
q42048
RabaList.pupatizeElements
train
def pupatizeElements(self) : """Transform all raba object into pupas""" for i in range(len(self)) : self[i] = self[i].pupa()
python
{ "resource": "" }
q42049
RabaList._attachToObject
train
def _attachToObject(self, anchorObj, relationName) : "Attaches the rabalist to a raba object. Only attached rabalists can be saved" if self.anchorObj == None : self.relationName = relationName self.anchorObj = anchorObj self._setNamespaceConAndConf(anchorObj._rabaClass._raba_namespace) self.tableName =...
python
{ "resource": "" }
q42050
FilesAPI.list_files_courses
train
def list_files_courses(self, course_id, content_types=None, include=None, only=None, order=None, search_term=None, sort=None): """ List files. Returns the paginated list of files for the folder or course. """ path = {} data = {} params = {} # R...
python
{ "resource": "" }
q42051
FilesAPI.get_public_inline_preview_url
train
def get_public_inline_preview_url(self, id, submission_id=None): """ Get public inline preview url. Determine the URL that should be used for inline preview of the file. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID"...
python
{ "resource": "" }
q42052
FilesAPI.get_file_courses
train
def get_file_courses(self, id, course_id, include=None): """ Get file. Returns the standard attachment json object """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id ...
python
{ "resource": "" }
q42053
FilesAPI.update_file
train
def update_file(self, id, hidden=None, lock_at=None, locked=None, name=None, on_duplicate=None, parent_folder_id=None, unlock_at=None): """ Update file. Update some settings on the specified file """ path = {} data = {} params = {} # REQUIRED -...
python
{ "resource": "" }
q42054
FilesAPI.update_folder
train
def update_folder(self, id, hidden=None, lock_at=None, locked=None, name=None, parent_folder_id=None, position=None, unlock_at=None): """ Update folder. Updates a folder """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID"...
python
{ "resource": "" }
q42055
FilesAPI.create_folder_courses
train
def create_folder_courses(self, name, course_id, hidden=None, lock_at=None, locked=None, parent_folder_id=None, parent_folder_path=None, position=None, unlock_at=None): """ Create folder. Creates a folder in the specified context """ path = {} data = {} p...
python
{ "resource": "" }
q42056
FilesAPI.delete_folder
train
def delete_folder(self, id, force=None): """ Delete folder. Remove the specified folder. You can only delete empty folders unless you set the 'force' flag """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" ...
python
{ "resource": "" }
q42057
FilesAPI.set_usage_rights_courses
train
def set_usage_rights_courses(self, file_ids, course_id, usage_rights_use_justification, folder_ids=None, publish=None, usage_rights_legal_copyright=None, usage_rights_license=None): """ Set usage rights. Sets copyright and license information for one or more files """ path...
python
{ "resource": "" }
q42058
import_class
train
def import_class(name): """Load class from fully-qualified python module name. ex: import_class('bulbs.content.models.Content') """ module, _, klass = name.rpartition('.') mod = import_module(module) return getattr(mod, klass)
python
{ "resource": "" }
q42059
RepoManager.get_valid_managers
train
def get_valid_managers(cls, location): """ Get the valid RepoManagers for this location. """ def by_priority_attr(c): return getattr(c, 'priority', 0) classes = sorted( iter_subclasses(cls), key=by_priority_attr, reverse=True) all_managers = (c(location) for c in classes) return (mgr for mgr in a...
python
{ "resource": "" }
q42060
RepoManager.find_all_files
train
def find_all_files(self): """ Find files including those in subrepositories. """ files = self.find_files() subrepo_files = ( posixpath.join(subrepo.location, filename) for subrepo in self.subrepos() for filename in subrepo.find_files() ) return itertools.chain(files, subrepo_files)
python
{ "resource": "" }
q42061
get_cmd_out
train
def get_cmd_out(command): '''Get the output of a command. Gets a nice Unicode no-extra-whitespace string of the ``stdout`` of a given command. Args: command (str or list): A string of the command, or a list of the arguments (as would be used in :class:`subprocess.Popen`). Note: If ``command`` is a ``str``,...
python
{ "resource": "" }
q42062
get_name
train
def get_name(): '''Get desktop environment or OS. Get the OS name or desktop environment. **List of Possible Values** +-------------------------+---------------+ | Windows | windows | +-------------------------+---------------+ | Mac OS X | mac | +-------------------------+---------------+ | G...
python
{ "resource": "" }
q42063
is_in_path
train
def is_in_path(program): ''' Check if a program is in the system ``PATH``. Checks if a given program is in the user's ``PATH`` or not. Args: program (str): The program to try to find in ``PATH``. Returns: bool: Is the program in ``PATH``? ''' if sys.version_info.major == 2: path = os.getenv('PATH') ...
python
{ "resource": "" }
q42064
is_running
train
def is_running(process): ''' Check if process is running. Check if the given process name is running or not. Note: On a Linux system, kernel threads (like ``kthreadd`` etc.) are excluded. Args: process (str): The name of the process. Returns: bool: Is the process running? ''' if os.name == 'nt'...
python
{ "resource": "" }
q42065
parse_datetime
train
def parse_datetime(value): """Returns a datetime object for a given argument This helps to convert strings, dates and datetimes to proper tz-enabled datetime objects.""" if isinstance(value, (string_types, text_type, binary_type)): value = dateutil.parser.parse(value) value.replace(tzi...
python
{ "resource": "" }
q42066
NegateQueryFilter
train
def NegateQueryFilter(es_query): # noqa """ Return a filter removing the contents of the provided query. """ query = es_query.to_dict().get("query", {}) filtered = query.get("filtered", {}) negated_filter = filtered.get("filter", {}) return Not(**negated_filter)
python
{ "resource": "" }
q42067
Request.body_template
train
def body_template(self, value): """ Must be an instance of a prestans.types.DataCollection subclass; this is generally set during the RequestHandler lifecycle. Setting this spwans the parsing process of the body. If the HTTP verb is GET an AssertionError is thrown. Use with extre...
python
{ "resource": "" }
q42068
Request.get_response_attribute_filter
train
def get_response_attribute_filter(self, template_filter, template_model=None): """ Prestans-Response-Attribute-List can contain a client's requested definition for attributes required in the response. This should match the response_attribute_filter_template? :param template_filt...
python
{ "resource": "" }
q42069
Command.version
train
def version(self): """ Return the underlying version """ lines = iter(self._invoke('version').splitlines()) version = next(lines).strip() return self._parse_version(version)
python
{ "resource": "" }
q42070
Mercurial.find_files
train
def find_files(self): """ Find versioned files in self.location """ all_files = self._invoke('locate', '-I', '.').splitlines() # now we have a list of all files in self.location relative to # self.find_root() # Remove the parent dirs from them. from_root = os.path.relpath(self.location, self.find_root(...
python
{ "resource": "" }
q42071
Mercurial._get_rev_num
train
def _get_rev_num(self, rev=None): """ Determine the revision number for a given revision specifier. """ # first, determine the numeric ID cmd = ['identify', '--num'] # workaround for #4 cmd.extend(['--config', 'defaults.identify=']) if rev: cmd.extend(['--rev', rev]) res = self._invoke(*cmd) retu...
python
{ "resource": "" }
q42072
Mercurial._get_tags_by_num
train
def _get_tags_by_num(self): """ Return a dictionary mapping revision number to tags for that number. """ by_revision = operator.attrgetter('revision') tags = sorted(self.get_tags(), key=by_revision) revision_tags = itertools.groupby(tags, key=by_revision) def get_id(rev): return rev.split(':', 1)[0] ...
python
{ "resource": "" }
q42073
Git.get_tags
train
def get_tags(self, rev=None): """ Return the tags for the current revision as a set """ rev = rev or 'HEAD' return set(self._invoke('tag', '--points-at', rev).splitlines())
python
{ "resource": "" }
q42074
Page.validate_template_name
train
def validate_template_name(self, key, value): """Validate template name. :param key: The template path. :param value: The template name. :raises ValueError: If template name is wrong. """ if value not in dict(current_app.config['PAGES_TEMPLATES']): raise Valu...
python
{ "resource": "" }
q42075
add_item
train
def add_item(name, command, system_wide=False): '''Adds a program to startup. Adds a program to user startup. Args: name (str) : The name of the startup entry. command (str) : The command to run. system_wide (bool): Add to system-wide startup. Note: ``system_wide`` requires superuser/admin pr...
python
{ "resource": "" }
q42076
remove_item
train
def remove_item(name, system_wide=False): '''Removes a program from startup. Removes a program from startup. Args: name (str) : The name of the program (as known to the system) to remove. See :func:``list_items``. system_wide (bool): Remove it from system-wide startup. Note: ``system_wide`` require...
python
{ "resource": "" }
q42077
AppEngineAuthContextProvider.get_current_user
train
def get_current_user(self): """ Override get_current_user for Google AppEngine Checks for oauth capable request first, if this fails fall back to standard users API """ from google.appengine.api import users if _IS_DEVELOPMENT_SERVER: return users.get_current...
python
{ "resource": "" }
q42078
Bam.et2roc
train
def et2roc(et_fo, roc_fo): """ET to ROC conversion. Args: et_fo (file): File object for the ET file. roc_fo (file): File object for the ROC file. raises: ValueError """ stats_dicts = [ { "q": q, "M": 0, "w": 0, "...
python
{ "resource": "" }
q42079
Bam.create_roc
train
def create_roc(self): """Create a ROC file for this BAM file. raises: ValueError """ with (gzip.open(self._et_fn, "tr") if self.compress_intermediate_files else open(self._et_fn, "r")) as et_fo: with open(self._roc_fn, "w+") as roc_fo: self.et2roc( e...
python
{ "resource": "" }
q42080
Bam.create_graphics
train
def create_graphics(self): """Create images related to this BAM file using GnuPlot.""" rnftools.utils.shell('"{}" "{}"'.format("gnuplot", self._gp_fn)) if self.render_pdf_method is not None: svg_fn = self._svg_fn pdf_fn = self._pdf_fn svg42pdf(svg_fn, pdf_fn...
python
{ "resource": "" }
q42081
photparse
train
def photparse(tab): """ Parse through a photometry table to group by source_id Parameters ---------- tab: list SQL query dictionary list from running query_dict.execute() Returns ------- newtab: list Dictionary list after parsing to group together sources """ # Ch...
python
{ "resource": "" }
q42082
user_order_by
train
def user_order_by(self, field): """ Queryset method ordering objects by user ordering field. """ # Get ordering model. model_label = order.utils.resolve_labels('.'.join(\ [self.model._meta.app_label, self.model._meta.object_name])) orderitem_set = getattr(self.model, \ or...
python
{ "resource": "" }
q42083
FeatureFlagsAPI.list_enabled_features_accounts
train
def list_enabled_features_accounts(self, account_id): """ List enabled features. List all features that are enabled on a given Account, Course, or User. Only the feature names are returned. """ path = {} data = {} params = {} # REQUIRE...
python
{ "resource": "" }
q42084
AppConfigViewMixin.get_nav_menu
train
def get_nav_menu(self): """Method to generate the menu""" _menu = self.get_site_menu() if _menu: site_menu = list(_menu) else: site_menu = [] had_urls = [] def get_url(menu, had_urls): if 'url' in menu: had_urls.append(...
python
{ "resource": "" }
q42085
OutcomeResultsAPI.get_outcome_results
train
def get_outcome_results(self, course_id, include=None, outcome_ids=None, user_ids=None): """ Get outcome results. Gets the outcome results for users and outcomes in the specified context. """ path = {} data = {} params = {} # REQUIRED - PATH - ...
python
{ "resource": "" }
q42086
OutcomeResultsAPI.get_outcome_result_rollups
train
def get_outcome_result_rollups(self, course_id, aggregate=None, include=None, outcome_ids=None, user_ids=None): """ Get outcome result rollups. Gets the outcome rollups for the users and outcomes in the specified context. """ path = {} data = {} ...
python
{ "resource": "" }
q42087
ipmitool._subprocess_method
train
def _subprocess_method(self, command): """Use the subprocess module to execute ipmitool commands and and set status """ p = subprocess.Popen([self._ipmitool_path] + self.args + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.output, self.error = p.communicate() ...
python
{ "resource": "" }
q42088
ipmitool._expect_method
train
def _expect_method(self, command): """Use the expect module to execute ipmitool commands and set status """ child = pexpect.spawn(self._ipmitool_path, self.args + command) i = child.expect([pexpect.TIMEOUT, 'Password: '], timeout=10) if i == 0: child....
python
{ "resource": "" }
q42089
ipmitool._get_ipmitool_path
train
def _get_ipmitool_path(self, cmd='ipmitool'): """Get full path to the ipmitool command using the unix `which` command """ p = subprocess.Popen(["which", cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return o...
python
{ "resource": "" }
q42090
Remove.truncate
train
def truncate(self, table): """Empty a table by deleting all of its rows.""" if isinstance(table, (list, set, tuple)): for t in table: self._truncate(t) else: self._truncate(table)
python
{ "resource": "" }
q42091
Remove._truncate
train
def _truncate(self, table): """ Remove all records from a table in MySQL It performs the same function as a DELETE statement without a WHERE clause. """ statement = "TRUNCATE TABLE {0}".format(wrap(table)) self.execute(statement) self._printer('\tTruncated table ...
python
{ "resource": "" }
q42092
Remove.truncate_database
train
def truncate_database(self, database=None): """Drop all tables in a database.""" # Change database if needed if database in self.databases and database is not self.database: self.change_db(database) # Get list of tables tables = self.tables if isinstance(self.tables,...
python
{ "resource": "" }
q42093
Remove.drop
train
def drop(self, table): """ Drop a table from a database. Accepts either a string representing a table name or a list of strings representing a table names. """ existing_tables = self.tables if isinstance(table, (list, set, tuple)): for t in table: ...
python
{ "resource": "" }
q42094
Remove._drop
train
def _drop(self, table, existing_tables=None): """Private method for executing table drop commands.""" # Retrieve list of existing tables for comparison existing_tables = existing_tables if existing_tables else self.tables # Only drop table if it exists if table in existing_table...
python
{ "resource": "" }
q42095
Remove.drop_empty_tables
train
def drop_empty_tables(self): """Drop all empty tables in a database.""" # Count number of rows in each table counts = self.count_rows_all() drops = [] # Loop through each table key and validate that rows count is not 0 for table, count in counts.items(): if c...
python
{ "resource": "" }
q42096
Update.update
train
def update(self, table, columns, values, where): """ Update the values of a particular row where a value is met. :param table: table name :param columns: column(s) to update :param values: updated values :param where: tuple, (where_column, where_value) """ ...
python
{ "resource": "" }
q42097
Update.update_many
train
def update_many(self, table, columns, values, where_col, where_index): """ Update the values of several rows. :param table: Name of the MySQL table :param columns: List of columns :param values: 2D list of rows :param where_col: Column name for where clause :para...
python
{ "resource": "" }
q42098
GroupsAPI.list_groups_available_in_context_accounts
train
def list_groups_available_in_context_accounts(self, account_id, include=None, only_own_groups=None): """ List the groups available in a context. Returns the list of active groups in the given context that are visible to user. """ path = {} data = {} param...
python
{ "resource": "" }
q42099
GroupsAPI.invite_others_to_group
train
def invite_others_to_group(self, group_id, invitees): """ Invite others to a group. Sends an invitation to all supplied email addresses which will allow the receivers to join the group. """ path = {} data = {} params = {} # REQUIRED - ...
python
{ "resource": "" }