code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
def delete_group_category(self, group_category_id): path = {} data = {} params = {} # REQUIRED - PATH - group_category_id path["group_category_id"] = group_category_id self.logger.debug("DELETE /api/v1/group_categories/{group_category_id} wit...
Delete a Group Category. Deletes a group category and all groups under it. Protected group categories can not be deleted, i.e. "communities" and "student_organized".
null
null
null
def list_groups_in_group_category(self, group_category_id): path = {} data = {} params = {} # REQUIRED - PATH - group_category_id path["group_category_id"] = group_category_id self.logger.debug("GET /api/v1/group_categories/{group_category_id...
List groups in group category. Returns a list of groups in a group category
null
null
null
def list_users_in_group_category(self, group_category_id, search_term=None, unassigned=None): path = {} data = {} params = {} # REQUIRED - PATH - group_category_id path["group_category_id"] = group_category_id # OPTIONAL - search_term ...
List users in group category. Returns a list of users in the group category.
null
null
null
def assign_unassigned_members(self, group_category_id, sync=None): path = {} data = {} params = {} # REQUIRED - PATH - group_category_id path["group_category_id"] = group_category_id # OPTIONAL - sync if sync is not None: ...
Assign unassigned members. Assign all unassigned members as evenly as possible among the existing student groups.
null
null
null
''' Se você possui informações cadastradas sobre o comprador você pode utilizar este método para enviar estas informações para o PagSeguro. É uma boa prática pois evita que seu cliente tenha que preencher estas informações novamente na página do PagSeguro. Args: name...
def set_client(self, *args, **kwargs)
Se você possui informações cadastradas sobre o comprador você pode utilizar este método para enviar estas informações para o PagSeguro. É uma boa prática pois evita que seu cliente tenha que preencher estas informações novamente na página do PagSeguro. Args: name (str): (opc...
4.542763
1.366695
3.323903
''' 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) Valor total do frete. Deve ser maior que 0.00...
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) Valor total do frete. Deve ser maior que 0.00 e menor ou ...
3.101824
1.316443
2.356215
''' Faz a requisição de pagamento ao servidor do PagSeguro. ''' # try: payment_v2_schema(self) # except MultipleInvalid as e: # raise PagSeguroPaymentValidationException(u'Erro na validação dos dados: %s' % e.msg) params = self._build_params() # l...
def request(self)
Faz a requisição de pagamento ao servidor do PagSeguro.
3.662237
3.117458
1.174751
''' método que constrói o dicionario com os parametros que serão usados na requisição HTTP Post ao PagSeguro Returns: Um dicionário com os parametros definidos no objeto Payment. ''' params = {} params['email'] = self.email params['token'] = s...
def _build_params(self)
método que constrói o dicionario com os parametros que serão usados na requisição HTTP Post ao PagSeguro Returns: Um dicionário com os parametros definidos no objeto Payment.
1.751196
1.556505
1.125082
''' Processa o xml de resposta e caso não existam erros retorna um dicionario com o codigo e data. :return: dictionary ''' result = {} xml = ElementTree.fromstring(response_xml) if xml.tag == 'errors': logger.error( u'Erro no p...
def _process_response_xml(self, response_xml)
Processa o xml de resposta e caso não existam erros retorna um dicionario com o codigo e data. :return: dictionary
3.17866
2.650498
1.199269
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 favicon_file = settings.FAVICON_FILE url = "{url}?{queryst...
def opensearch(request)
Return opensearch.xml.
3.027425
2.984251
1.014467
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: self.recover_db(self.backup_json_db_path) except Exception: ...
def db_manager(self)
" Do series of DB operations.
3.727091
3.593672
1.037126
if self.db_type != "json": raise RuntimeError("db_type only supports json now") if os.path.exists(self.json_db_path): return False if os.path.exists(self.factory_json_db_path): with self.db_mutex: shutil.copy2( se...
def create_db(self)
" Create a db file for model if there is no db. " User need to prepare thier own xxx.json.factory.
4.113647
3.500779
1.175066
with self.db_mutex: try: shutil.copy2(src_file, self.json_db_path) except IOError as e: _logger.debug("*** NO: %s file." % src_file) raise e
def recover_db(self, src_file)
" Recover DB from xxxxx.backup.json or xxxxx.json.factory to xxxxx.json " [src_file]: copy from src_file to xxxxx.json
6.438183
5.775657
1.11471
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): _logger.debug("*** No file to copy.")
def backup_db(self)
" Generate a xxxxx.backup.json.
3.793814
3.466143
1.094535
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
def load_db(self)
" Load json db as a dictionary.
5.237857
3.998886
1.309829
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.dump(self.db, fp, indent=4) except Exception as e: ...
def save_db(self)
" Save json db to file system.
4.556094
3.924684
1.160882
if not location or is_local_host(location): return hostname, card, port = location.split('/') chassis = self.root.hw.get_chassis(hostname) # todo - test if port owned by me. if force: chassis.get_card(int(card)).get_port(int(port)).release() ...
def reserve(self, location=None, force=False, wait_for_up=True, timeout=80)
Reserve port and optionally wait for port to come up. :param location: port location as 'ip/module/port'. If None, the location will be taken from the configuration. :param force: whether to revoke existing reservation (True) or not (False). :param wait_for_up: True - wait for port to come up, ...
6.040218
5.699929
1.059701
self.wait_for_states(timeout, 'up') connectionStatus = self.get_attribute('connectionStatus').strip() if connectionStatus.split(':')[0] != self.get_attribute('assignedTo').split(':')[0]: raise TgnError('Failed to reach up state, port connection status is {} after {} seconds...
def wait_for_up(self, timeout=40)
Wait until port is up and running, including all parameters (admin state, oper state, license etc.). :param timeout: max time to wait for port up.
7.655907
7.7167
0.992122
state = self.get_attribute('state') for _ in range(timeout): if state in states: return time.sleep(1) state = self.get_attribute('state') raise TgnError('Failed to reach states {}, port state is {} after {} seconds'.format(states, sta...
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.
3.825207
3.491266
1.09565
self.form_obj = super(FormWizardAdminView, self).get_form( step=step, data=data, files=files) return self.form_obj
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
3.35648
2.710643
1.23826
context = self.get_context(**kwargs) return self.render_to_response(context)
def render(self, form=None, **kwargs)
Returns the ``HttpResponse`` with the context data
3.566264
3.465322
1.029129
self.setup_forms() return TemplateResponse( self.request, self.form_template, context, current_app=self.admin_site.name)
def render_to_response(self, context)
Add django-crispy form helper and draw the template Returns the ``TemplateResponse`` ready to be displayed
4.867855
4.587116
1.061202
context = self.get_context_data(form=self.form_obj, **kwargs) context.update(super(FormAdminView, self).get_context()) return context
def get_context(self, **kwargs)
Use this method to built context data for the template Mix django wizard context data with django-xadmin context
4.686991
4.014109
1.167629
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), file=sys.stderr) print(" ...
def run(self)
Run merging.
2.505447
2.41653
1.036795
cls = type(v) return ( issubclass(cls, list) or issubclass(cls, dict) or issubclass(cls, Config) )
def is_config_container(v)
checks whether v is of type list,dict or Config
3.705632
2.635155
1.406229
attr = getattr(cls, key_name, None) if path != "": attr_full_name = "%s.%s" % (path, key_name) else: attr_full_name = key_name if not attr: # attribute specified by key_name is unknown, warn raise vodka.exceptions.ConfigErrorUnk...
def check(cls, cfg, key_name, path, parent_cfg=None)
Checks that the config values specified in key name is sane according to config attributes defined as properties on this class
2.719783
2.69378
1.009653
# number of critical errors found num_crit = 0 # number of non-critical errors found num_warn = 0 # check for missing keys in the config for name in dir(cls): if nested > 0: break try: attr = getattr(cls...
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
2.431772
2.483422
0.979202
for k in dir(cls): v = getattr(cls, k) if isinstance(v, Attribute): yield k,v
def attributes(cls)
yields tuples for all attributes defined on this handler tuple yielded: name (str), attribute (Attribute)
4.143559
2.952837
1.403247
if config_file: data_file = os.path.basename(config_file) data_path = os.path.dirname(config_file) if clear: self.clear() config = munge.load_datafile(data_file, data_path, default=None) if not config: raise...
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
3.138545
2.919437
1.075051
def remove_group_from_favorites(self, id): path = {} data = {} params = {} # REQUIRED - PATH - id path["id"] = id self.logger.debug("DELETE /api/v1/users/self/favorites/groups/{id} with query params: {params} and form data: {data}".format(par...
Remove group from favorites. Remove a group from the current user's favorites.
null
null
null
def reset_course_favorites(self): path = {} data = {} params = {} self.logger.debug("DELETE /api/v1/users/self/favorites/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("DELETE", "/a...
Reset course favorites. Reset the current user's course favorites to the default automatically generated list of enrolled courses
null
null
null
def find_recipients_conversations(self, context=None, exclude=None, from_conversation_id=None, permissions=None, search=None, type=None, user_id=None): path = {} data = {} params = {} # OPTIONAL - search if search is not None: params["searc...
Find recipients. Find valid recipients (users, courses and groups) that the current user can send messages to. The /api/v1/search/recipients path is the preferred endpoint, /api/v1/conversations/find_recipients is deprecated. Pagination is supported.
null
null
null
def list_all_courses(self, open_enrollment_only=None, public_only=None, search=None): path = {} data = {} params = {} # OPTIONAL - search if search is not None: params["search"] = search # OPTIONAL - public_only ...
List all courses. List all courses visible in the public index
null
null
null
def create_communication_channel(self, user_id, communication_channel_type, communication_channel_address, communication_channel_token=None, skip_confirmation=None): path = {} data = {} params = {} # REQUIRED - PATH - user_id path["user_id"] = user_id ...
Create a communication channel. Creates a new communication channel for the specified user.
null
null
null
def delete_communication_channel_id(self, id, user_id): path = {} data = {} params = {} # REQUIRED - PATH - user_id path["user_id"] = user_id # REQUIRED - PATH - id path["id"] = id self.logger.debug("DELETE /api/...
Delete a communication channel. Delete an existing communication channel.
null
null
null
if string[0] == '!': signature = -1 variable = string[1:] else: signature = 1 variable = string return cls(variable, signature)
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 instance
4.399692
4.247915
1.03573
@wraps(func) def wrapper(*args, **kwargs): if kwargs: args = args, kwargs if len(args) is 1: args = args[0] return func(args) return wrapper
def normalize_signature(func)
Decorator. Combine args and kwargs. Unpack single item tuples.
3.22622
2.706911
1.191846
commands_with_drops = len(commands) filtered_commands = [c for c in commands if not c.startswith(invalid_query_starts)] if commands_with_drops - len(filtered_commands) > 0: print("\t" + str(invalid_query_starts) + " commands removed", commands_with_drops - len(filtered_commands)) return fil...
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
3.20693
3.144478
1.019861
return PrepareSQL(sql, add_semicolon, invalid_starts).prepared
def prepare_sql(sql, add_semicolon=True, invalid_starts=('--', '/*', '*/', ';'))
Wrapper method for PrepareSQL class.
7.215105
4.258646
1.694225
bookends = ("\n", ";", "--", "/*", "*/") last_bookend_found = None start = 0 while start <= len(sql): results = self._get_next_occurrence(sql, start, bookends) if results is None: yield (last_bookend_found, None, sql[start:]) ...
def _split_sql(self, sql)
Generate hunks of SQL that are between the bookends. note: beginning & end of string are returned as None :return: tuple of beginning bookend, closing bookend, and contents
2.908133
2.639197
1.101901
# make map of first char to full needle (only works if all needles # have different first characters) firstcharmap = dict([(n[0], n) for n in needles]) firstchars = firstcharmap.keys() while offset < len(haystack): if haystack[offset] in firstchars: ...
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
3.173164
3.162828
1.003268
def export_content_courses(self, course_id, export_type, skip_notifications=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - export_type self._validate_enum(exp...
Export content. Begin a content export job for a course, group, or user. You can use the {api:ProgressController#show Progress API} to track the progress of the export. The migration's progress is linked to with the _progress_url_ value. When the export...
null
null
null
def export_content_groups(self, group_id, export_type, skip_notifications=None): path = {} data = {} params = {} # REQUIRED - PATH - group_id path["group_id"] = group_id # REQUIRED - export_type self._validate_enum(export_t...
Export content. Begin a content export job for a course, group, or user. You can use the {api:ProgressController#show Progress API} to track the progress of the export. The migration's progress is linked to with the _progress_url_ value. When the export...
null
null
null
def export_content_users(self, user_id, export_type, skip_notifications=None): path = {} data = {} params = {} # REQUIRED - PATH - user_id path["user_id"] = user_id # REQUIRED - export_type self._validate_enum(export_type, ...
Export content. Begin a content export job for a course, group, or user. You can use the {api:ProgressController#show Progress API} to track the progress of the export. The migration's progress is linked to with the _progress_url_ value. When the export...
null
null
null
if no_input: return True else: input_ = input('%s [Y/n] ' % question) input_ = input_.strip().lower() if input_ in ('y', 'yes', ''): return True if input_ in ('n', 'no'): return False print('Invalid selection')
def ask(question, no_input=False)
Display a Y/n question prompt, and return a boolean
2.600665
2.565512
1.013702
return Environment( loader=PackageLoader('remarkable') ).get_template(template_name).render(context)
def render_template(template_name, context)
Render a jinja template
5.395278
5.405574
0.998095
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, arguments.get('--noinput') ): shutil.rmtree(ou...
def render_template_directory(deck, arguments)
Render a template directory
2.794626
2.833339
0.986337
''' 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_countries=configs[...
def main()
set things up
5.829641
5.645814
1.03256
''' 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 tag ''' raw_text = quote.text ...
def _extract_proxies(self, ajax_endpoint)
request the xml object
3.640396
3.45485
1.053706
''' 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_countries is not None and proxy['count...
def _passes_filter(self, proxy)
avoid redudant and space consuming calls to 'self'
4.85557
3.09218
1.570274
''' make a GET request to freeproxylists.com/elite.html ''' url = '/'.join([DOC_ROOT, ELITE_PAGE]) response = requests.get(url) ''' extract the raw HTML doc from the response ''' raw_html = response.text ''' convert raw html into BeautifulSoup object ''' ...
def _extract_ajax_endpoints(self)
make a GET request to freeproxylists.com/elite.html
6.771578
4.680157
1.44687
for m in self.mappings: yield self.indexes[m.clause][m.target], m
def iteritems(self)
Iterates over all mappings Yields ------ (int,Mapping) The next pair (index, mapping)
15.168127
15.725785
0.964539
if "<-" not in string: raise ValueError("Cannot parse the given string to a mapping") target, clause_str = string.split('<-') return cls(Clause.from_str(clause_str), target)
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.Mapping Created object instance
7.571088
4.974967
1.521837
def list_user_logins_users(self, user_id): path = {} data = {} params = {} # REQUIRED - PATH - user_id path["user_id"] = user_id self.logger.debug("GET /api/v1/users/{user_id}/logins with query params: {params} and form data: {data}".format(p...
List user logins. Given a user ID, return that user's logins for the given account.
null
null
null
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): path = {} data = {} params = {} # REQUIRED - PATH - account_id path["accoun...
Create a user login. Create a new login for an existing user in the given account.
null
null
null
def edit_user_login(self, id, account_id, login_integration_id=None, login_password=None, login_sis_user_id=None, login_unique_id=None): path = {} data = {} params = {} # REQUIRED - PATH - account_id path["account_id"] = account_id # REQUIRED...
Edit a user login. Update an existing login for a user in the given account.
null
null
null
def delete_user_login(self, id, user_id): path = {} data = {} params = {} # REQUIRED - PATH - user_id path["user_id"] = user_id # REQUIRED - PATH - id path["id"] = id self.logger.debug("DELETE /api/v1/users/{user...
Delete a user login. Delete an existing login.
null
null
null
def list_questions_in_quiz_or_submission(self, quiz_id, course_id, quiz_submission_attempt=None, quiz_submission_id=None): path = {} data = {} params = {} # REQUIRED - PATH - course_id path["course_id"] = course_id # REQUIRED - PATH - quiz_id...
List questions in a quiz or a submission. Returns the list of QuizQuestions in this quiz.
null
null
null
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,...
Create a single quiz question. Create a new quiz question for this quiz
null
null
null
if s is None: return '' if hasattr(s, '__html__'): return s.__html__() if not isinstance(s, (text_type, binary_type)): s = text_type(s) if isinstance(s, binary_type): try: s.decode('ascii') except: s = s.decode('utf-8', 'replace') ...
def escape(s, quote=False)
Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag `quote` is `True`, the quotation mark character is also translated. There is a special handling for `None` which escapes to an empty string. :param s: the string to escape. :param quote: set to true to also e...
1.760539
1.889941
0.931531
data = self.merge(data, {'user': self.username, 'password': self.password, 'api_id': self.apiId}) return Transport.request(self, action, data, headers, method)
def request(self, action, data={}, headers={}, method='GET')
Append the user authentication details to every incoming request
4.322791
3.773573
1.145543
to = to if isinstance(to, list) else [to] to = [str(i) for i in to] data = {'to': ','.join(to), 'text': message} data = self.merge(data, {'callback': 7, 'mo': 1}, extra) try: content = self.parseLegacy(self.request('http/sendmsg', data)); except Cli...
def sendMessage(self, to, message, extra={})
If the 'to' parameter is a single entry, we will parse it into a list. We will merge default values into the request data and the extra parameters provided by the user.
6.721658
6.442951
1.043258
content = self.parseLegacy(self.request('http/delmsg', {'apimsgid': apiMsgId})) return { 'id': content['ID'], 'status': content['Status'], 'description': self.getStatus(content['Status']) }
def stopMessage(self, apiMsgId)
See parent method for documentation
9.230539
8.663672
1.06543
content = self.parseLegacy(self.request('http/getmsgcharge', {'apimsgid': apiMsgId})) return { 'id': apiMsgId, 'status': content['status'], 'description': self.getStatus(content['status']), 'charge': float(content['charge']) }
def getMessageCharge(self, apiMsgId)
See parent method for documentation
5.737931
5.373638
1.067793
try: content = self.parseLegacy(self.request('utils/routeCoverage', {'msisdn': msisdn})) return { 'routable': True, 'destination': msisdn, 'charge': float(content['Charge']) } except Exception: # If...
def routeCoverage(self, msisdn)
If the route coverage lookup encounters an error, we will treat it as "not covered".
7.344707
6.165972
1.191168
if self.end_date: if not self.start_date: raise ValidationError() elif self.end_date <= self.start_date: raise ValidationError()
def clean_publish_dates(self)
If an end_date value is provided, the start_date must be less.
3.604948
2.382078
1.513363
if self.videos: self.videos = [int(v) for v in self.videos if v is not None and is_valid_digit(v)]
def clean_videos(self)
Validates that all values in the video list are integer ids and removes all None values.
5.417378
3.846616
1.408349
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)]
def clean_super_features(self)
Removes any null & non-integer values from the super feature list
4.83744
3.657726
1.322527
self.clean() if not self.slug: self.slug = slugify(self.name) super(SpecialCoverage, self).save(*args, **kwargs) if self.query and self.query != {}: # Always save and require client to filter active date range self._save_percolator()
def save(self, *args, **kwargs)
Saving ensures that the slug, if not set, is set to the slugified name.
10.427963
9.453106
1.103126
index = Content.search_objects.mapping.index query_filter = self.get_content(published=False).to_dict() q = {} if "query" in query_filter: q = {"query": query_filter.get("query", {})} else: # We don't know how to save this return ...
def _save_percolator(self)
Saves the query field as an elasticsearch percolator
6.775594
6.58636
1.028731
if not hasattr(self, "_content"): self._content = self.get_content() return self._content
def contents(self)
performs .get_content() and caches it in a ._content property
4.325672
2.141477
2.019948
if "query" in self.query: q = self.query["query"] else: q = self.query if "pinned_ids" in q: return bool(len(q.get("pinned_ids", []))) return False
def has_pinned_content(self)
determines if the there is a pinned object in the search
3.483456
3.130579
1.112719
base_path = getattr(settings, "CUSTOM_SPECIAL_COVERAGE_PATH", "special_coverage/custom") if base_path is None: base_path = "" return "{0}/{1}_custom.html".format( base_path, self.slug.replace("-", "_") ).lstrip("/")
def custom_template_name(self)
Returns the path for the custom special coverage template we want.
5.677994
3.801879
1.49347
name, path, args, kwargs = super( ExclusiveBooleanField, self).deconstruct() if self._on_fields: kwargs['on'] = self._on_fields return name, path, args, kwargs
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
5.933122
4.854081
1.222296
if word not in self.tokens: self.tokens[word] = 0 self.tokens[word] += count self.tally += count
def train_token(self, word, count)
Trains a particular token (increases the weight/count of it) :param word: the token we're going to train :type word: str :param count: the number of occurances in the sample :type count: int
2.99419
3.450274
0.867812
if word not in self.tokens: return # If we're trying to untrain more tokens than we have, we end at 0 count = min(count, self.tokens[word]) self.tokens[word] -= count self.tally -= count
def untrain_token(self, word, count)
Untrains a particular token (decreases the weight/count of it) :param word: the token we're going to train :type word: str :param count: the number of occurances in the sample :type count: int
4.386549
4.641226
0.945127
"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) created_models = set() ...
def sync_apps(self, connection, app_labels)
Runs the old syncdb-style operation on a list of app_labels.
3.136654
2.96825
1.056735
# Get table data and columns from source database source = database if database else self.database tables = tables if tables else self.tables # Get database select queries commands = self._get_select_commands(source, tables) # Execute select commands re...
def get_database_rows(self, tables=None, database=None)
Retrieve a dictionary of table keys and list of rows values for every table.
5.460422
5.362506
1.018259
# Create dictionary of select queries row_queries = {tbl: self.select_all(tbl, execute=False) for tbl in tqdm(tables, total=len(tables), desc='Getting {0} select queries'.format(source))} # Convert command strings into lists of commands for tbl, command i...
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
4.18067
3.895591
1.07318
rows = {} for tbl, command in tqdm(commands, total=len(commands), desc='Executing {0} select queries'.format(source)): # Add key to dictionary if tbl not in rows: rows[tbl] = [] rows[tbl].extend(self.fetch(command, commit=True)) self._...
def _execute_select_commands(self, source, commands)
Execute select queries for all of the tables from a source database.
5.016927
4.627272
1.084208
# 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 tbl in tqdm(tables, total=len(tables), ...
def get_database_columns(self, tables=None, database=None)
Retrieve a dictionary of columns.
5.34969
5.069318
1.055308
# 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] = {} _rows = rows.pop(table) _cols = cols.pop(table) if len(_rows) > 1:...
def _get_insert_commands(self, rows, cols)
Retrieve dictionary of insert statements to be executed.
2.541811
2.447034
1.038731
# Change database to source self.change_db(source) if tables is None: tables = self.tables # Change database to destination self.change_db(destination) for t in tqdm(tables, total=len(tables), desc='Copying {0} table structure'.format(source)): ...
def copy_database_structure(self, source, destination, tables=None)
Copy multiple tables from one database to another.
3.236511
3.140553
1.030554
self.execute('CREATE TABLE {0}.{1} LIKE {2}.{1}'.format(destination, wrap(table), source))
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
6.383405
7.148387
0.892985
# Change database to source self.enable_printing = False self.change_db(source) tables = self.tables # Copy database data by executing INSERT and SELECT commands in a single query if optimized: self._copy_database_data_serverside(source, destination,...
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.
5.978931
6.558525
0.911627
for table in tqdm(tables, total=len(tables), desc='Copying table data (optimized)'): self.execute('INSERT INTO {0}.{1} SELECT * FROM {2}.{1}'.format(destination, wrap(table), source))
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
5.015805
4.874702
1.028946
# Retrieve database rows rows = self.get_database_rows(tables, source) # Retrieve database columns cols = self.get_database_columns(tables, source) # Validate rows and columns for r in list(rows.keys()): assert r in tables for c in list(cols...
def _copy_database_data_clientside(self, tables, source, destination)
Copy the data from a table into another table.
3.193639
3.139297
1.01731
print('\tCopying database {0} structure and data to database {1}'.format(source, destination)) with Timer('\nSuccess! Copied database {0} to {1} in '.format(source, destination)): # Create destination database if it does not exist if destination in self.databases: ...
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) Using optimized is about 900% faster Using one_query is...
2.996164
2.95559
1.013728
curesim_pattern = re.compile('@(.*)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)') max_seq_len = 0 fai_index = rnftools.utils.FaIdx(fai_fo=fai_fo) read_tuple_id_width = len(format(number_of_read_tuples, 'x')) fq_creator = rnftools.rnfformat...
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 object of CuReSim FASTQ file. fastq_rnf_fo (file object): File object of RNF FASTQ. fai_fo (file object): File object for FAI file of the reference genome. genome_id (int): RNF genome ID t...
3.234298
3.265824
0.990347
'''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 directories. Returns: list: A list of all match...
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 directories. Returns: list: A list of all matching ...
1.913368
1.667534
1.147423
'''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_wide (bool):Whether to get the system-wide file for...
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_wide (bool):Whether to get the system-wide file for the...
2.413212
1.59201
1.515827
changed_tasks = [] for task in self.client.filter_tasks({'status': 'pending'}): if task.get( 'modified', task.get( 'entry', datetime.datetime(2000, 1, 1).replace(tzinfo=pytz.utc) ) )...
def get_tasks_changed_since(self, since)
Returns a list of tasks that were changed recently.
3.50305
3.436892
1.019249
eqs = self.search(**kwargs) eqs = eqs.filter(Evergreen()) if included_channel_ids: eqs = eqs.filter(VideohubChannel(included_ids=included_channel_ids)) if excluded_channel_ids: eqs = eqs.filter(VideohubChannel(excluded_ids=excluded_channel_ids)) r...
def evergreen(self, included_channel_ids=None, excluded_channel_ids=None, **kwargs)
Search containing any evergreen piece of Content. :included_channel_ids list: Contains ids for channel ids relevant to the query. :excluded_channel_ids list: Contains ids for channel ids excluded from the query.
3.092988
3.068186
1.008084
eqs = self.evergreen(**kwargs) eqs = eqs.filter(VideohubVideo()) return eqs
def evergreen_video(self, **kwargs)
Filter evergreen content to exclusively video content.
16.65358
12.326065
1.351086
eqs = self.search(**kwargs).sort('-last_modified', '-published') return eqs.filter(InstantArticle())
def instant_articles(self, **kwargs)
QuerySet including all published content approved for instant articles. Instant articles are configured via FeatureType. FeatureType.instant_article = True.
17.24394
13.549998
1.272616
eqs = self.search(**kwargs) eqs = eqs.filter(AllSponsored()) published_offset = getattr(settings, "RECENT_SPONSORED_OFFSET_HOURS", None) if published_offset: now = timezone.now() eqs = eqs.filter( Published( after=now -...
def sponsored(self, **kwargs)
Search containing any sponsored pieces of Content.
4.498021
4.155155
1.082516
search_query = super(ContentManager, self).search() if "query" in kwargs: search_query = search_query.query("match", _all=kwargs.get("query")) else: search_query = search_query.sort('-published', '-last_modified') # Right now we have "Before", "After" (...
def search(self, **kwargs)
Query using ElasticSearch, returning an elasticsearch queryset. :param kwargs: keyword arguments (optional) * query : ES Query spec * tags : content tags * types : content types * feature_types : featured types * published : date range
3.119356
3.068176
1.016681
if obj_type in IxnObject.str_2_class: if type(IxnObject.str_2_class[obj_type]) is dict: if self.obj_type() in IxnObject.str_2_class[obj_type]: return IxnObject.str_2_class[obj_type][self.obj_type()] elif self.obj_parent().obj_type() in Ix...
def get_obj_class(self, obj_type)
Returns the object class based on parent and object types. In most cases the object class can be derived from object type alone but sometimes the same object type name is used for different object types so the parent (or even grandparent) type is required in order to determine the exact object ...
1.949129
1.844861
1.056518
value = self.api.getAttribute(self.obj_ref(), attribute) # IXN returns '::ixNet::OK' for invalid attributes. We want error. if value == '::ixNet::OK': raise TgnError(self.ref + ' does not have attribute ' + attribute) return str(value)
def get_attribute(self, attribute)
:param attribute: requested attributes. :return: attribute value. :raise TgnError: if invalid attribute.
9.942215
8.36242
1.188916
list_attribute = self.api.getListAttribute(self.obj_ref(), attribute) # IXN returns '::ixNet::OK' for invalid attributes. We want error. if list_attribute == ['::ixNet::OK']: raise TgnError(self.ref + ' does not have attribute ' + attribute) return list_attribute
def get_list_attribute(self, attribute)
:return: attribute value as Python list.
9.519249
8.6905
1.095363