code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# if this note was automatically filed, don't update the auto-classification information if not self.user: return # if the failure type isn't intermittent, ignore if self.failure_classification.name not in ["intermittent", "intermittent needs filing"]: r...
def _ensure_classification(self)
Ensures a single TextLogError's related bugs have Classifications. If the linked Job has a single meaningful TextLogError: - find the bugs currently related to it via a Classification - find the bugs mapped to the job related to this note - find the bugs that are mapped but not class...
6.200332
4.812278
1.28844
# Only insert bugs for verified failures since these are automatically # mirrored to ES and the mirroring can't be undone # TODO: Decide whether this should change now that we're no longer mirroring. bug_numbers = set(ClassifiedFailure.objects .filter(b...
def create_autoclassify_job_note(self, job, user=None)
Create a JobNote, possibly via auto-classification. Create mappings from the given Job to Bugs via verified Classifications of this Job. Also creates a JobNote.
5.837388
5.56088
1.049724
components = self._serialized_components() if not components: return [] from treeherder.model.error_summary import get_useful_search_results job = Job.objects.get(guid=self.job_guid) rv = [] ids_seen = set() for item in get_useful_search_resu...
def unstructured_bugs(self)
Get bugs that match this line in the Bug Suggestions artifact for this job.
6.09486
5.555965
1.096994
data = { "action": self.action, "line_number": self.line, "test": self.test, "subtest": self.subtest, "status": self.status, "expected": self.expected, "message": self.message, "signature": self.signature, ...
def to_mozlog_format(self)
Convert a FailureLine into a mozlog formatted dictionary.
2.700786
2.493135
1.083289
if bug_number == self.bug_number: return self other = ClassifiedFailure.objects.filter(bug_number=bug_number).first() if not other: self.bug_number = bug_number self.save(update_fields=['bug_number']) return self self.replace_wit...
def set_bug(self, bug_number)
Set the bug number of this Classified Failure If an existing ClassifiedFailure exists with the same bug number replace this instance with the existing one.
3.290671
2.413797
1.363276
match_ids_to_delete = list(self.update_matches(other)) TextLogErrorMatch.objects.filter(id__in=match_ids_to_delete).delete() # Update best classifications self.best_for_errors.update(best_classification=other) self.delete()
def replace_with(self, other)
Replace this instance with the given other. Deletes stale Match objects and updates related TextLogErrorMetadatas' best_classifications to point to the given other.
9.349099
4.435562
2.10776
for match in self.error_matches.all(): other_matches = TextLogErrorMatch.objects.filter( classified_failure=other, text_log_error=match.text_log_error, ) if not other_matches: match.classified_failure = other ...
def update_matches(self, other)
Update this instance's Matches to point to the given other's Matches. Find Matches with the same TextLogError as our Matches, updating their score if less than ours and mark our matches for deletion. If there are no other matches, update ours to point to the other ClassifiedFailure.
5.047113
3.422959
1.474488
if classification is None: classification = ClassifiedFailure.objects.create() TextLogErrorMatch.objects.create( text_log_error=self, classified_failure=classification, matcher_name=matcher_name, score=1, )
def create_match(self, matcher_name, classification)
Create a TextLogErrorMatch instance Typically used for manual "matches" or tests.
6.308585
4.051741
1.557006
if classification not in self.classified_failures.all(): self.create_match("ManualDetector", classification) # create a TextLogErrorMetadata instance for this TextLogError if it # doesn't exist. We can't use update_or_create here since OneToOne # relations don't us...
def verify_classification(self, classification)
Mark the given ClassifiedFailure as verified. Handles the classification not currently being related to this TextLogError and no Metadata existing.
6.828479
5.618361
1.215386
if settings.BUGFILER_API_KEY is None: return Response({"failure": "Bugzilla API key not set!"}, status=HTTP_400_BAD_REQUEST) params = request.data # Arbitrarily cap crash signatures at 2048 characters to prevent perf issues on bmo crash_...
def create_bug(self, request)
Create a bugzilla bug with passed params
2.749194
2.707821
1.015279
min_id = 0 while True: chunk = qs.filter(id__gt=min_id).order_by('id') if fields is not None: chunk = chunk.only(*fields) # Cast to a list to execute the QuerySet here and allow us to get the # last ID when updating min_id. We can't use .last() later as it ...
def chunked_qs(qs, chunk_size=10000, fields=None)
Generator to iterate over the given QuerySet, chunk_size rows at a time Usage: >>> qs = FailureLine.objects.filter(action='test_result') >>> for qs in chunked_qs(qs, chunk_size=10000, fields=['id', 'message']): ... for line in qs: ... print(line.message) Note: Whil...
5.336995
6.220594
0.857956
if not qs: return qs = qs.order_by('-id') # Can't use .only() here in case the query used select_related max_id = qs.first().id while True: chunk = qs.filter(id__lte=max_id) # upper bound of this chunk rows = chunk[:chunk_size] if len(rows) < 1: ...
def chunked_qs_reverse(qs, chunk_size=10000)
Generator to iterate over the given QuerySet in reverse chunk_size rows at a time Usage: >>> qs = FailureLine.objects.filter(action='test_result') >>> for qs in chunked_qs_reverse(qs, chunk_size=100): ... for line in qs: ... print(line.message) Note: This method is...
4.60999
4.784137
0.963599
job_id = int(request.data['job_id']) bug_id = int(request.data['bug_id']) try: BugJobMap.create( job_id=job_id, bug_id=bug_id, user=request.user, ) message = "Bug job map saved" except Integrity...
def create(self, request, project)
Add a new relation between a job and a bug.
3.308303
2.828607
1.169587
job_id, bug_id = map(int, pk.split("-")) job = Job.objects.get(repository__name=project, id=job_id) BugJobMap.objects.filter(job=job, bug_id=bug_id).delete() return Response({"message": "Bug job map deleted"})
def destroy(self, request, project, pk=None)
Delete bug-job-map entry. pk is a composite key in the form bug_id-job_id
4.376632
2.82737
1.547952
job_id, bug_id = map(int, pk.split("-")) job = Job.objects.get(repository__name=project, id=job_id) try: bug_job_map = BugJobMap.objects.get(job=job, bug_id=bug_id) serializer = BugJobMapSerializer(bug_job_map) return Response(serializer.data) ...
def retrieve(self, request, project, pk=None)
Retrieve a bug-job-map entry. pk is a composite key in the form bug_id-job_id
2.747061
2.137282
1.285306
match = match_obj.group(0) code_point = ord(match) hex_repr = hex(code_point) hex_code_point = hex_repr[2:] hex_value = hex_code_point.zfill(6).upper() return '<U+{}>'.format(hex_value)
def convert_unicode_character_to_ascii_repr(match_obj)
Converts a matched pattern from a unicode character to an ASCII representation For example the emoji 🍆 would get converted to the literal <U+01F346>
3.110009
3.170081
0.98105
for repo in Repository.objects.filter(dvcs_type='hg', active_status="active"): fetch_hg_push_log.apply_async( args=(repo.name, repo.url), queue='pushlog' )
def fetch_push_logs()
Run several fetch_hg_push_log subtasks, one per repository
8.205929
5.342367
1.53601
newrelic.agent.add_custom_parameter("repo_name", repo_name) process = HgPushlogProcess() process.run(repo_url + '/json-pushes/?full=1&version=2', repo_name)
def fetch_hg_push_log(repo_name, repo_url)
Run a HgPushlog etl process
8.448538
6.980814
1.210251
newrelic.agent.add_custom_parameter("exchange", exchange) newrelic.agent.add_custom_parameter("routing_key", routing_key) JobLoader().process_job(pulse_job)
def store_pulse_jobs(pulse_job, exchange, routing_key)
Fetches the jobs pending from pulse exchanges and loads them.
3.342905
3.300565
1.012828
newrelic.agent.add_custom_parameter("exchange", exchange) newrelic.agent.add_custom_parameter("routing_key", routing_key) PushLoader().process(body, exchange)
def store_pulse_pushes(body, exchange, routing_key)
Fetches the pushes pending from pulse exchanges and loads them.
3.925619
3.930312
0.998806
logger.debug('Running store_failure_lines for job %s', job_log.job.id) failureline.store_failure_lines(job_log)
def store_failure_lines(job_log)
Store the failure lines from a log corresponding to the structured errorsummary file.
4.533306
4.556267
0.994961
try: serializer = JobNoteSerializer(JobNote.objects.get(id=pk)) return Response(serializer.data) except JobNote.DoesNotExist: return Response("No note with id: {0}".format(pk), status=HTTP_404_NOT_FOUND)
def retrieve(self, request, project, pk=None)
GET method implementation for a note detail
2.884963
2.909244
0.991654
job_id = request.query_params.get('job_id') if not job_id: raise ParseError(detail="The job_id parameter is mandatory for this endpoint") try: job_id = int(job_id) except ValueError: raise ParseError(detail="The job_id parameter must be an in...
def list(self, request, project)
GET method implementation for list view job_id -- Mandatory filter indicating which job these notes belong to.
2.516751
2.156811
1.166885
JobNote.objects.create( job=Job.objects.get(repository__name=project, id=int(request.data['job_id'])), failure_classification_id=int(request.data['failure_classification_id']), user=request.user, text=request.data.get('text...
def create(self, request, project)
POST method implementation
4.223063
4.154098
1.016602
try: note = JobNote.objects.get(id=pk) note.delete() return Response({"message": "Note deleted"}) except JobNote.DoesNotExist: return Response("No note with id: {0}".format(pk), status=HTTP_404_NOT_FOUND)
def destroy(self, request, project, pk=None)
Delete a note entry
2.92039
2.704852
1.079686
# parse a log given its url artifact_bc = ArtifactBuilderCollection(job_log.url) artifact_bc.parse() artifact_list = [] for name, artifact in artifact_bc.artifacts.items(): artifact_list.append({ "job_guid": job_log.job.guid, "name": name, "type": '...
def extract_text_log_artifacts(job_log)
Generate a set of artifacts by parsing from the raw text log.
4.844983
4.708055
1.029084
logger.debug("Downloading/parsing log for log %s", job_log.id) try: artifact_list = extract_text_log_artifacts(job_log) except LogSizeException as e: job_log.update_status(JobLog.SKIPPED_SIZE) logger.warning('Skipping parsing log for %s: %s', job_log.id, e) return e...
def post_log_artifacts(job_log)
Post a list of artifacts to a job.
3.957648
3.973348
0.996049
cache_key = 'error-summary-{}'.format(job.id) cached_error_summary = cache.get(cache_key) if cached_error_summary is not None: return cached_error_summary # don't cache or do anything if we have no text log errors to get # results for errors = TextLogError.objects.filter(step__job=...
def get_error_summary(job)
Create a list of bug suggestions for a job. Caches the results if there are any.
5.131773
4.644391
1.10494
if term_cache is None: term_cache = {} # remove the mozharness prefix clean_line = get_mozharness_substring(err.line) # get a meaningful search term out of the error line search_term = get_error_search_term(clean_line) bugs = dict(open_recent=[], all_others=[]) # collect open...
def bug_suggestions_line(err, term_cache=None)
Get Bug suggestions for a given TextLogError (err). Tries to extract a search term from a clean version of the given error's line. We build a search term from the cleaned line and use that to search for bugs. Returns a dictionary with the cleaned line, the generated search term, and any bugs found wi...
4.065295
3.872999
1.04965
if not error_line: return None # This is strongly inspired by # https://hg.mozilla.org/webtools/tbpl/file/tip/php/inc/AnnotatedSummaryGenerator.php#l73 tokens = error_line.split(" | ") search_term = None if len(tokens) >= 3: # If this is process output then discard the to...
def get_error_search_term(error_line)
Generate a search term from the given error_line string. Attempt to build a search term that will yield meaningful results when used in a MySQL FTS query.
7.588298
7.559613
1.003795
search_term = None match = CRASH_RE.match(error_line) if match and is_helpful_search_term(match.group(1)): search_term = match.group(1) return search_term
def get_crash_signature(error_line)
Try to get a crash signature from the given error_line string.
3.860795
3.921077
0.984626
# Search terms that will match too many bug summaries # and so not result in useful suggestions. search_term = search_term.strip() blacklist = [ 'automation.py', 'remoteautomation.py', 'Shutdown', 'undefined', 'Main app process exited normally', 'Tra...
def is_helpful_search_term(search_term)
Decide if the given search_term string is helpful or not. We define "helpful" here as search terms that won't match an excessive number of bug summaries. Very short terms and those matching generic strings (listed in the blacklist) are deemed unhelpful since they wouldn't result in useful suggestions.
9.508535
8.292622
1.146626
for match in matches: # generate a new score from the current match dividend, divisor = score_multiplier score = match.score * dividend / divisor yield (score, match.classified_failure_id)
def score_matches(matches, score_multiplier=(1, 1))
Get scores for the given matches. Given a QuerySet of TextLogErrorMatches produce a score for each one until Good Enough™. An optional score multiplier can be passed in.
9.281891
8.116714
1.143553
time_budget = time_budget / 1000 # budget in milliseconds start = time.time() for thing in iterable: yield func(thing, *args) end = time.time() - start if end > time_budget: # Putting the condition at the end of the loop ensures that we # always run it...
def time_boxed(func, iterable, time_budget, *args)
Apply a function to the items of an iterable within a given time budget. Loop the given iterable, calling the given function on each item. The expended time is compared to the given time budget after each iteration.
5.699295
5.83808
0.976227
'''This structure helps with finding data from the job priorities table''' jp_index = {} # Creating this data structure which reduces how many times we iterate through the DB rows for jp in job_priorities: key = jp.unique_identifier() # This is guaranteed by a unique composite index for...
def job_priority_index(job_priorities)
This structure helps with finding data from the job priorities table
11.97682
9.753647
1.227933
job_guid = pulse_job["taskId"] x = { "job": { "job_guid": job_guid, "name": pulse_job["display"].get("jobName", "unknown"), "job_symbol": self._get_job_symbol(pulse_job), "group_name": pulse_job["display"].get("groupNa...
def transform(self, pulse_job)
Transform a pulse job into a job that can be written to disk. Log References and artifacts will also be transformed and loaded with the job. We can rely on the structure of ``pulse_job`` because it will already have been validated against the JSON Schema at this point.
4.276568
4.23673
1.009403
try: push = Push.objects.get(repository__name=project, id=pk) serializer = PushSerializer(push) return Response(serializer.data) except Push.DoesNotExist: return Response("No push with id: {0}".format(pk), ...
def retrieve(self, request, project, pk=None)
GET method implementation for detail view of ``push``
2.646844
2.502431
1.057709
try: push = Push.objects.get(id=pk) except Push.DoesNotExist: return Response("No push with id: {0}".format(pk), status=HTTP_404_NOT_FOUND) return Response(push.get_status())
def status(self, request, project, pk=None)
Return a count of the jobs belonging to this push grouped by job status.
2.855919
2.447019
1.167101
revision = request.query_params.get('revision') try: push = Push.objects.get(revision=revision, repository__name=project) except Push.DoesNotExist: return Response("No push with revision: {0}".format(revision), status=HTTP_404_NOT_FOU...
def health(self, request, project)
Return a calculated assessment of the health of this push.
4.030907
3.848023
1.047527
push_ids = request.query_params.getlist('push_ids') job_type = JobType.objects.get(name='Gecko Decision Task') decision_jobs = Job.objects.filter( push_id__in=push_ids, job_type=job_type ).select_related('taskcluster_metadata') if decision_jobs: ...
def decisiontask(self, request, project)
Return the decision task ids for the pushes.
3.549741
3.118267
1.13837
filename = '{0}.js'.format(language_code) path = os.path.join('tinymce', 'js', 'tinymce', 'langs', filename) return finders.find(path) is not None
def language_file_exists(language_code)
Check if TinyMCE has a language file for the specified lang code :param language_code: language code :type language_code: str :return: check result :rtype: bool
4.555304
4.431204
1.028006
language_code = convert_language_code(get_language() or settings.LANGUAGE_CODE) if not language_file_exists(language_code): language_code = language_code[:2] if not language_file_exists(language_code): # Fall back to English if Tiny MCE 4 does not have required translation ...
def get_language_config()
Creates a language configuration for TinyMCE4 based on Django project settings :return: language- and locale-related parameters for TinyMCE 4 :rtype: dict
3.234429
3.272619
0.98833
config = {} if mce_settings.USE_SPELLCHECKER: from enchant import list_languages enchant_languages = list_languages() if settings.DEBUG: logger.info('Enchant languages: {0}'.format(enchant_languages)) lang_names = [] for lang, name in settings.LANGUAGES: ...
def get_spellcheck_config()
Create TinyMCE spellchecker config based on Django settings :return: spellchecker parameters for TinyMCE :rtype: dict
2.952448
2.994308
0.98602
lang_and_country = django_lang.split('-') try: return '_'.join((lang_and_country[0], lang_and_country[1].upper())) except IndexError: return lang_and_country[0]
def convert_language_code(django_lang)
Converts Django language codes "ll-cc" into ISO codes "ll_CC" or "ll" :param django_lang: Django language code as ll-cc :type django_lang: str :return: ISO language code as ll_CC :rtype: str
2.638319
2.943265
0.896392
if mce_settings.USE_FILEBROWSER and 'file_browser_callback' not in callbacks: callbacks['file_browser_callback'] = 'djangoFileBrowser' if mce_settings.USE_SPELLCHECKER and 'spellchecker_callback' not in callbacks: callbacks['spellchecker_callback'] = 'tinymce4_spellcheck' if id_: ...
def render_tinymce_init_js(mce_config, callbacks, id_)
Renders TinyMCE.init() JavaScript code :param mce_config: TinyMCE 4 configuration :type mce_config: dict :param callbacks: TinyMCE callbacks :type callbacks: dict :param id_: HTML element's ID to which TinyMCE is attached. :type id_: str :return: TinyMCE.init() code :rtype: str
3.217269
3.322925
0.968204
for item in sys.argv: if re.search(r'manage.py|django-admin|django', item) is not None: return True return False
def is_managed()
Check if a Django project is being managed with ``manage.py`` or ``django-admin`` scripts :return: Check result :rtype: bool
5.649064
4.732367
1.193708
data = json.loads(request.body.decode('utf-8')) output = {'id': data['id']} error = None status = 200 try: if data['params']['lang'] not in list_languages(): error = 'Missing {0} dictionary!'.format(data['params']['lang']) raise LookupError(error) spell_c...
def spell_check(request)
Implements the TinyMCE 4 spellchecker protocol :param request: Django http request with JSON-RPC payload from TinyMCE 4 containing a language code and a text to check for errors. :type request: django.http.request.HttpRequest :return: Django http response containing JSON-RPC payload with sp...
3.051659
2.979917
1.024075
if 'grappelli' in settings.INSTALLED_APPS: margin_left = 0 elif VERSION[:2] <= (1, 8): margin_left = 110 # For old style admin else: margin_left = 170 # For Django >= 1.9 style admin # For Django >= 2.0 responsive admin responsive_admin = VERSION[:2] >= (2, 0) retu...
def css(request)
Custom CSS for TinyMCE 4 widget By default it fixes widget's position in Django Admin :param request: Django http request :type request: django.http.request.HttpRequest :return: Django http response with CSS file for TinyMCE 4 :rtype: django.http.HttpResponse
3.667949
3.464633
1.058683
try: fb_url = reverse('fb_browse') except: fb_url = reverse('filebrowser:fb_browse') return HttpResponse(jsmin(render_to_string('tinymce/filebrowser.js', context={'fb_url': fb_url}, request=req...
def filebrowser(request)
JavaScript callback function for `django-filebrowser`_ :param request: Django http request :type request: django.http.request.HttpRequest :return: Django http response with filebrowser JavaScript code for for TinyMCE 4 :rtype: django.http.HttpResponse .. _django-filebrowser: https://github.com/seh...
3.380924
3.1104
1.086974
err = "glaad.offensive_terms" msg = "Offensive term. Remove it or consider the context." list = [ "fag", "faggot", "dyke", "sodomite", "homosexual agenda", "gay agenda", "transvestite", "homosexual lifestyle", "gay lifestyle" ...
def check(text)
Flag offensive words based on the GLAAD reference guide.
13.461788
11.319368
1.18927
tp = 0 fp = 0 parent_directory = os.path.dirname(proselint_path) path_to_corpus = os.path.join(parent_directory, "corpora", "0.1.0") for root, _, files in os.walk(path_to_corpus): files = [f for f in files if f.endswith(".md")] for f in files: fullpath = os.path.joi...
def score(check=None)
Compute the linter's score on the corpus. Proselint's score reflects the desire to have a linter that catches many errors, but which takes false alarms seriously. It is better not to say something than to say the wrong thing, and the harm from saying the wrong thing is greater than the benefit of sayin...
3.355248
3.179037
1.055429
err = "oxford.venery_terms" msg = "The venery term is '{}'." term_list = [ ["alligators", "congregation"], ["antelopes", "herd"], ["baboons", "troop"], ["badgers", "cete"], ["bats", "colony"], ["bears", "sloth"], ["b...
def check(text)
Check the text.
4.668755
4.671267
0.999462
err = "links.valid" msg = u"Broken link: {}" regex = re.compile( r, re.U | re.X) errors = [] for m in re.finditer(regex, text): url = m.group(0).strip() if "http://" not in url and "https://" not in url: url = "http://" + url if is_broken_...
def check(text)
Check the text.
3.838065
3.977308
0.964991
try: request = urllib_request.Request( url, headers={'User-Agent': 'Mozilla/5.0'}) urllib_request.urlopen(request).read() return False except urllib_request.URLError: return True except SocketError: return True
def is_broken_link(url)
Determine whether the link returns a 404 error.
2.516671
2.455321
1.024987
err = "security.credit_card" msg = u"Don't put credit card numbers in plain text." credit_card_numbers = [ "4\d{15}", "5[1-5]\d{14}", "3[4,7]\d{13}", "3[0,6,8]\d{12}", "6011\d{12}", ] return existence_check(text, credit_card_numbers, err, msg)
def check(text)
Check the text.
4.289152
4.239241
1.011774
err = "misc.annotations" msg = u"Annotation left in text." annotations = [ "FIXME", "FIX ME", "TODO", "todo", "ERASE THIS", "FIX THIS", ] return existence_check( text, annotations, err, msg, ignore_case=False, join=True)
def check(text)
Check the text.
10.978914
11.335146
0.968573
err = "misc.suddenly" msg = u"Suddenly is nondescript, slows the action, and warns your reader." regex = "Suddenly," return existence_check(text, [regex], err, msg, max_errors=3, require_padding=False, offset=-1, ignore_case=False)
def check(text)
Advice on sudden vs suddenly.
22.165125
19.893539
1.114187
err = "weasel_words.very" msg = ("Substitute 'damn' every time you're " "inclined to write 'very'; your editor will delete it " "and the writing will be just as it should be.") regex = "very" return existence_check(text, [regex], err, msg, max_errors=1)
def check(text)
Avoid 'very'.
23.986689
20.770266
1.154857
err = "psychology.p_equals_zero" msg = "Unless p really equals zero, you should use more decimal places." list = [ "p = 0.00", "p = 0.000", "p = 0.0000", ] return existence_check(text, list, err, msg, join=True)
def check_p_equals_zero(text)
Check for p = 0.000.
7.265971
6.642661
1.093834
err = "garner.phrasal_adjectives.ly" msg = u regex = "\s[^\s-]+ly-" return existence_check(text, [regex], err, msg, require_padding=False, offset=-1)
def check_ly(text)
Check the text.
36.062756
35.962135
1.002798
auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return "60/minute" else: return "600/minute"
def rate()
Set rate limits for authenticated and nonauthenticated users.
4.877757
4.391913
1.110622
if 'text' in request.values: text = unquote(request.values['text']) job = q.enqueue(worker_function, text) return jsonify(job_id=job.id), 202 elif 'job_id' in request.values: job = q.fetch_job(request.values['job_id']) if not job: return jsonify( ...
def lint()
Run linter on the provided text and return the results.
2.742808
2.663967
1.029596
err = "MAU102" msg = "Months should be capitalized. '{}' is the preferred form." list = [ ["January", ["january"]], ["February", ["february"]], # ["March", ["march"]], ["April", ["april"]], # ["May", ["may"]], ...
def check_months(text)
Suggest the preferred forms.
3.162834
2.734136
1.156795
err = "MAU102" msg = "Days of the week should be capitalized. '{}' is the preferred form." list = [ ["Monday", ["monday"]], ["Tuesday", ["tuesday"]], ["Wednesday", ["wednesday"]], ["Thursday", ["thursday"]], ["Friday", ["friday"]], ...
def check_days(text)
Suggest the preferred forms.
4.426268
3.5859
1.234353
err = "skunked_terms.misc" msg = u skunked_terms = [ "bona fides", "deceptively", "decimate", "effete", "fulsome", "hopefully", "impassionate", "Thankfully,", ] return existence_check(text, skunked_terms, err, msg)
def check(text)
Check the text.
15.694012
15.503902
1.012262
err = "misc.illogic" msg = u"'{}' is illogical." illogics = [ "preplan", "more than .{1,10} all", "appraisal valuations?", "(?:i|you|he|she|it|y'all|all y'all|you all|they) could care less", "least worst", "much-needed gaps?", "much-needed voids?...
def check(text)
Check the text.
19.28051
19.229511
1.002652
err = "misc.illogic.coin" msg = "You can't coin an existing phrase. Did you mean 'borrow'?" regex = "to coin a phrase from" return existence_check(text, [regex], err, msg, offset=1)
def check_coin_a_phrase_from(text)
Check the text.
20.879539
21.50918
0.970727
err = "misc.illogic.collusion" msg = "It's impossible to defraud yourself. Try 'aquiescence'." regex = "without your collusion" return existence_check( text, [regex], err, msg, require_padding=False, offset=-1)
def check_without_your_collusion(text)
Check the textself.
23.977152
24.857704
0.964576
err = "leonard.exclamation.multiple" msg = u"Stop yelling. Keep your exclamation points under control." regex = r"[\!]\s*?[\!]{1,}" return existence_check( text, [regex], err, msg, require_padding=False, ignore_case=False, max_errors=1, dotall=True)
def check_repeated_exclamations(text)
Check the text.
15.493361
15.64305
0.990431
err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." regex = r"\w!" count = len(re.findall(regex, text)) num_words = len(text.split(" ")) ppm = (count*1.0 / num_words) * 1e6 if ppm > 30 and count > 1: loc = re.search(regex, te...
def check_exclamations_ppm(text)
Make sure that the exclamation ppm is under 30.
5.85971
5.650705
1.036987
err = "strunk_white.composition" msg = "Try '{}' instead of '{}'." bad_forms = [ # Put statements in positive form ["dishonest", ["not honest"]], ["trifling", ["not important"]], ["forgot", ["did not remember"]], ["i...
def check(text)
Suggest the preferred forms.
11.244614
10.978909
1.024201
err = "consistency.spelling" msg = "Inconsistent spelling of '{}' (vs. '{}')." word_pairs = [ ["advisor", "adviser"], # ["analyse", "analyze"], ["centre", "center"], ["colour", "color"], ["emphasise", "emphasize"], ["finalise", "finalize"], ["foc...
def check(text)
Check the text.
4.784875
4.794759
0.997939
err = "uncomparables.misc" msg = "Comparison of an uncomparable: '{}' is not comparable." comparators = [ "most", "more", "less", "least", "very", "quite", "largely", "extremely", "increasingly", "kind of", "mildly...
def check(text)
Check the text.
4.825146
4.823952
1.000248
err = "consistency.spacing" msg = "Inconsistent spacing after period (1 vs. 2 spaces)." regex = ["[\.\?!] [A-Z]", "[\.\?!] [A-Z]"] return consistency_check(text, [regex], err, msg)
def check(text)
Check the text.
14.491836
14.554904
0.995667
err = "pinker.latin" msg = "Use English. '{}' is the preferred form." list = [ ["other things being equal", ["ceteris paribus"]], ["among other things", ["inter alia"]], ["in and of itself", ["simpliciter"]], ["having made the ne...
def check(text)
Suggest the preferred forms.
21.874271
19.782476
1.10574
err = "hyperbolic.misc" msg = u"'{}' is hyperbolic." words = [ "[a-z]*[!]{2,}", "[a-z]*\?{2,}" ] return existence_check(text, words, err, msg)
def check(text)
Check the text.
11.002844
11.453397
0.960662
err = "glaad.terms" msg = "Possibly offensive term. Consider using '{}' instead of '{}'." list = [ ["gay man", ["homosexual man"]], ["gay men", ["homosexual men"]], ["lesbian", ["homosexual woman"]], ["lesbians", ["homosexual w...
def check(text)
Suggest preferred forms given the reference document.
6.472817
6.089002
1.063034
err = "MSC104" msg = u"Don't fail to capitalize roman numeral abbreviations." pwd_regex = " (I(i*)|i*)" password = [ "World War{}".format(pwd_regex), ] return blacklist(text, password, err, msg)
def check(text)
Check the text.
33.673737
35.320377
0.95338
for path, _, files in os.walk(os.getcwd()): for fname in [f for f in files if os.path.splitext(f)[1] == ".pyc"]: try: os.remove(os.path.join(path, fname)) except OSError: pass
def _delete_compiled_python_files()
Remove files with a 'pyc' extension.
2.24698
1.930749
1.163787
if output_json: click.echo(errors_to_json(errors)) else: for error in errors: (check, message, line, column, start, end, extent, severity, replacements) = error if compact: filename = "-" click.echo( filena...
def print_errors(filename, errors, output_json=False, compact=False)
Print the errors, resulting from lint, for filename.
4.500093
4.214088
1.067869
if time: click.echo(timing_test()) return # In debug or clean mode, delete cache & *.pyc files before running. if debug or clean: clear_cache() # Use the demo file by default. if demo: paths = [demo_file] # Expand the list of directories and files. fil...
def proselint(paths=None, version=None, clean=None, debug=None, output_json=None, time=None, demo=None, compact=None)
A CLI for proselint, a linter for prose.
4.045667
4.08882
0.989446
expanded_files = [] legal_extensions = [".md", ".txt", ".rtf", ".html", ".tex", ".markdown"] for f in files: # If it's a directory, recursively walk through it and find the files. if os.path.isdir(f): for dir_, _, filenames in os.walk(f): for filename in fil...
def extract_files(files)
Expand list of paths to include all text files matching the pattern.
2.663642
2.511143
1.060729
err = "misc.not_guilty" msg = u"'not guilty beyond a reasonable doubt' is an ambiguous phrasing." regex = r"not guilty beyond (a |any )?reasonable doubt" return existence_check(text, [regex], err, msg)
def check(text)
Check the text.
15.047781
15.589814
0.965232
err = "hedging.misc" msg = "Hedging. Just say it." narcissism = [ "I would argue that", ", so to speak", "to a certain degree", ] return existence_check(text, narcissism, err, msg)
def check(text)
Suggest the preferred forms.
20.015615
19.332626
1.035328
err = "misc.tense_present" msg = u"'{}'." illogics = [ u"up to \d{1,3}% ?[-\u2014\u2013]{0,3} ?(?:or|and) more\W?", "between you and I", "on accident", "somewhat of a", "all it's own", "reason is because", "audible to the ear", "in regard...
def check(text)
Check the text.
10.480495
10.619309
0.986928
err = "terms.denizen_labels.garner" msg = "'{}' is the preferred denizen label." preferences = [ ["Afrikaner", ["Afrikaaner"]], ["Afrikaner", ["Afrikander"]], ["Alabamian", ["Alabaman"]], ["Albuquerquean", ["Albuquerquian"]], ["Ancho...
def check(text)
Suggest the preferred forms. source: Garner's Modern American Usage source_url: http://bit.ly/1T4alrY
4.383043
4.292191
1.021167
err = "terms.denizen_labels.norris" msg = "Would you like '{}'?" preferences = [ ["Mancunian", ["Manchesterian"]], ["Mancunians", ["Manchesterians"]], ["Vallisoletano", ["Valladolidian"]], ["Wulfrunian", ["Wolverhamptonian", "Wolverhamptonite"]...
def check_denizen_labels_norris(text)
Suggest the preferred forms. source: Mary Norris source_url: http://nyr.kr/1rGienj
8.563713
8.394503
1.020157
err = "institution.vtech" msg = "Incorrect name. Use '{}' instead of '{}'." institution = [ ["Virginia Polytechnic Institute and State University", ["Virginia Polytechnic and State University"]], ] return preferred_forms_check(text, institution, err, msg)
def check_vtech(text)
Suggest the correct name. source: Virginia Tech Division of Student Affairs source_url: http://bit.ly/2en1zbv
11.093228
9.530507
1.16397
err = "malapropisms.misc" msg = u"'{}' is a malapropism." illogics = [ "the infinitesimal universe", "a serial experience", "attack my voracity", ] return existence_check(text, illogics, err, msg, offset=1)
def check(text)
Check the text.
24.551813
25.541832
0.961239
err = "dates_times.am_pm.midnight_noon" msg = (u"'a.m.' is always morning; 'p.m.' is always night.") list = [ "\d{1,2} ?a\.?m\.? in the morning", "\d{1,2} ?p\.?m\.? in the evening", "\d{1,2} ?p\.?m\.? at night", "\d{1,2} ?p\.?m\.? in the afternoon", ] return ex...
def check_redundancy(text)
Check the text.
5.085111
5.081238
1.000762
err = "sexism.misc" msg = "Gender bias. Use '{}' instead of '{}'." sexism = [ ["anchor", ["anchorman", "anchorwoman"]], ["chair", ["chairman", "chairwoman"]], ["drafter", ["draftman", "draftwoman"]], ["ombuds", ["ombudsman", "ombu...
def check(text)
Suggest the preferred forms.
3.796034
3.672098
1.033751
err = "dates_times.dates" msg = u"Apostrophes aren't needed for decades." regex = "\d0\'s" return existence_check( text, [regex], err, msg, excluded_topics=["50 Cent"])
def check_decade_apostrophes_short(text)
Check the text for dates of the form X0's.
24.259533
20.565775
1.179607
err = "dates_times.dates" msg = u"Apostrophes aren't needed for decades." regex = "\d\d\d0\'s" return existence_check(text, [regex], err, msg)
def check_decade_apostrophes_long(text)
Check the text for dates of the form XXX0's.
13.351347
11.710026
1.140164
err = "dates_times.dates" msg = u"When specifying a date range, write 'from X to Y'." regex = "[fF]rom \d+[^ \t\n\r\f\va-zA-Z0-9_\.]\d+" return existence_check(text, [regex], err, msg)
def check_dash_and_from(text)
Check the text.
13.72939
14.014288
0.979671
err = "dates_times.dates" msg = u"When specifying a month and year, no comma is needed." regex = "(?:" + "|".join(calendar.month_name[1:]) + "), \d{3,}" return existence_check(text, [regex], err, msg)
def check_month_year_comma(text)
Check the text.
12.650112
12.831022
0.985901
err = "dates_times.dates" msg = u"When specifying a month and year, 'of' is unnecessary." regex = "(?:" + "|".join(calendar.month_name[1:]) + ") of \d{3,}" return existence_check(text, [regex], err, msg)
def check_month_of_year(text)
Check the text.
12.820539
12.880151
0.995372
err = "redundancy.wallace" msg = "Redundancy. Use '{}' instead of '{}'." redundancies = [ ["rectangular", ["rectangular in shape"]], ["audible", ["audible to the ear"]], ] return preferred_forms_check(text, redundancies, err, msg)
def check(text)
Suggest the preferred forms.
17.369579
14.630193
1.187242
err = "redundancy.nordquist" msg = "Redundancy. Use '{}' instead of '{}'." redundancies = [ ["essential", ["absolutely essential"]], ["necessary", ["absolutely necessary"]], ["a.m.", ["a.m. in the morning"]], ["p.m.", ["p.m....
def check_nordquist(text)
Suggest the preferred forms. source: Richard Nordquist source_url: http://grammar.about.com/bio/Richard-Nordquist-22176.htm
7.491718
6.611572
1.133122
@functools.wraps(f) def wrapped(*args, **kwargs): f(*args, **kwargs) close_cache_shelves() return wrapped
def close_cache_shelves_after(f)
Decorator that ensures cache shelves are closed after the call.
2.120782
1.928928
1.099462
# Determine the location of the cache. cache_dirname = os.path.join(_get_xdg_cache_home(), 'proselint') legacy_cache_dirname = os.path.join(os.path.expanduser("~"), ".proselint") if not os.path.isdir(cache_dirname): # Migrate the cache from the legacy path to XDG complaint location. ...
def memoize(f)
Cache results of computations on disk.
2.931182
2.900421
1.010606