_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q41800
get_sesames
train
def get_sesames(email, password, device_ids=None, nicknames=None, timeout=5): """Return list of available Sesame objects.""" sesames = [] account = CandyHouseAccount(email, password, timeout=timeout) for sesame in account.sesames: if device_ids is not None and sesame['device_id'] not in device_...
python
{ "resource": "" }
q41801
RotaryEncoder.pulse
train
def pulse(self): """ Calls when_rotated callback if detected changes """ new_b_value = self.gpio_b.is_active new_a_value = self.gpio_a.is_active value = self.table_values.value(new_b_value, new_a_value, self.old_b_value, self.old_a_value) self.old_b_value = new_...
python
{ "resource": "" }
q41802
DataAPI.default_versions
train
def default_versions(self, default_versions): ''' Set archive default read versions Parameters ---------- default_versions: dict Dictionary of archive_name, version pairs. On read/download, archives in this dictionary will download the specified version ...
python
{ "resource": "" }
q41803
DataAPI.create
train
def create( self, archive_name, authority_name=None, versioned=True, raise_on_err=True, metadata=None, tags=None, helper=False): ''' Create a DataFS archive Parameters ---------- arc...
python
{ "resource": "" }
q41804
DataAPI.get_archive
train
def get_archive(self, archive_name, default_version=None): ''' Retrieve a data archive Parameters ---------- archive_name: str Name of the archive to retrieve default_version: version str or :py:class:`~distutils.StrictVersion` giving the defaul...
python
{ "resource": "" }
q41805
DataAPI.search
train
def search(self, *query, **kwargs): ''' Searches based on tags specified by users Parameters --------- query: str tags to search on. If multiple terms, provided in comma delimited string format prefix: str start of archive name. Pro...
python
{ "resource": "" }
q41806
DataAPI._validate_archive_name
train
def _validate_archive_name(self, archive_name): ''' Utility function for creating and validating archive names Parameters ---------- archive_name: str Name of the archive from which to create a service path Returns ------- archive_path: str...
python
{ "resource": "" }
q41807
DataAPI.hash_file
train
def hash_file(f): ''' Utility function for hashing file contents Overload this function to change the file equality checking algorithm Parameters ---------- f: file-like File-like object or file path from which to compute checksum value Returns ...
python
{ "resource": "" }
q41808
html_list
train
def html_list(data): """Convert dict into formatted HTML.""" if data is None: return None as_li = lambda v: "<li>%s</li>" % v items = [as_li(v) for v in data] return mark_safe("<ul>%s</ul>" % ''.join(items))
python
{ "resource": "" }
q41809
check_pypi
train
def check_pypi(modeladmin, request, queryset): """Update latest package info from PyPI.""" for p in queryset: if p.is_editable: logger.debug("Ignoring version update '%s' is editable", p.package_name) else: p.update_from_pypi()
python
{ "resource": "" }
q41810
PackageVersionAdmin._updateable
train
def _updateable(self, obj): """Return True if there are available updates.""" if obj.latest_version is None or obj.is_editable: return None else: return obj.latest_version != obj.current_version
python
{ "resource": "" }
q41811
PackageVersionAdmin.available_updates
train
def available_updates(self, obj): """Print out all versions ahead of the current one.""" from package_monitor import pypi package = pypi.Package(obj.package_name) versions = package.all_versions() return html_list([v for v in versions if v > obj.current_version])
python
{ "resource": "" }
q41812
get_agent
train
def get_agent(msg): """ Handy hack to handle legacy messages where 'agent' was a list. """ agent = msg['msg']['agent'] if isinstance(agent, list): agent = agent[0] return agent
python
{ "resource": "" }
q41813
run_suite
train
def run_suite(case, config, summary): """ Run the full suite of verification tests """ config["name"] = case model_dir = os.path.join(livvkit.model_dir, config['data_dir'], case) bench_dir = os.path.join(livvkit.bench_dir, config['data_dir'], case) tabs = [] case_summary = LIVVDict() model_c...
python
{ "resource": "" }
q41814
_analyze_case
train
def _analyze_case(model_dir, bench_dir, config): """ Runs all of the verification checks on a particular case """ bundle = livvkit.verification_model_module model_out = functions.find_file(model_dir, "*"+config["output_ext"]) bench_out = functions.find_file(bench_dir, "*"+config["output_ext"]) model...
python
{ "resource": "" }
q41815
bit_for_bit
train
def bit_for_bit(model_path, bench_path, config): """ Checks whether the given files have bit for bit solution matches on the given variable list. Args: model_path: absolute path to the model dataset bench_path: absolute path to the benchmark dataset config: the configuration of ...
python
{ "resource": "" }
q41816
plot_bit_for_bit
train
def plot_bit_for_bit(case, var_name, model_data, bench_data, diff_data): """ Create a bit for bit plot """ plot_title = "" plot_name = case + "_" + var_name + ".png" plot_path = os.path.join(os.path.join(livvkit.output_dir, "verification", "imgs")) functions.mkdir_p(plot_path) m_ndim = np.ndim(m...
python
{ "resource": "" }
q41817
Campaign.save
train
def save(self, *args, **kwargs): """Kicks off celery task to re-save associated special coverages to percolator :param args: inline arguments (optional) :param kwargs: keyword arguments :return: `bulbs.campaigns.Campaign` """ campaign = super(Campaign, self).save(*args, ...
python
{ "resource": "" }
q41818
Count.count_rows_duplicates
train
def count_rows_duplicates(self, table, cols='*'): """Get the number of rows that do not contain distinct values.""" return self.count_rows(table, '*') - self.count_rows_distinct(table, cols)
python
{ "resource": "" }
q41819
Count.count_rows
train
def count_rows(self, table, cols='*'): """Get the number of rows in a particular table.""" query = 'SELECT COUNT({0}) FROM {1}'.format(join_cols(cols), wrap(table)) result = self.fetch(query) return result if result is not None else 0
python
{ "resource": "" }
q41820
Count.count_rows_distinct
train
def count_rows_distinct(self, table, cols='*'): """Get the number distinct of rows in a particular table.""" return self.fetch('SELECT COUNT(DISTINCT {0}) FROM {1}'.format(join_cols(cols), wrap(table)))
python
{ "resource": "" }
q41821
Structure.get_unique_column
train
def get_unique_column(self, table): """Determine if any of the columns in a table contain exclusively unique values.""" for col in self.get_columns(table): if self.count_rows_duplicates(table, col) == 0: return col
python
{ "resource": "" }
q41822
Structure.get_duplicate_vals
train
def get_duplicate_vals(self, table, column): """Retrieve duplicate values in a column of a table.""" query = 'SELECT {0} FROM {1} GROUP BY {0} HAVING COUNT(*) > 1'.format(join_cols(column), wrap(table)) return self.fetch(query)
python
{ "resource": "" }
q41823
BaseSimpleMetadata.get_field_info
train
def get_field_info(self, field): """ This method is basically a mirror from rest_framework==3.3.3 We are currently pinned to rest_framework==3.1.1. If we upgrade, this can be refactored and simplified to rely more heavily on rest_framework's built in logic. """ ...
python
{ "resource": "" }
q41824
StringBuffer._double_prefix
train
def _double_prefix(self): """Grow the given deque by doubling, but don't split the second chunk just because the first one is small. """ new_len = max(len(self._buf[0]) * 2, (len(self._buf[0]) + len(self._buf[1]))) self._merge_prefix(new_len)
python
{ "resource": "" }
q41825
StringBuffer._merge_prefix
train
def _merge_prefix(self, size): """Replace the first entries in a deque of strings with a single string of up to size bytes. >>> d = collections.deque(['abc', 'de', 'fghi', 'j']) >>> _merge_prefix(d, 5); print(d) deque(['abcde', 'fghi', 'j']) Strings will be split as nec...
python
{ "resource": "" }
q41826
get_sponsored_special_coverage_query
train
def get_sponsored_special_coverage_query(only_recent=False): """ Reference to all SpecialCovearge queries. :param only_recent: references RECENT_SPONSORED_OFFSET_HOURS from django settings. Used to return sponsored content within a given configuration of hours. :returns: Djes.LazySearch query m...
python
{ "resource": "" }
q41827
DebuggedApplication.debug_application
train
def debug_application(self, environ, start_response): """Run the application and conserve the traceback frames.""" app_iter = None try: app_iter = self.app(environ, start_response) for item in app_iter: yield item if hasattr(app_iter, 'close'):...
python
{ "resource": "" }
q41828
DebuggedApplication.paste_traceback
train
def paste_traceback(self, request, traceback): """Paste the traceback and return a JSON response.""" rv = traceback.paste() return Response(json.dumps(rv), content_type='application/json')
python
{ "resource": "" }
q41829
ESPublishedFilterBackend.filter_queryset
train
def filter_queryset(self, request, queryset, view): """Apply the relevant behaviors to the view queryset.""" start_value = self.get_start(request) if start_value: queryset = self.apply_published_filter(queryset, "after", start_value) end_value = self.get_end(request) ...
python
{ "resource": "" }
q41830
ESPublishedFilterBackend.apply_published_filter
train
def apply_published_filter(self, queryset, operation, value): """ Add the appropriate Published filter to a given elasticsearch query. :param queryset: The DJES queryset object to be filtered. :param operation: The type of filter (before/after). :param value: The date or datetim...
python
{ "resource": "" }
q41831
ESPublishedFilterBackend.get_date_datetime_param
train
def get_date_datetime_param(self, request, param): """Check the request for the provided query parameter and returns a rounded value. :param request: WSGI request object to retrieve query parameter data. :param param: the name of the query parameter. """ if param in request.GET:...
python
{ "resource": "" }
q41832
Session.create
train
def create(self, message, mid=None, age=60, force=True): """ create session force if you pass `force = False`, it may raise SessionError due to duplicate message id """ with self.session_lock: if not hasattr(message, "id"): message....
python
{ "resource": "" }
q41833
parse_args
train
def parse_args(args=None): """ Handles the parsing of options for LIVVkit's command line interface Args: args: The list of arguments, typically sys.argv[1:] """ parser = argparse.ArgumentParser(description="Main script to run LIVVkit.", formatter_class=a...
python
{ "resource": "" }
q41834
GroupCategoriesAPI.get_single_group_category
train
def get_single_group_category(self, group_category_id): """ Get a single group category. Returns the data for a single group category, or a 401 if the caller doesn't have the rights to see it. """ path = {} data = {} params = {} # REQU...
python
{ "resource": "" }
q41835
GroupCategoriesAPI.create_group_category_accounts
train
def create_group_category_accounts(self, name, account_id, auto_leader=None, create_group_count=None, group_limit=None, self_signup=None, split_group_count=None): """ Create a Group Category. Create a new group category """ path = {} data = {} params = {}...
python
{ "resource": "" }
q41836
GroupCategoriesAPI.list_groups_in_group_category
train
def list_groups_in_group_category(self, group_category_id): """ List groups in group category. Returns a list of groups in a group category """ path = {} data = {} params = {} # REQUIRED - PATH - group_category_id """ID""" pat...
python
{ "resource": "" }
q41837
GroupCategoriesAPI.list_users_in_group_category
train
def list_users_in_group_category(self, group_category_id, search_term=None, unassigned=None): """ List users in group category. Returns a list of users in the group category. """ path = {} data = {} params = {} # REQUIRED - PATH - group_categor...
python
{ "resource": "" }
q41838
GroupCategoriesAPI.assign_unassigned_members
train
def assign_unassigned_members(self, group_category_id, sync=None): """ Assign unassigned members. Assign all unassigned members as evenly as possible among the existing student groups. """ path = {} data = {} params = {} # REQUIRED - P...
python
{ "resource": "" }
q41839
Payment.set_shipping
train
def set_shipping(self, *args, **kwargs): ''' Define os atributos do frete Args: type (int): (opcional) Tipo de frete. Os valores válidos são: 1 para 'Encomenda normal (PAC).', 2 para 'SEDEX' e 3 para 'Tipo de frete não especificado.' cost (float): (opcional) Valo...
python
{ "resource": "" }
q41840
opensearch
train
def opensearch(request): """ Return opensearch.xml. """ contact_email = settings.CONTACT_EMAIL short_name = settings.SHORT_NAME description = settings.DESCRIPTION favicon_width = settings.FAVICON_WIDTH favicon_height = settings.FAVICON_HEIGHT favicon_type = settings.FAVICON_TYPE ...
python
{ "resource": "" }
q41841
ModelInitiator.db_manager
train
def db_manager(self): """ " Do series of DB operations. """ rc_create = self.create_db() # for first create try: self.load_db() # load existing/factory except Exception as e: _logger.debug("*** %s" % str(e)) try: sel...
python
{ "resource": "" }
q41842
ModelInitiator.create_db
train
def create_db(self): """ " Create a db file for model if there is no db. " User need to prepare thier own xxx.json.factory. """ if self.db_type != "json": raise RuntimeError("db_type only supports json now") if os.path.exists(self.json_db_path): ...
python
{ "resource": "" }
q41843
ModelInitiator.backup_db
train
def backup_db(self): """ " Generate a xxxxx.backup.json. """ with self.db_mutex: if os.path.exists(self.json_db_path): try: shutil.copy2(self.json_db_path, self.backup_json_db_path) except (IOError, OSError): ...
python
{ "resource": "" }
q41844
ModelInitiator.load_db
train
def load_db(self): """ " Load json db as a dictionary. """ try: with open(self.json_db_path) as fp: self.db = json.load(fp) except Exception as e: _logger.debug("*** Open JSON DB error.") raise e
python
{ "resource": "" }
q41845
ModelInitiator.save_db
train
def save_db(self): """ " Save json db to file system. """ with self.db_mutex: if not isinstance(self.db, dict) and not isinstance(self.db, list): return False try: with open(self.json_db_path, "w") as fp: json.du...
python
{ "resource": "" }
q41846
IxnPort.wait_for_states
train
def wait_for_states(self, timeout=40, *states): """ Wait until port reaches one of the requested states. :param timeout: max time to wait for requested port states. """ state = self.get_attribute('state') for _ in range(timeout): if state in states: ...
python
{ "resource": "" }
q41847
FormWizardAdminView.get_form
train
def get_form(self, step=None, data=None, files=None): """Instanciate the form for the current step FormAdminView from xadmin expects form to be at self.form_obj """ self.form_obj = super(FormWizardAdminView, self).get_form( step=step, data=data, files=files) return ...
python
{ "resource": "" }
q41848
FormWizardAdminView.render
train
def render(self, form=None, **kwargs): """Returns the ``HttpResponse`` with the context data""" context = self.get_context(**kwargs) return self.render_to_response(context)
python
{ "resource": "" }
q41849
FormWizardAdminView.render_to_response
train
def render_to_response(self, context): """Add django-crispy form helper and draw the template Returns the ``TemplateResponse`` ready to be displayed """ self.setup_forms() return TemplateResponse( self.request, self.form_template, context, current_app=se...
python
{ "resource": "" }
q41850
FormWizardAdminView.get_context
train
def get_context(self, **kwargs): """Use this method to built context data for the template Mix django wizard context data with django-xadmin context """ context = self.get_context_data(form=self.form_obj, **kwargs) context.update(super(FormAdminView, self).get_context()) ...
python
{ "resource": "" }
q41851
FqMerger.run
train
def run(self): """Run merging. """ print("", file=sys.stderr) print("Going to merge/convert RNF-FASTQ files.", file=sys.stderr) print("", file=sys.stderr) print(" mode: ", self.mode, file=sys.stderr) print(" input files: ", ", ".join(self.input_files_fn)...
python
{ "resource": "" }
q41852
is_config_container
train
def is_config_container(v): """ checks whether v is of type list,dict or Config """ cls = type(v) return ( issubclass(cls, list) or issubclass(cls, dict) or issubclass(cls, Config) )
python
{ "resource": "" }
q41853
Handler.validate
train
def validate(cls, cfg, path="", nested=0, parent_cfg=None): """ Validates a section of a config dict. Will automatically validate child sections as well if their attribute pointers are instantiated with a handler property """ # number of critical errors found num...
python
{ "resource": "" }
q41854
Handler.attributes
train
def attributes(cls): """ yields tuples for all attributes defined on this handler tuple yielded: name (str), attribute (Attribute) """ for k in dir(cls): v = getattr(cls, k) if isinstance(v, Attribute): yield k,v
python
{ "resource": "" }
q41855
Config.read
train
def read(self, config_dir=None, clear=False, config_file=None): """ The munge Config's read function only allows to read from a config directory, but we also want to be able to read straight from a config file as well """ if config_file: data_file = os.path.b...
python
{ "resource": "" }
q41856
FavoritesAPI.remove_group_from_favorites
train
def remove_group_from_favorites(self, id): """ Remove group from favorites. Remove a group from the current user's favorites. """ path = {} data = {} params = {} # REQUIRED - PATH - id """the ID or SIS ID of the group to remove""" ...
python
{ "resource": "" }
q41857
FavoritesAPI.reset_course_favorites
train
def reset_course_favorites(self): """ Reset course favorites. Reset the current user's course favorites to the default automatically generated list of enrolled courses """ path = {} data = {} params = {} self.logger.debug("DELETE /api/...
python
{ "resource": "" }
q41858
SearchAPI.list_all_courses
train
def list_all_courses(self, open_enrollment_only=None, public_only=None, search=None): """ List all courses. List all courses visible in the public index """ path = {} data = {} params = {} # OPTIONAL - search """Search terms used for m...
python
{ "resource": "" }
q41859
CommunicationChannelsAPI.create_communication_channel
train
def create_communication_channel(self, user_id, communication_channel_type, communication_channel_address, communication_channel_token=None, skip_confirmation=None): """ Create a communication channel. Creates a new communication channel for the specified user. """ path = ...
python
{ "resource": "" }
q41860
CommunicationChannelsAPI.delete_communication_channel_id
train
def delete_communication_channel_id(self, id, user_id): """ Delete a communication channel. Delete an existing communication channel. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = u...
python
{ "resource": "" }
q41861
Literal.from_str
train
def from_str(cls, string): """ Creates a literal from a string Parameters ---------- string : str If the string starts with '!', it's interpreted as a negated variable Returns ------- caspo.core.literal.Literal Created object inst...
python
{ "resource": "" }
q41862
normalize_signature
train
def normalize_signature(func): """Decorator. Combine args and kwargs. Unpack single item tuples.""" @wraps(func) def wrapper(*args, **kwargs): if kwargs: args = args, kwargs if len(args) is 1: args = args[0] return func(args) return wrapper
python
{ "resource": "" }
q41863
filter_commands
train
def filter_commands(commands, invalid_query_starts=('DROP', 'UNLOCK', 'LOCK')): """ Remove particular queries from a list of SQL commands. :param commands: List of SQL commands :param invalid_query_starts: Type of SQL command to remove :return: Filtered list of SQL commands """ commands_wit...
python
{ "resource": "" }
q41864
prepare_sql
train
def prepare_sql(sql, add_semicolon=True, invalid_starts=('--', '/*', '*/', ';')): """Wrapper method for PrepareSQL class.""" return PrepareSQL(sql, add_semicolon, invalid_starts).prepared
python
{ "resource": "" }
q41865
PrepareSQL._get_next_occurrence
train
def _get_next_occurrence(haystack, offset, needles): """ Find next occurence of one of the needles in the haystack :return: tuple of (index, needle found) or: None if no needle was found""" # make map of first char to full needle (only works if all needles # have di...
python
{ "resource": "" }
q41866
render_template_directory
train
def render_template_directory(deck, arguments): """Render a template directory""" output_directory = dir_name_from_title(deck.title) if os.path.exists(output_directory): if sys.stdout.isatty(): if ask( '%s already exists, shall I delete it?' % output_directory, ...
python
{ "resource": "" }
q41867
main
train
def main(): ''' set things up ''' configs = setup(argparse.ArgumentParser()) harvester = GreyHarvester( test_domain=configs['test_domain'], test_sleeptime=TEST_SLEEPTIME, https_only=configs['https_only'], allowed_countries=configs['allowed_countries'], denied_countr...
python
{ "resource": "" }
q41868
GreyHarvester._extract_proxies
train
def _extract_proxies(self, ajax_endpoint): ''' request the xml object ''' proxy_xml = requests.get(ajax_endpoint) print(proxy_xml.content) root = etree.XML(proxy_xml.content) quote = root.xpath('quote')[0] ''' extract the raw text from the body of the quote ...
python
{ "resource": "" }
q41869
GreyHarvester._passes_filter
train
def _passes_filter(self, proxy): ''' avoid redudant and space consuming calls to 'self' ''' ''' validate proxy based on provided filters ''' if self.allowed_countries is not None and proxy['country'] not in self.allowed_countries: return False if self.denied_countr...
python
{ "resource": "" }
q41870
MappingList.iteritems
train
def iteritems(self): """ Iterates over all mappings Yields ------ (int,Mapping) The next pair (index, mapping) """ for m in self.mappings: yield self.indexes[m.clause][m.target], m
python
{ "resource": "" }
q41871
Mapping.from_str
train
def from_str(cls, string): """ Creates a mapping from a string Parameters ---------- string : str String of the form `target<-clause` where `clause` is a valid string for :class:`caspo.core.clause.Clause` Returns ------- caspo.core.mapping.Ma...
python
{ "resource": "" }
q41872
LoginsAPI.list_user_logins_users
train
def list_user_logins_users(self, user_id): """ List user logins. Given a user ID, return that user's logins for the given account. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user...
python
{ "resource": "" }
q41873
LoginsAPI.create_user_login
train
def create_user_login(self, user_id, account_id, login_unique_id, login_authentication_provider_id=None, login_integration_id=None, login_password=None, login_sis_user_id=None): """ Create a user login. Create a new login for an existing user in the given account. """ path...
python
{ "resource": "" }
q41874
LoginsAPI.edit_user_login
train
def edit_user_login(self, id, account_id, login_integration_id=None, login_password=None, login_sis_user_id=None, login_unique_id=None): """ Edit a user login. Update an existing login for a user in the given account. """ path = {} data = {} params = {} ...
python
{ "resource": "" }
q41875
LoginsAPI.delete_user_login
train
def delete_user_login(self, id, user_id): """ Delete a user login. Delete an existing login. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - id ...
python
{ "resource": "" }
q41876
QuizQuestionsAPI.list_questions_in_quiz_or_submission
train
def list_questions_in_quiz_or_submission(self, quiz_id, course_id, quiz_submission_attempt=None, quiz_submission_id=None): """ List questions in a quiz or a submission. Returns the list of QuizQuestions in this quiz. """ path = {} data = {} params = {} ...
python
{ "resource": "" }
q41877
QuizQuestionsAPI.create_single_quiz_question
train
def create_single_quiz_question(self, quiz_id, course_id, question_answers=None, question_correct_comments=None, question_incorrect_comments=None, question_neutral_comments=None, question_points_possible=None, question_position=None, question_question_name=None, question_question_text=None, question_question_type=None,...
python
{ "resource": "" }
q41878
Http.request
train
def request(self, action, data={}, headers={}, method='GET'): """ Append the user authentication details to every incoming request """ data = self.merge(data, {'user': self.username, 'password': self.password, 'api_id': self.apiId}) return Transport.request(self, action, data, he...
python
{ "resource": "" }
q41879
SpecialCoverage.clean_publish_dates
train
def clean_publish_dates(self): """ If an end_date value is provided, the start_date must be less. """ if self.end_date: if not self.start_date: raise ValidationError("""The End Date requires a Start Date value.""") elif self.end_date <= self.start_...
python
{ "resource": "" }
q41880
SpecialCoverage.clean_videos
train
def clean_videos(self): """ Validates that all values in the video list are integer ids and removes all None values. """ if self.videos: self.videos = [int(v) for v in self.videos if v is not None and is_valid_digit(v)]
python
{ "resource": "" }
q41881
SpecialCoverage.clean_super_features
train
def clean_super_features(self): """ Removes any null & non-integer values from the super feature list """ if self.super_features: self.super_features = [int(sf) for sf in self.super_features if sf is not None and is_valid_digit(sf)]
python
{ "resource": "" }
q41882
SpecialCoverage._save_percolator
train
def _save_percolator(self): """ Saves the query field as an elasticsearch percolator """ index = Content.search_objects.mapping.index query_filter = self.get_content(published=False).to_dict() q = {} if "query" in query_filter: q = {"query": query_fi...
python
{ "resource": "" }
q41883
SpecialCoverage.custom_template_name
train
def custom_template_name(self): """ Returns the path for the custom special coverage template we want. """ base_path = getattr(settings, "CUSTOM_SPECIAL_COVERAGE_PATH", "special_coverage/custom") if base_path is None: base_path = "" return "{0}/{1}_custom.html...
python
{ "resource": "" }
q41884
ExclusiveBooleanField.deconstruct
train
def deconstruct(self): """ to support Django 1.7 migrations, see also the add_introspection_rules section at bottom of this file for South + earlier Django versions """ name, path, args, kwargs = super( ExclusiveBooleanField, self).deconstruct() if self._on_fi...
python
{ "resource": "" }
q41885
Command.sync_apps
train
def sync_apps(self, connection, app_labels): "Runs the old syncdb-style operation on a list of app_labels." cursor = connection.cursor() try: # Get a list of already installed *models* so that references work right. tables = connection.introspection.table_names(cursor) ...
python
{ "resource": "" }
q41886
CloneData.get_database_rows
train
def get_database_rows(self, tables=None, database=None): """Retrieve a dictionary of table keys and list of rows values for every table.""" # Get table data and columns from source database source = database if database else self.database tables = tables if tables else self.tables ...
python
{ "resource": "" }
q41887
CloneData._get_select_commands
train
def _get_select_commands(self, source, tables): """ Create select queries for all of the tables from a source database. :param source: Source database name :param tables: Iterable of table names :return: Dictionary of table keys, command values """ # Create dicti...
python
{ "resource": "" }
q41888
CloneData._execute_select_commands
train
def _execute_select_commands(self, source, commands): """Execute select queries for all of the tables from a source database.""" rows = {} for tbl, command in tqdm(commands, total=len(commands), desc='Executing {0} select queries'.format(source)): # Add key to dictionary ...
python
{ "resource": "" }
q41889
CloneData.get_database_columns
train
def get_database_columns(self, tables=None, database=None): """Retrieve a dictionary of columns.""" # Get table data and columns from source database source = database if database else self.database tables = tables if tables else self.tables return {tbl: self.get_columns(tbl) for...
python
{ "resource": "" }
q41890
CloneData._get_insert_commands
train
def _get_insert_commands(self, rows, cols): """Retrieve dictionary of insert statements to be executed.""" # Get insert queries insert_queries = {} for table in tqdm(list(rows.keys()), total=len(list(rows.keys())), desc='Getting insert rows queries'): insert_queries[table] = ...
python
{ "resource": "" }
q41891
CloneDatabase.copy_database_structure
train
def copy_database_structure(self, source, destination, tables=None): """Copy multiple tables from one database to another.""" # Change database to source self.change_db(source) if tables is None: tables = self.tables # Change database to destination self.cha...
python
{ "resource": "" }
q41892
CloneDatabase.copy_table_structure
train
def copy_table_structure(self, source, destination, table): """ Copy a table from one database to another. :param source: Source database :param destination: Destination database :param table: Table name """ self.execute('CREATE TABLE {0}.{1} LIKE {2}.{1}'.format...
python
{ "resource": "" }
q41893
CloneDatabase.copy_database_data
train
def copy_database_data(self, source, destination, optimized=False): """ Copy the data from one database to another. Retrieve existing data from the source database and insert that data into the destination database. """ # Change database to source self.enable_printing = ...
python
{ "resource": "" }
q41894
CloneDatabase._copy_database_data_serverside
train
def _copy_database_data_serverside(self, source, destination, tables): """Select rows from a source database and insert them into a destination db in one query""" for table in tqdm(tables, total=len(tables), desc='Copying table data (optimized)'): self.execute('INSERT INTO {0}.{1} SELECT * F...
python
{ "resource": "" }
q41895
CloneDatabase._copy_database_data_clientside
train
def _copy_database_data_clientside(self, tables, source, destination): """Copy the data from a table into another table.""" # Retrieve database rows rows = self.get_database_rows(tables, source) # Retrieve database columns cols = self.get_database_columns(tables, source) ...
python
{ "resource": "" }
q41896
Clone.copy_database
train
def copy_database(self, source, destination): """ Copy a database's content and structure. SMALL Database speed improvements (DB size < 5mb) Using optimized is about 178% faster Using one_query is about 200% faster LARGE Database speed improvements (DB size > 5mb) ...
python
{ "resource": "" }
q41897
CuReSim.recode_curesim_reads
train
def recode_curesim_reads( curesim_fastq_fo, rnf_fastq_fo, fai_fo, genome_id, number_of_read_tuples=10**9, recode_random=False, ): """Recode CuReSim output FASTQ file to the RNF-compatible output FASTQ file. Args: curesim_fastq_fo (file object): File obje...
python
{ "resource": "" }
q41898
get_config_dir
train
def get_config_dir(program='', system_wide=False): '''Get the configuration directory. Get the configuration directories, optionally for a specific program. Args: program (str) : The name of the program whose configuration directories have to be found. system_wide (bool): Gets the system-wide configuration d...
python
{ "resource": "" }
q41899
get_config_file
train
def get_config_file(program, system_wide=False): '''Get the configuration file for a program. Gets the configuration file for a given program, assuming it stores it in a standard location. See also :func:`get_config_dir()`. Args: program (str): The program for which to get the configuration file. system_wi...
python
{ "resource": "" }