code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
app.sitemap_links.append(pagename + ".html") | def add_html_link(app, pagename, templatename, context, doctree) | As each page is built, collect page names for the sitemap | 14.309126 | 7.677018 | 1.863891 |
site_url = app.builder.config.site_url or app.builder.config.html_baseurl
if not site_url:
print("sphinx-sitemap error: neither html_baseurl nor site_url "
"are set in conf.py. Sitemap not built.")
return
if (not app.sitemap_links):
print("sphinx-sitemap warning: N... | def create_sitemap(app, exception) | Generates the sitemap.xml from the collected HTML page links | 2.312497 | 2.273273 | 1.017255 |
ideal = [float("inf")] * mo_prob.nobj
nadir = [float("-inf")] * mo_prob.nobj
for i in range(mo_prob.nobj):
meth = opt_meth_cls(SelectedOptimizationProblem(mo_prob, i))
_decis, obj = meth.search()
for j, obj_val in enumerate(obj):
if obj_val < ideal[j]:
... | def estimate_payoff_table(
opt_meth_cls: Type[OptimizationMethod], mo_prob: MOProblem
) -> Tuple[List[float], List[float]] | Estimates the ideal and nadir by using a payoff table. This should give a
good estimate for the ideal, but can be very inaccurate for the nadir. For an explanation of why, see [DEB2010]_.
References
----------
.. [DEB2010] Deb, K., Miettinen, K., & Chaudhuri, S. (2010).
Toward an estimation of... | 3.054627 | 3.145763 | 0.971029 |
ideal, nadir = idnad
ideal_arr = np.array(ideal)
nadir_arr = np.array(nadir)
idnad_range = nadir_arr - ideal_arr
nadir_arr += pad_nadir * idnad_range
ideal_arr -= pad_ideal * idnad_range
return list(ideal_arr), list(nadir_arr) | def pad(idnad: Tuple[List[float], List[float]], pad_nadir=0.05, pad_ideal=0.0) | Pad an ideal/nadir estimate. This is mainly useful for padding the nadir
estimated by a payoff table for safety purposes. | 2.11663 | 2.04443 | 1.035315 |
ideal, nadir = idnad
mult = np.power(10, dp)
ideal_arr = np.floor(np.array(ideal) * mult) / mult
nadir_arr = np.ceil(np.array(nadir) * mult) / mult
return list(ideal_arr), list(nadir_arr) | def round_off(idnad: Tuple[List[float], List[float]], dp: int = 2) | Round off an ideal/nadir estimate e.g. so that it's looks nicer when
plotted. This function is careful to round so only ever move the values
away from the contained range. | 2.831025 | 2.435779 | 1.162267 |
return round_off(estimate_payoff_table(opt_meth, mo_prob), dp) | def default_estimate(
opt_meth: Type[OptimizationMethod], mo_prob: MOProblem, dp: int = 2
) -> Tuple[List[float], List[float]] | The recommended nadir/ideal estimator - use a payoff table and then round
off the result. | 12.076679 | 4.030322 | 2.996455 |
self._max = max
if max:
self._coeff = -1.0
else:
self._coeff = 1.0
return self._search(**params) | def search(self, max=False, **params) -> Tuple[np.ndarray, List[float]] | Search for the optimal solution
This sets up the search for the optimization and calls the _search method
Parameters
----------
max : bool (default False)
If true find mximum of the objective function instead of minimum
**params : dict [optional]
Parame... | 4.692195 | 5.382724 | 0.871714 |
if preference:
self.preference = preference
print(("Given preference: %s" % self.preference.pref_input))
self._update_fh()
# tmpzh = list(self.zh)
self._update_zh(self.zh, self.fh)
# self.zh = list(np.array(self.zh) / 2. + np.array(self.zh_prev) ... | def next_iteration(self, preference=None) | Return next iteration bounds | 6.364892 | 6.244725 | 1.019243 |
if bounds:
self.problem.points = reachable_points(
self.problem.points, self.problem.ideal, bounds
)
if not utils.isin(self.fh, self.problem.points) or ref_point != self.ref_point:
self.ref_point = list(ref_point)
self._update_fh()... | def next_iteration(self, ref_point, bounds=None) | Calculate the next iteration point to be shown to the DM
Parameters
----------
ref_point : list of float
Reference point given by the DM | 4.112988 | 4.380352 | 0.938963 |
for paragraph in paragraphs:
if paragraph.class_type == 'good':
if paragraph.heading:
tag = 'h'
else:
tag = 'p'
elif no_boilerplate:
continue
else:
tag = 'b'
print('<%s> %s' % (tag, cgi.escape(parag... | def output_default(paragraphs, fp=sys.stdout, no_boilerplate=True) | Outputs the paragraphs as:
<tag> text of the first paragraph
<tag> text of the second paragraph
...
where <tag> is <p>, <h> or <b> which indicates
standard paragraph, heading or boilerplate respecitvely. | 3.409804 | 3.253717 | 1.047972 |
for paragraph in paragraphs:
output = '<p class="%s" cfclass="%s" heading="%i" xpath="%s"> %s' % (
paragraph.class_type,
paragraph.cf_class,
int(paragraph.heading),
paragraph.xpath,
cgi.escape(paragraph.text)
)
print(output, fi... | def output_detailed(paragraphs, fp=sys.stdout) | Same as output_default, but only <p> tags are used and the following
attributes are added: class, cfclass and heading. | 4.876016 | 3.121975 | 1.561837 |
for paragraph in paragraphs:
if paragraph.class_type in ('good', 'neargood'):
if paragraph.heading:
cls = 2
else:
cls = 3
else:
cls = 1
for text_node in paragraph.text_nodes:
print('%i\t%s' % (cls, text_nod... | def output_krdwrd(paragraphs, fp=sys.stdout) | Outputs the paragraphs in a KrdWrd compatible format:
class<TAB>first text node
class<TAB>second text node
...
where class is 1, 2 or 3 which means
boilerplate, undecided or good respectively. Headings are output as
undecided. | 4.551466 | 3.517621 | 1.293904 |
if isinstance(html, unicode):
decoded_html = html
# encode HTML for case it's XML with encoding declaration
forced_encoding = encoding if encoding else default_encoding
html = html.encode(forced_encoding, errors)
else:
decoded_html = decode_html(html, default_encodin... | def html_to_dom(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS) | Converts HTML to DOM. | 3.709207 | 3.669468 | 1.01083 |
if isinstance(html, unicode):
return html
if encoding:
return html.decode(encoding, errors)
match = CHARSET_META_TAG_PATTERN.search(html)
if match:
declared_encoding = match.group(1).decode("ASCII")
# proceed unknown encoding as if it wasn't found at all
wi... | def decode_html(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS) | Converts a `html` containing an HTML page into Unicode.
Tries to guess character encoding from meta tag. | 4.410426 | 4.173917 | 1.056663 |
"Removes unwanted parts of DOM."
options = {
"processing_instructions": False,
"remove_unknown_tags": False,
"safe_attrs_only": False,
"page_structure": False,
"annoying_tags": False,
"frames": False,
"meta": False,
"links": False,
"javascr... | def preprocessor(dom) | Removes unwanted parts of DOM. | 4.175952 | 3.782643 | 1.103977 |
"Context-free paragraph classification."
stoplist = frozenset(w.lower() for w in stoplist)
for paragraph in paragraphs:
length = len(paragraph)
stopword_density = paragraph.stopwords_density(stoplist)
link_density = paragraph.links_density()
paragraph.heading = bool(not no_h... | def classify_paragraphs(paragraphs, stoplist, length_low=LENGTH_LOW_DEFAULT,
length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT,
stopwords_high=STOPWORDS_HIGH_DEFAULT, max_link_density=MAX_LINK_DENSITY_DEFAULT,
no_headings=NO_HEADINGS_DEFAULT) | Context-free paragraph classification. | 3.026245 | 2.999795 | 1.008817 |
return _get_neighbour(i, paragraphs, ignore_neargood, 1, len(paragraphs)) | def get_next_neighbour(i, paragraphs, ignore_neargood) | Return the class of the paragraph at the bottom end of the short/neargood
paragraphs block. If ignore_neargood is True, than only 'bad' or 'good'
can be returned, otherwise 'neargood' can be returned, too. | 3.937885 | 4.386343 | 0.89776 |
# copy classes
for paragraph in paragraphs:
paragraph.class_type = paragraph.cf_class
# good headings
for i, paragraph in enumerate(paragraphs):
if not (paragraph.heading and paragraph.class_type == 'short'):
continue
j = i + 1
distance = 0
while... | def revise_paragraph_classification(paragraphs, max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT) | Context-sensitive paragraph classification. Assumes that classify_pragraphs
has already been called. | 1.942046 | 1.944821 | 0.998573 |
dom = html_to_dom(html_text, default_encoding, encoding, enc_errors)
dom = preprocessor(dom)
paragraphs = ParagraphMaker.make_paragraphs(dom)
classify_paragraphs(paragraphs, stoplist, length_low, length_high,
stopwords_low, stopwords_high, max_link_density, no_headings)
revise_paragra... | def justext(html_text, stoplist, length_low=LENGTH_LOW_DEFAULT,
length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT,
stopwords_high=STOPWORDS_HIGH_DEFAULT, max_link_density=MAX_LINK_DENSITY_DEFAULT,
max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT, no_headings=NO_HEADINGS_DEFAU... | Converts an HTML page into a list of classified paragraphs. Each paragraph
is represented as instance of class ˙˙justext.paragraph.Paragraph˙˙. | 3.017656 | 2.919611 | 1.033582 |
handler = cls()
lxml.sax.saxify(root, handler)
return handler.paragraphs | def make_paragraphs(cls, root) | Converts DOM into paragraphs. | 6.814499 | 6.08469 | 1.119942 |
path_to_stoplists = os.path.dirname(sys.modules["justext"].__file__)
path_to_stoplists = os.path.join(path_to_stoplists, "stoplists")
stoplist_names = []
for filename in os.listdir(path_to_stoplists):
name, extension = os.path.splitext(filename)
if extension == ".txt":
... | def get_stoplists() | Returns a collection of built-in stop-lists. | 2.097574 | 2.005067 | 1.046137 |
file_path = os.path.join("stoplists", "%s.txt" % language)
try:
stopwords = pkgutil.get_data("justext", file_path)
except IOError:
raise ValueError(
"Stoplist for language '%s' is missing. "
"Please use function 'get_stoplists' for complete list of stoplists "
... | def get_stoplist(language) | Returns an built-in stop-list for the language as a set of words. | 4.281308 | 4.166738 | 1.027496 |
cache_key = '{0}:{1}:{2}:{3}'.format(
client,
region,
aws_access_key_id,
endpoint_url or ''
)
if not aws_session_token:
if cache_key in CLIENT_CACHE:
return CLIENT_CACHE[cache_key]
session = get_boto_session(
region,
aws_access_key... | def get_boto_client(
client,
region=None,
aws_access_key_id=None,
aws_secret_access_key=None,
aws_session_token=None,
endpoint_url=None
) | Get a boto3 client connection. | 2.08926 | 2.099365 | 0.995186 |
cache_key = '{0}:{1}:{2}:{3}'.format(
resource,
region,
aws_access_key_id,
endpoint_url or ''
)
if not aws_session_token:
if cache_key in RESOURCE_CACHE:
return RESOURCE_CACHE[cache_key]
session = get_boto_session(
region,
aws_acce... | def get_boto_resource(
resource,
region=None,
aws_access_key_id=None,
aws_secret_access_key=None,
aws_session_token=None,
endpoint_url=None
) | Get a boto resource connection. | 2.068955 | 2.094429 | 0.987837 |
return boto3.session.Session(
region_name=region,
aws_secret_access_key=aws_secret_access_key,
aws_access_key_id=aws_access_key_id,
aws_session_token=aws_session_token
) | def get_boto_session(
region,
aws_access_key_id=None,
aws_secret_access_key=None,
aws_session_token=None
) | Get a boto3 session. | 1.558026 | 1.555988 | 1.00131 |
if not isinstance(str_or_bytes, six.text_type):
return str_or_bytes.decode(encoding)
return str_or_bytes | def ensure_text(str_or_bytes, encoding='utf-8') | Ensures an input is a string, decoding if it is bytes. | 2.033696 | 1.869413 | 1.087879 |
if isinstance(str_or_bytes, six.text_type):
return str_or_bytes.encode(encoding, errors)
return str_or_bytes | def ensure_bytes(str_or_bytes, encoding='utf-8', errors='strict') | Ensures an input is bytes, encoding if it is a string. | 1.869762 | 1.744552 | 1.071772 |
'''
Find a key's alias by looking up its key_arn in the KEY_METADATA
cache. This function will only work after a key has been lookedup by
its alias and is meant as a convenience function for turning an ARN
that's already been looked up back into its alias.
'''
for... | def _get_key_alias_from_cache(self, key_arn) | Find a key's alias by looking up its key_arn in the KEY_METADATA
cache. This function will only work after a key has been lookedup by
its alias and is meant as a convenience function for turning an ARN
that's already been looked up back into its alias. | 7.482182 | 1.687894 | 4.43285 |
'''
Decrypt a token.
'''
version, user_type, _from = self._parse_username(username)
if (version > self.maximum_token_version or
version < self.minimum_token_version):
raise TokenValidationError('Unacceptable token version.')
try:
to... | def decrypt_token(self, username, token) | Decrypt a token. | 2.979894 | 2.967023 | 1.004338 |
_from = self.auth_context['from']
if self.token_version == 1:
return '{0}'.format(_from)
elif self.token_version == 2:
_user_type = self.auth_context['user_type']
return '{0}/{1}/{2}'.format(
self.token_version,
_user_t... | def get_username(self) | Get a username formatted for a specific token version. | 3.808836 | 2.987789 | 1.274801 |
# Generate string formatted timestamps for not_before and not_after,
# for the lifetime specified in minutes.
now = datetime.datetime.utcnow()
# Start the not_before time x minutes in the past, to avoid clock skew
# issues.
_not_before = now - datetime.timedelta(... | def get_token(self) | Get an authentication token. | 3.816371 | 3.765392 | 1.013539 |
key, value = arg.split("=")
if value.lower() == "true" or value.lower() == "false":
value = bool(value)
elif INT_RE.match(value):
value = int(value)
elif FLOAT_RE.match(value):
value = float(value)
return (key, value) | def dictstr(arg) | Parse a key=value string as a tuple (key, value) that can be provided as an argument to dict() | 2.145576 | 1.994171 | 1.075924 |
words = [dict(v, **dict([('sentence', i)]))
for i, s in enumerate(matches['sentences'])
for k, v in s.items() if k != 'length']
return words | def regex_matches_to_indexed_words(matches) | Transforms tokensregex and semgrex matches to indexed words.
:param matches: unprocessed regex matches
:return: flat array of indexed words | 5.988665 | 8.027411 | 0.746027 |
self.ensure_alive()
try:
input_format = properties.get("inputFormat", "text")
if input_format == "text":
ctype = "text/plain; charset=utf-8"
elif input_format == "serialized":
ctype = "application/x-protobuf"
else:... | def _request(self, buf, properties, date=None) | Send a request to the CoreNLP server.
:param (str | unicode) text: raw text for the CoreNLPServer to parse
:param (dict) properties: properties that the server expects
:param (str) date: reference date of document, used by server to set docDate - expects YYYY-MM-DD
:return: request resu... | 3.174983 | 2.917809 | 1.08814 |
# set properties for server call
if properties is None:
properties = self.default_properties
properties.update({
'annotators': ','.join(annotators or self.default_annotators),
'inputFormat': 'text',
'outputFormat': self.def... | def annotate(self, text, annotators=None, output_format=None, properties=None, date=None) | Send a request to the CoreNLP server.
:param (str | unicode) text: raw text for the CoreNLPServer to parse
:param (list | string) annotators: list of annotators to use
:param (str) output_format: output type from server: serialized, json, text, conll, conllu, or xml
:param (dict) proper... | 3.004758 | 2.799878 | 1.073175 |
self.ensure_alive()
if properties is None:
properties = self.default_properties
properties.update({
'annotators': ','.join(annotators or self.default_annotators),
'inputFormat': 'text',
'outputFormat': self.default_output_f... | def __regex(self, path, text, pattern, filter, annotators=None, properties=None) | Send a regex-related request to the CoreNLP server.
:param (str | unicode) path: the path for the regex endpoint
:param text: raw text for the CoreNLPServer to apply the regex
:param (str | unicode) pattern: regex pattern
:param (bool) filter: option to filter sentences that contain matc... | 3.469643 | 3.41029 | 1.017404 |
return {
"customAnnotatorClass.{}".format(self.name): "edu.stanford.nlp.pipeline.GenericWebServiceAnnotator",
"generic.endpoint": "http://{}:{}".format(self.host, self.port),
"generic.requires": ",".join(self.requires),
"generic.provides": ",".join(self.p... | def properties(self) | Defines a Java property to define this anntoator to CoreNLP. | 5.163545 | 3.933751 | 1.312626 |
httpd = HTTPServer((self.host, self.port), self._Handler)
sa = httpd.socket.getsockname()
serve_message = "Serving HTTP on {host} port {port} (http://{host}:{port}/) ..."
print(serve_message.format(host=sa[0], port=sa[1]))
try:
httpd.serve_forever()
e... | def run(self) | Runs the server using Python's simple HTTPServer.
TODO: make this multithreaded. | 1.934364 | 1.79222 | 1.079312 |
flags = _flag_transform(flags)
return _wcparse.translate(_wcparse.split(patterns, flags), flags) | def translate(patterns, *, flags=0) | Translate `fnmatch` pattern. | 12.921545 | 10.298353 | 1.25472 |
patterns = None
flags = self.flags
if pathname:
flags |= _wcparse.PATHNAME
if pattern:
patterns = _wcparse.WcSplit(pattern, flags=flags).split()
return _wcparse.compile(patterns, flags) if patterns else patterns | def _compile_wildcard(self, pattern, pathname=False) | Compile or format the wildcard inclusion/exclusion pattern. | 6.102576 | 5.809637 | 1.050423 |
if not isinstance(file_pattern, _wcparse.WcRegexp):
file_pattern = self._compile_wildcard(file_pattern, self.file_pathname)
if not isinstance(folder_exclude_pattern, _wcparse.WcRegexp):
folder_exclude_pattern = self._compile_wildcard(folder_exclude_pattern, self.dir_p... | def _compile(self, file_pattern, folder_exclude_pattern) | Compile patterns. | 3.122582 | 2.900066 | 1.076728 |
valid = False
fullpath = os.path.join(base, name)
if self.file_check is not None and self.compare_file(fullpath[self._base_len:] if self.file_pathname else name):
valid = True
if valid and (not self.show_hidden and util.is_hidden(fullpath)):
valid = Fals... | def _valid_file(self, base, name) | Return whether a file can be searched. | 5.508471 | 5.25042 | 1.049149 |
valid = True
fullpath = os.path.join(base, name)
if (
not self.recursive or
(
self.folder_exclude_check is not None and
not self.compare_directory(fullpath[self._base_len:] if self.dir_pathname else name)
)
):
... | def _valid_folder(self, base, name) | Return whether a folder can be searched. | 6.154159 | 5.759128 | 1.068592 |
return not self.folder_exclude_check.match(directory + self.sep if self.dir_pathname else directory) | def compare_directory(self, directory) | Compare folder. | 30.606281 | 26.354551 | 1.161328 |
self._base_len = len(self.base)
for base, dirs, files in os.walk(self.base, followlinks=self.follow_links):
# Remove child folders based on exclude rules
for name in dirs[:]:
try:
if not self._valid_folder(base, name):
... | def _walk(self) | Start search for valid files. | 2.896122 | 2.619707 | 1.105514 |
if flags & MINUSNEGATE:
return flags & NEGATE and pattern[0:1] in MINUS_NEGATIVE_SYM
else:
return flags & NEGATE and pattern[0:1] in NEGATIVE_SYM | def is_negative(pattern, flags) | Check if negative pattern. | 5.440042 | 5.001845 | 1.087607 |
if flags & BRACE:
for p in ([patterns] if isinstance(patterns, (str, bytes)) else patterns):
try:
yield from bracex.iexpand(p, keep_escapes=True)
except Exception: # pragma: no cover
# We will probably never hit this as `bracex`
... | def expand_braces(patterns, flags) | Expand braces. | 5.318059 | 5.107006 | 1.041326 |
if not bool(flags & CASE_FLAGS):
case_sensitive = util.is_case_sensitive()
elif flags & FORCECASE:
case_sensitive = True
else:
case_sensitive = False
return case_sensitive | def get_case(flags) | Parse flags for case sensitivity settings. | 5.614908 | 4.215503 | 1.331966 |
return (util.platform() != "windows" or (not bool(flags & REALPATH) and get_case(flags))) and not flags & _FORCEWIN | def is_unix_style(flags) | Check if we should use Unix style. | 30.55295 | 23.076723 | 1.323973 |
positive = []
negative = []
if isinstance(patterns, (str, bytes)):
patterns = [patterns]
flags |= _TRANSLATE
for pattern in patterns:
for expanded in expand_braces(pattern, flags):
(negative if is_negative(expanded, flags) else positive).append(
Wc... | def translate(patterns, flags) | Translate patterns. | 6.642194 | 6.539932 | 1.015636 |
if flags & SPLIT:
splitted = []
for pattern in ([patterns] if isinstance(patterns, (str, bytes)) else patterns):
splitted.extend(WcSplit(pattern, flags).split())
return splitted
else:
return patterns | def split(patterns, flags) | Split patterns. | 4.57996 | 4.499238 | 1.017941 |
patterns = [patterns]
for pattern in patterns:
for expanded in expand_braces(pattern, flags):
(negative if is_negative(expanded, flags) else positive).append(_compile(expanded, flags))
if patterns and flags & REALPATH and negative and not positive:
positive.append(_compile(... | def compile(patterns, flags): # noqa A001
positive = []
negative = []
if isinstance(patterns, (str, bytes)) | Compile patterns. | 5.882987 | 5.565105 | 1.057121 |
return re.compile(WcParse(pattern, flags & FLAG_MASK).parse()) | def _compile(pattern, flags) | Compile the pattern to regex. | 44.276672 | 32.899807 | 1.345803 |
matched = False
base = None
m = pattern.fullmatch(filename)
if m:
matched = True
# Lets look at the captured `globstar` groups and see if that part of the path
# contains symlinks.
if not follow:
groups = m.groups()
last = len(groups)
... | def _fs_match(pattern, filename, sep, follow, symlinks) | Match path against the pattern.
Since `globstar` doesn't match symlinks (unless `FOLLOW` is enabled), we must look for symlinks.
If we identify a symlink in a `globstar` match, we know this result should not actually match. | 3.598555 | 3.383675 | 1.063505 |
sep = '\\' if util.platform() == "windows" else '/'
if isinstance(filename, bytes):
sep = os.fsencode(sep)
if not filename.endswith(sep) and os.path.isdir(filename):
filename += sep
matched = False
for pattern in include:
if _fs_match(pattern, filename, sep, follow, sy... | def _match_real(filename, include, exclude, follow, symlinks) | Match real filename includes and excludes. | 2.660722 | 2.614005 | 1.017872 |
if real:
symlinks = {}
if isinstance(filename, bytes):
curdir = os.fsencode(os.curdir)
mount = RE_BWIN_MOUNT if util.platform() == "windows" else RE_BMOUNT
else:
curdir = os.curdir
mount = RE_WIN_MOUNT if util.platform() == "windows" else... | def _match_pattern(filename, include, exclude, real, path, follow) | Match includes and excludes. | 3.34347 | 3.318676 | 1.007471 |
c = next(i)
if c == '!':
c = next(i)
if c in ('^', '-', '['):
c = next(i)
while c != ']':
if c == '\\':
# Handle escapes
subindex = i.index
try:
self._references(i, True)
... | def _sequence(self, i) | Handle character group. | 5.677447 | 5.226519 | 1.086277 |
value = ''
c = next(i)
if c == '\\':
# \\
if sequence and self.bslash_abort:
raise PathNameException
value = c
elif c == '/':
# \/
if sequence:
raise PathNameException
i.rew... | def _references(self, i, sequence=False) | Handle references. | 7.032797 | 6.733582 | 1.044436 |
# Start list parsing
success = True
index = i.index
list_type = c
try:
c = next(i)
if c != '(':
raise StopIteration
while c != ')':
c = next(i)
if self.extend and c in EXT_TYPES and sel... | def parse_extend(self, c, i) | Parse extended pattern lists. | 4.053314 | 3.890528 | 1.041842 |
if l and value in (b'', ''):
return
globstar = value in (b'**', '**') and self.globstar
magic = self.is_magic(value)
if magic:
value = compile(value, self.flags)
l.append(WcGlob(value, magic, globstar, dir_only, False)) | def store(self, value, l, dir_only) | Group patterns by literals and potential magic patterns. | 8.501374 | 6.928762 | 1.226969 |
split_index = []
parts = []
start = -1
pattern = self.pattern.decode('latin-1') if self.is_bytes else self.pattern
i = util.StringIter(pattern)
iter(i)
# Detect and store away windows drive as a literal
if self.win_drive_detect:
m ... | def split(self) | Start parsing the pattern. | 2.958503 | 2.853337 | 1.036857 |
c = next(i)
if c == '\\':
# \\
if sequence and self.bslash_abort:
raise PathNameException
elif c == '/':
# \/
if sequence and self.pathname:
raise PathNameException
elif self.pathname:
... | def _references(self, i, sequence=False) | Handle references. | 7.148799 | 6.761359 | 1.057302 |
split_index = []
parts = []
pattern = self.pattern.decode('latin-1') if self.is_bytes else self.pattern
i = util.StringIter(pattern)
iter(i)
for c in i:
if self.extend and c in EXT_TYPES and self.parse_extend(c, i):
continue
... | def split(self) | Start parsing the pattern. | 3.248627 | 3.001119 | 1.082472 |
if self.dir_start and not self.after_start:
self.set_after_start()
elif not self.dir_start and self.after_start:
self.reset_dir_track() | def update_dir_state(self) | Update the directory state.
If we are at the directory start,
update to after start state (the character right after).
If at after start, reset state. | 4.867629 | 3.184394 | 1.528589 |
if self.pathname:
value = self.seq_path_dot if self.after_start and not self.dot else self.seq_path
if self.after_start:
value = self.no_dir + value
else:
value = _NO_DOT if self.after_start and not self.dot else ""
self.reset_dir_tra... | def _restrict_sequence(self) | Restrict sequence. | 9.823457 | 8.185353 | 1.200126 |
removed = False
first = result[-2]
v1 = ord(first[1:2] if len(first) > 1 else first)
v2 = ord(last[1:2] if len(last) > 1 else last)
if v2 < v1:
result.pop()
result.pop()
removed = True
else:
result.append(last)
... | def _sequence_range_check(self, result, last) | If range backwards, remove it.
A bad range will cause the regular expression to fail,
so we need to remove it, but return that we removed it
so the caller can know the sequence wasn't empty.
Caller will have to craft a sequence that makes sense
if empty at the end with either an... | 3.353859 | 2.997635 | 1.118835 |
last_posix = False
m = i.match(RE_POSIX)
if m:
last_posix = True
# Cannot do range with posix class
# so escape last `-` if we think this
# is the end of a range.
if end_range and i.index - 1 >= end_range:
resu... | def _handle_posix(self, i, result, end_range) | Handle posix classes. | 6.829758 | 6.399475 | 1.067237 |
result = ['[']
end_range = 0
escape_hyphen = -1
removed = False
last_posix = False
c = next(i)
if c in ('!', '^'):
# Handle negate char
result.append('^')
c = next(i)
if c == '[':
last_posix = self... | def _sequence(self, i) | Handle character group. | 4.255488 | 4.151525 | 1.025042 |
value = ''
c = next(i)
if c == '\\':
# \\
if sequence and self.bslash_abort:
raise PathNameException
value = r'\\'
if self.bslash_abort:
if not self.in_list:
value = self.get_path_sep() ... | def _references(self, i, sequence=False) | Handle references. | 5.324526 | 5.238581 | 1.016406 |
if self.pathname:
if self.after_start and not self.dot:
star = self.path_star_dot2
globstar = self.path_gstar_dot2
elif self.after_start:
star = self.path_star_dot1
globstar = self.path_gstar_dot1
else:... | def _handle_star(self, i, current) | Handle star. | 4.814002 | 4.790131 | 1.004983 |
if not self.inv_ext:
return
index = len(current) - 1
while index >= 0:
if isinstance(current[index], InvPlaceholder):
content = current[index + 1:]
content.append(_EOP if not self.pathname else self.path_eop)
curr... | def clean_up_inverse(self, current) | Clean up current.
Python doesn't have variable lookbehinds, so we have to do negative lookaheads.
!(...) when converted to regular expression is atomic, so once it matches, that's it.
So we use the pattern `(?:(?!(?:stuff|to|exclude)<x>))[^/]*?)` where <x> is everything
that comes after... | 8.4157 | 7.619852 | 1.104444 |
# Save state
temp_dir_start = self.dir_start
temp_after_start = self.after_start
temp_in_list = self.in_list
temp_inv_ext = self.inv_ext
self.in_list = True
if reset_dot:
self.allow_special_dir = False
# Start list parsing
su... | def parse_extend(self, c, i, current, reset_dot=False) | Parse extended pattern lists. | 3.900231 | 3.865463 | 1.008994 |
try:
if self.bslash_abort:
count = -1
c = '\\'
while c == '\\':
count += 1
c = next(i)
i.rewind(1)
# Rewind one more if we have an odd number (escape): \\\*
... | def consume_path_sep(self, i) | Consume any consecutive path separators are they count as one. | 5.305905 | 5.142587 | 1.031758 |
self.set_after_start()
i = util.StringIter(pattern)
iter(i)
root_specified = False
if self.win_drive_detect:
m = RE_WIN_PATH.match(pattern)
if m:
drive = m.group(0).replace('\\\\', '\\')
if drive.endswith('\\'):
... | def root(self, pattern, current) | Start parsing the pattern. | 3.51934 | 3.44413 | 1.021837 |
result = ['']
negative = False
p = util.norm_pattern(self.pattern, not self.unix, self.raw_chars)
p = p.decode('latin-1') if self.is_bytes else p
if is_negative(p, self.flags):
negative = True
p = p[1:]
self.root(p, result)
ca... | def parse(self) | Parse pattern list. | 4.514182 | 4.127253 | 1.09375 |
return _match_pattern(filename, self._include, self._exclude, self._real, self._path, self._follow) | def match(self, filename) | Match filename. | 12.308674 | 9.828152 | 1.252389 |
# Here we force `PATHNAME`.
flags = (flags & FLAG_MASK) | _wcparse.PATHNAME
if flags & _wcparse.REALPATH and util.platform() == "windows":
flags |= _wcparse._FORCEWIN
if flags & _wcparse.FORCECASE:
flags ^= _wcparse.FORCECASE
return flags | def _flag_transform(flags) | Transform flags to glob defaults. | 9.986062 | 8.83708 | 1.130018 |
return list(iglob(util.to_tuple(patterns), flags=flags)) | def glob(patterns, *, flags=0) | Glob. | 14.344366 | 13.912487 | 1.031043 |
flags = _flag_transform(flags)
if not _wcparse.is_unix_style(flags):
filename = util.norm_slash(filename)
return _wcparse.compile(_wcparse.split(patterns, flags), flags).match(filename) | def globmatch(filename, patterns, *, flags=0) | Check if filename matches pattern.
By default case sensitivity is determined by the file system,
but if `case_sensitive` is set, respect that instead. | 8.296803 | 8.478667 | 0.97855 |
matches = []
flags = _flag_transform(flags)
unix = _wcparse.is_unix_style(flags)
obj = _wcparse.compile(_wcparse.split(patterns, flags), flags)
for filename in filenames:
if not unix:
filename = util.norm_slash(filename)
if obj.match(filename):
matches... | def globfilter(filenames, patterns, *, flags=0) | Filter names using pattern. | 5.327823 | 5.100619 | 1.044544 |
pattern = util.norm_pattern(pattern, False, True)
return escape(pattern, unix) | def raw_escape(pattern, unix=False) | Apply raw character transform before applying escape. | 10.062846 | 9.096643 | 1.106215 |
is_bytes = isinstance(pattern, bytes)
replace = br'\\\1' if is_bytes else r'\\\1'
win = util.platform() == "windows"
if win and not unix:
magic = _wcparse.RE_BWIN_MAGIC if is_bytes else _wcparse.RE_WIN_MAGIC
else:
magic = _wcparse.RE_BMAGIC if is_bytes else _wcparse.RE_MAGIC
... | def escape(pattern, unix=False) | Escape. | 4.596177 | 4.521028 | 1.016622 |
self.pattern = []
self.npatterns = None
npattern = []
for p in pattern:
if _wcparse.is_negative(p, self.flags):
# Treat the inverse pattern as a normal pattern if it matches, we will exclude.
# This is faster as compiled patterns usua... | def _parse_patterns(self, pattern) | Parse patterns. | 6.566076 | 6.361019 | 1.032237 |
return _wcparse._match_real(
filename, patterns._include, patterns._exclude, patterns._follow, self.symlinks
) | def _match_excluded(self, filename, patterns) | Call match real directly to skip unnecessary `exists` check. | 21.344664 | 13.511268 | 1.579768 |
return self.npatterns and self._match_excluded(path, self.npatterns) | def _is_excluded(self, path, dir_only) | Check if file is excluded. | 17.370626 | 11.891631 | 1.460744 |
return a.lower() == b if not self.case_sensitive else a == b | def _match_literal(self, a, b=None) | Match two names. | 8.418046 | 6.645384 | 1.266751 |
if target is None:
matcher = None
elif isinstance(target, (str, bytes)):
# Plain text match
if not self.case_sensitive:
match = target.lower()
else:
match = target
matcher = functools.partial(self._matc... | def _get_matcher(self, target) | Get deep match. | 4.418445 | 4.1176 | 1.073063 |
scandir = self.current if not curdir else curdir
# Python will never return . or .., so fake it.
if os.path.isdir(scandir) and matcher is not None:
for special in self.specials:
if matcher(special):
yield os.path.join(curdir, special)
... | def _glob_dir(self, curdir, matcher, dir_only=False, deep=False) | Non recursive directory glob. | 2.731781 | 2.734186 | 0.99912 |
is_magic = this.is_magic
dir_only = this.dir_only
target = this.pattern
is_globstar = this.is_globstar
if is_magic and is_globstar:
# Glob star directory `**`.
# Throw away multiple consecutive `globstars`
# and acquire the pattern ... | def _glob(self, curdir, this, rest) | Handle glob flow.
There are really only a couple of cases:
- File name.
- File name pattern (magic).
- Directory.
- Directory name pattern (magic).
- Extra slashes `////`.
- `globstar` `**`. | 6.211942 | 6.137068 | 1.0122 |
results = [curdir]
if not self._is_parent(curdir) and not self._is_this(curdir):
fullpath = os.path.abspath(curdir)
basename = os.path.basename(fullpath)
dirname = os.path.dirname(fullpath)
if basename:
matcher = self._get_matche... | def _get_starting_paths(self, curdir) | Get the starting location.
For case sensitive paths, we have to "glob" for
it first as Python doesn't like for its users to
think about case. By scanning for it, we can get
the actual casing and then compare. | 3.643091 | 3.671759 | 0.992192 |
# Cached symlinks
self.symlinks = {}
if self.is_bytes:
curdir = os.fsencode(os.curdir)
else:
curdir = os.curdir
for pattern in self.pattern:
# If the pattern ends with `/` we return the files ending with `/`.
dir_only = ... | def glob(self) | Starts off the glob iterator. | 4.408545 | 4.326491 | 1.018966 |
if isinstance(name, str):
return name.replace('/', "\\") if not is_case_sensitive() else name
else:
return name.replace(b'/', b"\\") if not is_case_sensitive() else name | def norm_slash(name) | Normalize path slashes. | 4.162213 | 3.750817 | 1.109682 |
r
is_bytes = isinstance(pattern, bytes)
if not normalize and not is_raw_chars:
return pattern
def norm_char(token):
if normalize and token in ('/', b'/'):
token = br'\\' if is_bytes else r'\\'
return token
def norm(m):
if m.group(1)... | def norm_pattern(pattern, normalize, is_raw_chars) | r"""
Normalize pattern.
- For windows systems we want to normalize slashes to \.
- If raw string chars is enabled, we want to also convert
encoded string chars to literal characters.
- If `normalize` is enabled, take care to convert \/ to \\\\. | 2.6941 | 2.680076 | 1.005233 |
hidden = False
f = os.path.basename(path)
if f[:1] in ('.', b'.'):
# Count dot file as hidden on all systems
hidden = True
elif _PLATFORM == 'windows':
# On Windows, look for `FILE_ATTRIBUTE_HIDDEN`
FILE_ATTRIBUTE_HIDDEN = 0x2
if PY35:
results = ... | def is_hidden(path) | Check if file is hidden. | 3.30984 | 3.132251 | 1.056697 |
m = pattern.match(self._string, self._index)
if m:
self._index = m.end()
return m | def match(self, pattern) | Perform regex match at index. | 4.449226 | 3.44909 | 1.289971 |
try:
char = self._string[self._index]
self._index += 1
except IndexError: # pragma: no cover
raise StopIteration
return char | def iternext(self) | Iterate through characters of the string. | 4.335464 | 3.360385 | 1.290169 |
from wagtail.core.models import Page
# Empty slugs are ugly (eg. '-1' may be generated) so force non-empty
if not text:
text = 'no-title'
# use django slugify filter to slugify
slug = cautious_slugify(text)[:255]
values_list = Page.objects.filter(
slug__startswith=slug
... | def generate_slug(text, tail_number=0) | Returns a new unique slug. Object must provide a SlugField called slug.
URL friendly slugs are generated using django.template.defaultfilters'
slugify. Numbers are added to the end of slugs for uniqueness.
based on implementation in jmbo.utils
https://github.com/praekelt/jmbo/blob/develop/jmbo/utils/__... | 5.053955 | 5.05488 | 0.999817 |
'''
Update the Current Media Folder.
Returns list of files copied across or
raises an exception.
'''
temp_directory = tempfile.mkdtemp()
temp_file = tempfile.TemporaryFile()
# assumes the zip file contains a directory called media
temp_media_file = os.path.join(temp_directory, 'medi... | def update_media_file(upload_file) | Update the Current Media Folder.
Returns list of files copied across or
raises an exception. | 3.05987 | 2.386584 | 1.282113 |
'''
Returns an MD5 hash of the image file
Handles images stored locally and on AWS
I know this code is ugly.
Please don't ask.
The rabbit hole is deep.
'''
md5 = hashlib.md5()
try:
for chunk in image.file.chunks():
md5.update(chunk)
return md5.hexdigest(... | def get_image_hash(image) | Returns an MD5 hash of the image file
Handles images stored locally and on AWS
I know this code is ugly.
Please don't ask.
The rabbit hole is deep. | 4.26914 | 2.514291 | 1.69795 |
flat_fields = {}
nested_fields = {}
# exclude "id" and "meta" elements
for k, v in fields.items():
# TODO: remove dependence on KEYS_TO_INCLUDE
if k not in KEYS_TO_EXCLUDE:
if type(v) not in [type({}), type([])]:
flat_fields.update({k: v})
el... | def separate_fields(fields) | Non-foreign key fields can be mapped to new article instances
directly. Foreign key fields require a bit more work.
This method returns a tuple, of the same format:
(flat fields, nested fields) | 3.80811 | 3.537179 | 1.076595 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.