code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
log.debug("Deleting directory {!r}", directory)
shutil.rmtree(directory, onerror=shutil_rmtree_onerror) | def rmtree(directory: str) -> None | Deletes a directory tree. | 6.351424 | 4.718072 | 1.346191 |
for root, dirs, files in os.walk(path):
for x in dirs:
shutil.chown(os.path.join(root, x), user, group)
for x in files:
shutil.chown(os.path.join(root, x), user, group) | def chown_r(path: str, user: str, group: str) -> None | Performs a recursive ``chown``.
Args:
path: path to walk down
user: user name or ID
group: group name or ID
As per http://stackoverflow.com/questions/2853723 | 1.944352 | 1.857428 | 1.046798 |
os.chmod(root, permission)
for dirpath, dirnames, filenames in os.walk(root):
for d in dirnames:
os.chmod(os.path.join(dirpath, d), permission)
for f in filenames:
os.chmod(os.path.join(dirpath, f), permission) | def chmod_r(root: str, permission: int) -> None | Recursive ``chmod``.
Args:
root: directory to walk down
permission: e.g. ``e.g. stat.S_IWUSR`` | 1.694241 | 1.83374 | 0.923927 |
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result | def find(pattern: str, path: str) -> List[str] | Finds files in ``path`` whose filenames match ``pattern`` (via
:func:`fnmatch.fnmatch`). | 1.5968 | 1.729906 | 0.923056 |
try:
return find(pattern, path)[0]
except IndexError:
log.critical('''Couldn't find "{}" in "{}"''', pattern, path)
raise | def find_first(pattern: str, path: str) -> str | Finds first file in ``path`` whose filename matches ``pattern`` (via
:func:`fnmatch.fnmatch`), or raises :exc:`IndexError`. | 6.126519 | 5.787196 | 1.058633 |
for base_filename in starting_filenames:
if os.path.isfile(base_filename):
yield os.path.abspath(base_filename)
elif os.path.isdir(base_filename) and recursive:
for dirpath, dirnames, filenames in os.walk(base_filename):
for fname in filenames:
... | def gen_filenames(starting_filenames: List[str],
recursive: bool) -> Generator[str, None, None] | From a starting list of files and/or directories, generates filenames of
all files in the list, and (if ``recursive`` is set) all files within
directories in the list.
Args:
starting_filenames: files and/or directories
recursive: walk down any directories in the starting list, recursively?
... | 1.641215 | 1.923273 | 0.853345 |
exists = False
locked = None
file_object = None
if os.path.exists(filepath):
exists = True
locked = True
try:
buffer_size = 8
# Opening file in append mode and read the first 8 characters.
file_object = open(filepath, 'a', buffer_size)
... | def exists_locked(filepath: str) -> Tuple[bool, bool] | Checks if a file is locked by opening it in append mode.
(If no exception is thrown in that situation, then the file is not locked.)
Args:
filepath: file to check
Returns:
tuple: ``(exists, locked)``
See https://www.calazan.com/how-to-check-if-a-file-is-locked-in-python/. | 3.353969 | 3.243366 | 1.034101 |
filename = os.path.abspath(filename)
directory = os.path.abspath(directory)
if os.path.commonpath([directory, filename]) != directory:
# Filename is not within directory
return ""
return os.path.relpath(filename, start=directory) | def relative_filename_within_dir(filename: str, directory: str) -> str | Starting with a (typically absolute) ``filename``, returns the part of the
filename that is relative to the directory ``directory``.
If the file is *not* within the directory, returns an empty string. | 2.654837 | 2.528178 | 1.050099 |
errors = self.json.get('data').get('failures')
if errors:
logger.error(errors)
return errors | def _get_errors(self) | Gets errors from HTTP response | 8.020238 | 6.407059 | 1.251781 |
n_pages = calc_n_virtual_pages(n_sheets)
assert n_pages % 4 == 0
half_n_pages = n_pages // 2
firsthalf = list(range(half_n_pages))
secondhalf = list(reversed(range(half_n_pages, n_pages)))
# Seen from the top of an UNFOLDED booklet (e.g. a stack of paper that's
# come out of your printe... | def page_sequence(n_sheets: int, one_based: bool = True) -> List[int] | Generates the final page sequence from the starting number of sheets. | 4.243415 | 4.279198 | 0.991638 |
assert shutil.which(executable), "Need {!r} on the PATH.{}".format(
executable, "\n" + explanation if explanation else "") | def require(executable: str, explanation: str = "") -> None | Ensures that the external tool is available.
Asserts upon failure. | 8.572857 | 6.846371 | 1.252175 |
printable = " ".join(shlex.quote(x) for x in args).replace("\n", r"\n")
log.debug("Running external command: {}", printable)
if get_output:
p = subprocess.run(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, check=True)
stdout, stderr = p.stdout.decode(en... | def run(args: List[str],
get_output: bool = False,
encoding: str = sys.getdefaultencoding()) -> Tuple[str, str] | Run an external command +/- return the results.
Returns a ``(stdout, stderr)`` tuple (both are blank strings if the output
wasn't wanted). | 2.62897 | 2.412783 | 1.089601 |
log.debug("Getting page count for {!r}", filename)
require(PDFTK, HELP_MISSING_PDFTK)
stdout, _ = run([PDFTK, filename, "dump_data"], get_output=True)
regex = re.compile(r"^NumberOfPages: (\d+)$", re.MULTILINE)
m = regex.search(stdout)
if m:
return int(m.group(1))
raise ValueErr... | def get_page_count(filename: str) -> int | How many pages are in a PDF? | 4.755209 | 4.177189 | 1.138375 |
# https://unix.stackexchange.com/questions/277892/how-do-i-create-a-blank-pdf-from-the-command-line # noqa
require(CONVERT, HELP_MISSING_IMAGEMAGICK)
run([CONVERT, "xc:none", "-page", paper, filename]) | def make_blank_pdf(filename: str, paper: str = "A4") -> None | NOT USED.
Makes a blank single-page PDF, using ImageMagick's ``convert``. | 7.61046 | 6.805572 | 1.118269 |
if slice_horiz == 1 and slice_vert == 1:
log.debug("No slicing required")
return input_filename # nothing to do
log.info("Slicing each source page mv into {} horizontally x {} vertically",
slice_horiz, slice_vert)
log.debug("... from {!r} to {!r}", input_filename, output_f... | def slice_pdf(input_filename: str, output_filename: str,
slice_horiz: int, slice_vert: int) -> str | Slice each page of the original, to convert to "one real page per PDF
page". Return the output filename. | 4.478419 | 4.309785 | 1.039128 |
log.info("Creating booklet")
log.debug("... {!r} -> {!r}", input_filename, output_filename)
require(PDFJAM, HELP_MISSING_PDFJAM)
n_pages = get_page_count(input_filename)
n_sheets = calc_n_sheets(n_pages)
log.debug("{} pages => {} sheets", n_pages, n_sheets)
pagenums = page_sequence(n_sh... | def booklet_nup_pdf(input_filename: str, output_filename: str,
latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> str | Takes a PDF (e.g. A4) and makes a 2x1 booklet (e.g. 2xA5 per A4).
The booklet can be folded like a book and the final pages will be in order.
Returns the output filename. | 6.189331 | 5.822416 | 1.063018 |
log.info("Rotating even-numbered pages 180 degrees for long-edge "
"duplex printing")
log.debug("... {!r} -> {!r}", input_filename, output_filename)
require(PDFTK, HELP_MISSING_PDFTK)
args = [
PDFTK,
"A=" + input_filename, # give it handle 'A'
# handles are one... | def rotate_even_pages_180(input_filename: str, output_filename: str) -> str | Rotates even-numbered pages 180 degrees.
Returns the output filename. | 12.000261 | 10.648334 | 1.126961 |
if not os.path.isfile(input_filename):
log.warning("Input file does not exist or is not a file")
return False
if not overwrite and os.path.isfile(output_filename):
log.error("Output file exists; not authorized to overwrite (use "
"--overwrite if you are sure)")
... | def convert_to_foldable(input_filename: str,
output_filename: str,
slice_horiz: int,
slice_vert: int,
overwrite: bool = False,
longedge: bool = False,
latex_paper_size: str = L... | Runs a chain of tasks to convert a PDF to a useful booklet PDF. | 2.916879 | 2.741408 | 1.064008 |
main_only_quicksetup_rootlogger(level=logging.DEBUG)
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"input_file",
help="Input PDF (which is not modified by this program)")
parser.add_argument(
"outp... | def main() -> None | Command-line processor. See ``--help`` for details. | 3.865688 | 3.849531 | 1.004197 |
cmdargs = [
mysql,
"-h", host,
"-P", str(port),
"-e", "SHOW VARIABLES; SHOW STATUS",
"-u", user,
"-p" # prompt for password
]
log.info("Connecting to MySQL with user: {}", user)
log.debug(cmdargs)
process = subprocess.Popen(cmdargs, stdout=subpro... | def get_mysql_vars(mysql: str,
host: str,
port: int,
user: str) -> Dict[str, str] | Asks MySQL for its variables and status.
Args:
mysql: ``mysql`` executable filename
host: host name
port: TCP/IP port number
user: username
Returns:
dictionary of MySQL variables/values | 2.827263 | 2.815596 | 1.004144 |
try:
return "{:.3f}".format(int(valstr) / (1024 * 1024))
except (TypeError, ValueError):
return '?' | def val_mb(valstr: Union[int, str]) -> str | Converts a value in bytes (in string format) to megabytes. | 3.999186 | 2.820004 | 1.418149 |
valstr = vardict.get(varname, None)
table.add_row([varname, val_mb(valstr), UNITS_MB]) | def add_var_mb(table: PrettyTable,
vardict: Dict[str, str],
varname: str) -> None | Adds a row to ``table`` for ``varname``, in megabytes. | 8.060794 | 6.068183 | 1.32837 |
main_only_quicksetup_rootlogger(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument(
"--mysql", default="mysql",
help="MySQL program (default=mysql)")
parser.add_argument(
"--host", default="127.0.0.1",
help="MySQL server/host (prefer '127.0.0... | def main() | Command-line processor. See ``--help`` for details. | 1.811869 | 1.819631 | 0.995734 |
if show_inner_file:
print("{} [{}]".format(zipfilename, contentsfilename))
else:
print(zipfilename) | def report_hit_filename(zipfilename: str, contentsfilename: str,
show_inner_file: bool) -> None | For "hits": prints either the ``.zip`` filename, or the ``.zip`` filename
and the inner filename.
Args:
zipfilename: filename of the ``.zip`` file
contentsfilename: filename of the inner file
show_inner_file: if ``True``, show both; if ``False``, show just the
``.zip`` filen... | 3.98161 | 4.397768 | 0.905371 |
if show_inner_file:
print("{} [{}]: {}".format(zipfilename, contentsfilename, line))
else:
print("{}: {}".format(zipfilename, line)) | def report_line(zipfilename: str, contentsfilename: str, line: str,
show_inner_file: bool) -> None | Prints a line from a file, with the ``.zip`` filename and optionally also
the inner filename.
Args:
zipfilename: filename of the ``.zip`` file
contentsfilename: filename of the inner file
line: the line from the inner file
show_inner_file: if ``True``, show both filenames; if ``... | 2.971161 | 2.84118 | 1.045749 |
assert not (files_without_match and files_with_matches)
report_lines = (not files_without_match) and (not files_with_matches)
report_hit_lines = report_lines and not invert_match
report_miss_lines = report_lines and invert_match
log.debug("Checking ZIP: " + zipfilename)
found_in_zip = False... | def parse_zip(zipfilename: str,
regex: Pattern,
invert_match: bool,
files_with_matches: bool,
files_without_match: bool,
grep_inner_file_name: bool,
show_inner_file: bool) -> None | Implement a "grep within an OpenXML file" for a single OpenXML file, which
is by definition a ``.zip`` file.
Args:
zipfilename: name of the OpenXML (zip) file
regex: regular expression to match
invert_match: find files that do NOT match, instead of ones that do?
files_with_match... | 2.243067 | 2.299594 | 0.975419 |
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
description=
)
parser.add_argument(
"pattern",
help="Regular expression pattern to apply."
)
parser.add_argument(
"filename", nargs="*",
help="File(s) to check. You can also spe... | def main() -> None | Command-line handler for the ``grep_in_openxml`` tool.
Use the ``--help`` option for help. | 2.500958 | 2.479569 | 1.008626 |
def drug_timelines(
drug_events_df: DataFrame,
event_lasts_for: datetime.timedelta,
patient_colname: str = DEFAULT_PATIENT_COLNAME,
event_datetime_colname: str = DEFAULT_DRUG_EVENT_DATETIME_COLNAME) \
-> Dict[Any, IntervalList]:
sourcecolnum_pt = drug_events_df.co... | Takes a set of drug event start times (one or more per patient), plus a
fixed time that each event is presumed to last for, and returns an
:class:`IntervalList` for each patient representing the set of events
(which may overlap, in which case they will be amalgamated).
Args:
drug_events_d... | null | null | null | |
elems = self.find_elements_by_xpath(xpath)
if isinstance(elems, list) and len(elems) > 0:
return elems[0] | def find_element_by_xpath(self, xpath) | Finds an element by xpath.
:param xpath: The xpath locator of the element to find.
:return: ElemLxml
See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_ | 2.481417 | 2.832802 | 0.875958 |
from sdklib.html.elem import ElemLxml
elements = self.html_obj.xpath(xpath)
return [ElemLxml(e) for e in elements] | def find_elements_by_xpath(self, xpath) | Finds multiple elements by xpath.
:param xpath: The xpath locator of the elements to be found.
:return: list of ElemLxml
See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_ | 8.15164 | 6.965097 | 1.170355 |
from sdklib.html.elem import Elem5lib
return Elem5lib(self.html_obj.find(self._convert_xpath(xpath))) | def find_element_by_xpath(self, xpath) | Finds an element by xpath.
:param xpath: The xpath locator of the element to find.
:return:
See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ | 16.724636 | 17.419407 | 0.960115 |
from sdklib.html.elem import Elem5lib
return [Elem5lib(e) for e in self.html_obj.findall(self._convert_xpath(xpath))] | def find_elements_by_xpath(self, xpath) | Finds multiple elements by xpath.
:param xpath: The xpath locator of the elements to be found.
:return:
See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ | 12.942495 | 13.437236 | 0.963181 |
body_params = json.loads(context.text)
assert body_params == context.api_response.data, \
"Expected: {}; Message: {}".format(body_params, context.api_response.data) | def http_response_body_should_be_this_json(context) | Parameters:
.. code-block:: json
{
"param1": "value1",
"param2": "value2",
"param3": {
"param31": "value31"
}
} | 5.277435 | 5.046164 | 1.045831 |
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
ser = json.dumps(d)
if uids:
for uid in uids:
path = '/dq/%s/%s' % (uid, queue)
yield s... | def queue(self, queue, message, params={}, uids=[]) | Queue a job in Rhumba | 3.23579 | 3.271327 | 0.989137 |
servers = yield self.getClusterServers()
d = {
'workers': {},
'crons': {},
'queues': {}
}
now = time.time()
reverse_map = {}
for sname in servers:
last = yield self._get_key('/server/%s/heartbeat' % sname)
... | def clusterStatus(self) | Returns a dict of cluster nodes and their status information | 2.651378 | 2.663676 | 0.995383 |
# https://docs.pylonsproject.org/projects/deform/en/latest/widget.html#widget-requirements
js_resources = [] # type: List[str]
css_resources = [] # type: List[str]
for form in forms:
resources = form.get_widget_resources() # type: Dict[str, List[str]]
# Add, ignoring duplicates:
... | def get_head_form_html(req: "Request", forms: List[Form]) -> str | Returns the extra HTML that needs to be injected into the ``<head>``
section for a Deform form to work properly. | 2.244883 | 2.117317 | 1.060249 |
def _validate(node: SchemaNode, value: Any) -> None:
log.debug("Validating: {!r}", value)
try:
validator(node, value)
log.debug("... accepted")
except Invalid:
log.debug("... rejected")
raise
return _validate | def debug_validator(validator: ValidatorType) -> ValidatorType | Use as a wrapper around a validator, e.g.
.. code-block:: python
self.validator = debug_validator(OneOf(["some", "values"]))
If you do this, the log will show the thinking of the validator (what it's
trying to validate, and whether it accepted or rejected the value). | 4.426821 | 4.571698 | 0.96831 |
yield field
for c in field.children:
for f in gen_fields(c):
yield f | def gen_fields(field: Field) -> Generator[Field, None, None] | Starting with a Deform :class:`Field`, yield the field itself and any
children. | 2.842441 | 2.787012 | 1.019888 |
try:
return super().validate(controls, subcontrol)
except ValidationFailure as e:
if DEBUG_FORM_VALIDATION:
log.warning("Validation failure: {!r}; {}",
e, self._get_form_errors())
self._show_hidden_widgets_for_field... | def validate(self,
controls: Iterable[Tuple[str, str]],
subcontrol: str = None) -> Any | Validates the form.
Args:
controls: an iterable of ``(key, value)`` tuples
subcontrol:
Returns:
a Colander ``appstruct``
Raises:
ValidationFailure: on failure | 7.037918 | 6.979766 | 1.008331 |
self.slug = slugify(self.name)
self.uid = self.slug
super(DivisionLevel, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | **uid**: :code:`{levelcode}` | 4.559588 | 4.133696 | 1.103029 |
if isinstance(fnames, basestring):
fnames = [fnames]
fnames_expanded = [
os.path.expandvars(os.path.expanduser(fname)) for fname in fnames]
stream = StringIO()
try:
stats = pstats.Stats(fnames[0], stream=stream)
for fname in fnames_expanded[1:]:
stats.ad... | def get_pstats_print2list(fnames, filter_fnames=None, exclude_fnames=None,
sort=None, sort_reverse=None, limit=None) | Print stats with a filter or exclude filenames, sort index and limit.
:param list fnames: cProfile standard files to process.
:param list filter_fnames: Relative paths to filter and show them.
:param list exclude_fnames: Relative paths to avoid show them.
:param str sort: Standard `pstats` key of value ... | 2.736527 | 2.679237 | 1.021383 |
if not pstats:
return False
if pformat is None:
pformat = ("{method:<40s} {factor:>16s} {cumtime:>10s} "
"{calls:>10s} {rcalls:>10s} {tottime:>10s} "
"{tt_percall:>10s} {ct_percall:>10s} "
"<{file}:{lineno}")
for pstat_line in [di... | def print_pstats_list(pstats, pformat=None) | Print list of pstats dict formatted
:param list pstats: pstats dicts to print
:param str format: String.format style to show fields with keys:
ncalls, tottime, tt_percall, cumtime, ct_percall, file, lineno, method
rcalls, calls
:return: Directly print of result formatted and return True | 3.588988 | 2.938759 | 1.22126 |
self.metrics.extend(self._metrics.values())
del self._metrics | def merge_metrics(self) | Merge metrics in the internal _metrics dict to metrics list
and delete the internal _metrics | 9.457833 | 5.385525 | 1.756158 |
self.attributes.append(Attribute(name, value)) | def add_attribute(self, name, value) | :param name: Name of the attribute
:type name: string
:param value: Value of the attribute
:type value: string | 6.560601 | 5.366423 | 1.222528 |
self.tags.append(Tag(name, value)) | def add_tag(self, name, value) | :param name: Name of the tag
:type name: string
:param value: Value of the tag
:type value: string | 6.526452 | 5.434549 | 1.200919 |
if self.id is None and host is not None:
self.id = host
if self.name is None and host is not None:
self.name = host
if tags is not None:
Tags = []
for i in tags:
for k in i:
Tags.append(Tag(k, i[k]))
... | def add_sample(self,
metricId,
timestamp,
value,
metricType=None,
host=None,
sparseDataStrategy='None',
unit='',
tags=None,
min=None,
... | :param metricId: Metric FQN
:type metricId: string
:param timestamp: Timestamp for the sample
:type timestamp: int
:param value: Value of the sample
:type value: float
:param metricType: Metric Type
:type metricType: string
... | 2.47149 | 2.477913 | 0.997408 |
iterable = iter(iterable)
left = next(iterable)
for right in iterable:
yield left, right
left = right | def pairwise(iterable) | Pair each element with its neighbors.
Arguments
---------
iterable : iterable
Returns
-------
The generator produces a tuple containing a pairing of each element with
its neighbor. | 2.783563 | 4.8494 | 0.574001 |
pos, neg = [], []
pos_append, neg_append = pos.append, neg.append
for elem in iterable:
if pred(elem):
pos_append(elem)
else:
neg_append(elem)
return neg, pos | def partition(pred, iterable) | Partition an iterable.
Arguments
---------
pred : function
A function that takes an element of the iterable and returns
a boolen indicating to which partition it belongs
iterable : iterable
Returns
-------
A two-tuple of lists with the first list containin... | 2.155646 | 2.627376 | 0.820456 |
lst = list(iterable)
if reverse:
rng = range(len(lst), -1, -1)
else:
rng = range(len(lst) + 1)
return chain.from_iterable(combinations(lst, r) for r in rng) | def powerset(iterable, *, reverse=False) | Return the powerset.
Arguments
---------
iterable : iterable
reverse : boolean
Indicates whether the powerset should be returned descending by
size
Returns
-------
A generator producing each element of the powerset. | 2.322778 | 2.858763 | 0.812511 |
result = collections.defaultdict(list)
for rec in iterable:
result[key(rec)].append(rec)
return result if default_dict else dict(result) | def multi_map(key, iterable, *, default_dict=False) | Collect data into a multi-map.
Arguments
----------
key : function
A function that accepts an element retrieved from the
iterable and returns the key to be used in the multi-map
iterable : iterable
default_dict : boolean
Indicate... | 2.722066 | 3.481722 | 0.781816 |
result = []
result_append = result.append
if trailing:
for elem in iterable:
result_append(elem)
if pred(elem):
yield result
result = []
result_append = result.append
else:
for elem in iterable:
if p... | def split(pred, iterable, *, trailing=True) | Split the iterable.
Arguments
----------
pred : function
A function that accepts an element retrieved from the iterable
and returns a boolean indicating if it is the element on which
to split
iterable : iterable
trailing : boolean
Indi... | 1.881477 | 2.027439 | 0.928007 |
if length < 0:
return ()
iterable = iter(iterable)
result = tuple(islice(iterable, length))
while result:
yield result
result = tuple(islice(iterable, length)) | def chunk(iterable, length) | Collect data into chunks.
Arguments
---------
iterable : iterable
length : integer
Maximum size of each chunk to return
Returns
-------
The generator produces a tuple of elements whose size is at least one but
no more than *length*.
If the number of elements in th... | 2.353843 | 3.199901 | 0.735599 |
return []
data = list(iterable)
base, rem = divmod(len(data), n)
iterable = iter(data)
for i in range(n):
yield tuple(islice(iterable, base + 1 if i < rem else base)) | def divide(iterable, n): # pylint: disable=invalid-name
if n <= 0 | Evenly divide elements.
Arguments
---------
iterable : iterable
n : integer
The number of buckets in which to divide the elements
Returns
-------
The generator produces *n* tuples, each containing a number of elements
where the number is calculated to be evenly di... | 3.558245 | 3.864603 | 0.920727 |
return []
if count < 0:
return [0] * n
base, rem = divmod(count, n)
return [base + 1 if i < rem else base for i in range(n)] | def divide_sizes(count, n): # pylint: disable=invalid-name
if n <= 0 | Evenly divide a count.
Arguments
---------
count : integer
The number to be evenly divided
n : integer
The number of buckets in which to divide the number
Returns
-------
A list of integers indicating what size each bucket should be for an even
distribution ... | 3.164951 | 3.7882 | 0.835476 |
def node_children(node):
return list(node.get_children())
def print_node(node):
text = node.spelling or node.displayname
kind = str(node.kind).split('.')[1]
return '{} {}'.format(kind, text)
return draw_tree(cursor, node_children, print_node) | def dump(cursor) | Display the AST represented by the cursor | 4.679497 | 4.137649 | 1.130956 |
if not x: # None and blank string
return None
if isinstance(x, DateTime):
return x
tz = get_tz_local() if assume_local else get_tz_utc()
if isinstance(x, datetime.datetime):
return pendulum.instance(x, tz=tz) # (*)
elif isinstance(x, datetime.date):
# BEWARE: d... | def coerce_to_pendulum(x: PotentialDatetimeType,
assume_local: bool = False) -> Optional[DateTime] | Converts something to a :class:`pendulum.DateTime`.
Args:
x: something that may be coercible to a datetime
assume_local: if ``True``, assume local timezone; if ``False``, assume
UTC
Returns:
a :class:`pendulum.DateTime`, or ``None``.
Raises:
pendulum.parsing.ex... | 3.466854 | 3.562952 | 0.973028 |
p = coerce_to_pendulum(x, assume_local=assume_local)
return None if p is None else p.date() | def coerce_to_pendulum_date(x: PotentialDatetimeType,
assume_local: bool = False) -> Optional[Date] | Converts something to a :class:`pendulum.Date`.
Args:
x: something that may be coercible to a date
assume_local: if ``True``, assume local timezone; if ``False``, assume
UTC
Returns:
a :class:`pendulum.Date`, or ``None``.
Raises:
pendulum.parsing.exceptions.Par... | 2.775275 | 5.416877 | 0.512339 |
return datetime.datetime(
x.year, x.month, x.day,
x.hour, x.minute, x.second, x.microsecond,
tzinfo=x.tzinfo
) | def pendulum_to_datetime(x: DateTime) -> datetime.datetime | Used, for example, where a database backend insists on datetime.datetime.
Compare code in :meth:`pendulum.datetime.DateTime.int_timestamp`. | 2.193998 | 2.398369 | 0.914788 |
# noqa
pendulum_in_utc = pendulum.UTC.convert(x)
return pendulum_to_datetime_stripping_tz(pendulum_in_utc) | def pendulum_to_utc_datetime_without_tz(x: DateTime) -> datetime.datetime | Converts a Pendulum ``DateTime`` (which will have timezone information) to
a ``datetime.datetime`` that (a) has no timezone information, and (b) is
in UTC.
Example:
.. code-block:: python
import pendulum
from cardinal_pythonlib.datetimefunc import *
in_moscow = pendulum.parse(... | 4.482625 | 7.646382 | 0.586241 |
return datetime.date(year=x.year, month=x.month, day=x.day) | def pendulum_date_to_datetime_date(x: Date) -> datetime.date | Takes a :class:`pendulum.Date` and returns a :class:`datetime.date`.
Used, for example, where a database backend insists on
:class:`datetime.date`. | 2.920718 | 2.947777 | 0.990821 |
return datetime.time(
hour=x.hour, minute=x.minute, second=x.second,
microsecond=x.microsecond,
tzinfo=x.tzinfo
) | def pendulum_time_to_datetime_time(x: Time) -> datetime.time | Takes a :class:`pendulum.Time` and returns a :class:`datetime.time`.
Used, for example, where a database backend insists on
:class:`datetime.time`. | 2.432487 | 2.303136 | 1.056163 |
d = coerce_to_pendulum(d)
if d is None:
return default
return d.strftime(fmt) | def format_datetime(d: PotentialDatetimeType,
fmt: str,
default: str = None) -> Optional[str] | Format a datetime with a ``strftime`` format specification string, or
return ``default`` if the input is ``None``. | 4.288763 | 4.593601 | 0.933639 |
# noqa
# Convert tdelta to integer seconds.
if inputtype == 'timedelta':
remainder = int(tdelta.total_seconds())
elif inputtype in ['s', 'seconds']:
remainder = int(tdelta)
elif inputtype in ['m', 'minutes']:
remainder = int(tdelta) * 60
elif inputtype in ['h', 'hours'... | def strfdelta(tdelta: Union[datetime.timedelta, int, float, str],
fmt='{D:02}d {H:02}h {M:02}m {S:02}s',
inputtype='timedelta') | Convert a ``datetime.timedelta`` object or a regular number to a custom-
formatted string, just like the ``strftime()`` method does for
``datetime.datetime`` objects.
The ``fmt`` argument allows custom formatting to be specified. Fields can
include ``seconds``, ``minutes``, ``hours``, ``days``, and ``w... | 1.975113 | 1.862277 | 1.06059 |
dt = coerce_to_pendulum(dt)
tz = get_tz_utc()
return dt.in_tz(tz) | def convert_datetime_to_utc(dt: PotentialDatetimeType) -> DateTime | Convert date/time with timezone to UTC (with UTC timezone). | 5.738879 | 5.049009 | 1.136635 |
dt = coerce_to_pendulum(dt)
tz = get_tz_local()
return dt.in_tz(tz) | def convert_datetime_to_local(dt: PotentialDatetimeType) -> DateTime | Convert date/time with timezone to local timezone. | 5.35629 | 4.597127 | 1.165139 |
start = coerce_to_pendulum(start)
end = coerce_to_pendulum(end)
if start is None or end is None:
return default
duration = end - start
minutes = duration.in_minutes()
(hours, minutes) = divmod(minutes, 60)
if hours < 0:
# negative... trickier
# Python's divmod do... | def get_duration_h_m(start: Union[str, DateTime],
end: Union[str, DateTime],
default: str = "N/A") -> str | Calculate the time between two dates/times expressed as strings.
Args:
start: start date/time
end: end date/time
default: string value to return in case either of the inputs is
``None``
Returns:
a string that is one of
.. code-block:
'hh:mm'
... | 3.37182 | 3.594807 | 0.93797 |
dob = coerce_to_pendulum_date(dob)
when = coerce_to_pendulum_date(when)
if dob is None or when is None:
return default
return (when - dob).years | def get_age(dob: PotentialDatetimeType,
when: PotentialDatetimeType,
default: str = "") -> Union[int, str] | Age (in whole years) at a particular date, or ``default``.
Args:
dob: date of birth
when: date/time at which to calculate age
default: value to return if either input is ``None``
Returns:
age in whole years (rounded down), or ``default`` | 2.638815 | 3.692321 | 0.714677 |
if dt is None:
return None
return dt.replace(day=1) | def truncate_date_to_first_of_month(
dt: Optional[DateLikeType]) -> Optional[DateLikeType] | Change the day to the first of the month. | 3.726897 | 3.00944 | 1.238402 |
now = datetime.datetime.utcnow()
return now.replace(tzinfo=None) | def get_now_utc_notz_datetime() -> datetime.datetime | Get the UTC time now, but with no timezone information,
in :class:`datetime.datetime` format. | 4.071733 | 3.659718 | 1.112581 |
if x is None:
return None
elif isinstance(x, DateTime):
return pendulum_to_datetime(x)
elif isinstance(x, datetime.datetime):
return x
elif isinstance(x, datetime.date):
return datetime.datetime(x.year, x.month, x.day)
else:
return dateutil.parser.parse(x... | def coerce_to_datetime(x: Any) -> Optional[datetime.datetime] | Ensure an object is a :class:`datetime.datetime`, or coerce to one, or
raise :exc:`ValueError` or :exc:`OverflowError` (as per
http://dateutil.readthedocs.org/en/latest/parser.html). | 2.129783 | 2.318281 | 0.91869 |
new_context = copy.deepcopy(context)
assert new_context.method in ALLOWED_METHODS
new_context.url_path = generate_url_path(
new_context.url_path,
prefix=new_context.prefix_url_path,
format_suffix=new_context.url_path_format,
**new_context.url_path_params
)
if n... | def request_from_context(context) | Do http requests from context.
:param context: request context. | 2.637828 | 2.667753 | 0.988783 |
for field in self.fields_to_clear + list(args):
setattr(self, field, None) | def clear(self, *args) | Set default values to **self.fields_to_clear**. In addition, it is possible to pass extra fields to clear.
:param args: extra fields to clear. | 7.647638 | 3.814021 | 2.005138 |
scheme, host, port = get_hostname_parameters_from_url(value)
self._host = "%s://%s:%s" % (scheme, host, port) | def host(self, value) | A string that will be automatically included at the beginning of the url generated for doing each http request.
:param value: The host to be connected with, e.g. (http://hostname) or (https://X.X.X.X:port) | 5.262775 | 5.722972 | 0.919588 |
if value and not value.is_empty():
self._cookie = value
else:
self._cookie = Cookie() | def cookie(self, value) | Set cookie.
:param value: | 4.793908 | 6.31063 | 0.759656 |
if value is None:
cls.DEFAULT_HOST = "http://127.0.0.1:80"
else:
scheme, host, port = get_hostname_parameters_from_url(value)
cls.DEFAULT_HOST = "%s://%s:%s" % (scheme, host, port) | def set_default_host(cls, value) | Default: "http://127.0.0.1:80"
A string that will be automatically included at the beginning of the url generated for doing each http request. | 2.989019 | 2.588065 | 1.154924 |
if value is None:
cls.DEFAULT_PROXY = None
else:
scheme, host, port = get_hostname_parameters_from_url(value)
cls.DEFAULT_PROXY = "%s://%s:%s" % (scheme, host, port) | def set_default_proxy(cls, value) | Default: None (no proxy)
A string that will be used to tell each request must be sent through this proxy server.
Use the scheme://hostname:port form.
If you need to use a proxy, you can configure individual requests with the proxies argument to any request
method. | 3.099793 | 3.028595 | 1.023509 |
host = kwargs.get('host', self.host)
proxy = kwargs.get('proxy', self.proxy)
renderer = kwargs.get('renderer', MultiPartRenderer() if files else self.default_renderer)
prefix_url_path = kwargs.get('prefix_url_path', self.prefix_url_path)
authentication_instances = kwargs... | def _http_request(self, method, url_path, headers=None, query_params=None, body_params=None, files=None, **kwargs) | Method to do http requests.
:param method:
:param url_path:
:param headers:
:param body_params:
:param query_params:
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart
encoding upload.
... | 2.26858 | 2.201571 | 1.030437 |
assert self.LOGIN_URL_PATH is not None
render_name = kwargs.pop("render", "json")
render = get_renderer(render_name)
params = parse_args(**kwargs)
return self.post(self.LOGIN_URL_PATH, body_params=params, render=render) | def login(self, **kwargs) | Login abstract method with default implementation.
:param kwargs: parameters
:return: SdkResponse | 5.997965 | 5.358333 | 1.119371 |
if len(ninedigits) != 9 or not all(str(x).isdigit() for x in ninedigits):
raise ValueError("bad string to nhs_check_digit")
check_digit = 11 - (sum([
int(d) * f
for (d, f) in zip(ninedigits, NHS_DIGIT_WEIGHTINGS)
]) % 11)
# ... % 11 yields something in the range 0-10
# .... | def nhs_check_digit(ninedigits: Union[str, List[Union[str, int]]]) -> int | Calculates an NHS number check digit.
Args:
ninedigits: string or list
Returns:
check digit
Method:
1. Multiply each of the first nine digits by the corresponding
digit weighting (see :const:`NHS_DIGIT_WEIGHTINGS`).
2. Sum the results.
3. Take remainder after division ... | 3.679554 | 3.057072 | 1.20362 |
# noqa
if not isinstance(n, int):
log.debug("is_valid_nhs_number: parameter was not of integer type")
return False
s = str(n)
# Not 10 digits long?
if len(s) != 10:
log.debug("is_valid_nhs_number: not 10 digits")
return False
main_digits = [int(s[i]) for i in ... | def is_valid_nhs_number(n: int) -> bool | Validates an integer as an NHS number.
Args:
n: NHS number
Returns:
valid?
Checksum details are at
http://www.datadictionary.nhs.uk/version2/data_dictionary/data_field_notes/n/nhs_number_de.asp | 2.572811 | 2.606026 | 0.987254 |
check_digit = 10 # NHS numbers with this check digit are all invalid
while check_digit == 10:
digits = [random.randint(1, 9)] # don't start with a zero
digits.extend([random.randint(0, 9) for _ in range(8)])
# ... length now 9
check_digit = nhs_check_digit(digits)
# no... | def generate_random_nhs_number() -> int | Returns a random valid NHS number, as an ``int``. | 4.07279 | 3.767198 | 1.081119 |
if len(first9digits) != 9:
log.warning("Not 9 digits")
return None
try:
first9int = int(first9digits)
except (TypeError, ValueError):
log.warning("Not an integer")
return None # not an int
if len(str(first9int)) != len(first9digits):
# e.g. leading z... | def generate_nhs_number_from_first_9_digits(first9digits: str) -> Optional[int] | Returns a valid NHS number, as an ``int``, given the first 9 digits.
The particular purpose is to make NHS numbers that *look* fake (rather
than truly random NHS numbers which might accidentally be real).
For example:
.. code-block:: none
123456789_ : no; checksum 10
987654321_ : yes,... | 3.054693 | 3.316918 | 0.920943 |
# noqa
# None in, None out.
funcname = "nhs_number_from_text_or_none: "
if not s:
log.debug(funcname + "incoming parameter was None")
return None
# (a) If it's not a 10-digit number, bye-bye.
# Remove whitespace
s = WHITESPACE_REGEX.sub("", s) # replaces all instances
... | def nhs_number_from_text_or_none(s: str) -> Optional[int] | Returns a validated NHS number (as an integer) from a string, or ``None``
if it is not valid.
It's a 10-digit number, so note that database 32-bit INT values are
insufficient; use BIGINT. Python will handle large integers happily.
NHS number rules:
http://www.datadictionary.nhs.uk/... | 3.52765 | 3.704711 | 0.952206 |
assert bool(msg) != bool(msg_string), "Specify either msg or msg_string"
# Connect
try:
session = smtplib.SMTP(host, port)
except smtplib.SMTPException as e:
raise RuntimeError(
"send_msg: Failed to connect to host {}, port {}: {}".format(
host, port, e))... | def send_msg(from_addr: str,
to_addrs: Union[str, List[str]],
host: str,
user: str,
password: str,
port: int = None,
use_tls: bool = True,
msg: email.mime.multipart.MIMEMultipart = None,
msg_string: str = None) -> No... | Sends a pre-built e-mail message.
Args:
from_addr: e-mail address for 'From:' field
to_addrs: address or list of addresses to transmit to
host: mail server host
user: username on mail server
password: password for username on mail server
port: port to use, or ``None... | 2.361304 | 2.41833 | 0.976419 |
logging.basicConfig()
log.setLevel(logging.DEBUG)
parser = argparse.ArgumentParser(
description="Send an e-mail from the command line.")
parser.add_argument("sender", action="store",
help="Sender's e-mail address")
parser.add_argument("host", action="store",
... | def main() -> None | Command-line processor. See ``--help`` for details. | 1.960594 | 1.925409 | 1.018274 |
idx = clang.cindex.Index.create()
tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs)
return _ensure_parse_valid(tu) | def parse_string(contents, name='tmp.cpp', **kwargs) | Parse a string of C/C++ code | 4.424721 | 4.589383 | 0.964121 |
idx = clang.cindex.Index.create()
assert os.path.exists(name)
tu = idx.parse(name, **kwargs)
return _ensure_parse_valid(tu) | def parse(name, **kwargs) | Parse a C/C++ file | 5.832592 | 5.202093 | 1.121201 |
if not value:
return []
return [x.strip() for x in value.split(",")] | def ip_addresses_from_xff(value: str) -> List[str] | Returns a list of IP addresses (as strings), given the value of an HTTP
``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header.
Args:
value:
the value of an HTTP ``X-Forwarded-For`` (or ``WSGI
HTTP_X_FORWARDED_FOR``) header
Returns:
a list of IP address as st... | 3.55565 | 5.208611 | 0.682648 |
return any([
self.trusted_proxy_headers,
self.http_host,
self.remote_addr,
self.script_name,
self.server_name,
self.server_port,
self.url_scheme,
self.rewrite_path_info,
]) | def necessary(self) -> bool | Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config? | 4.729004 | 3.619877 | 1.306399 |
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid in uids:
yield self.client.lpush('rhumba.dq.%s.%s' % (
uid, queue), json.dumps(d))
... | def queue(self, queue, message, params={}, uids=[]) | Queue a job in Rhumba | 3.345068 | 2.922189 | 1.144713 |
if suid:
r = yield self.client.get('rhumba.dq.%s.%s.%s' % (suid, queue, uid))
else:
r = yield self.client.get('rhumba.q.%s.%s' % (queue, uid))
if r:
defer.returnValue(json.loads(r))
else:
defer.returnValue(None) | def getResult(self, queue, uid, suid=None) | Retrieve the result of a job from its ID | 3.10605 | 3.229885 | 0.96166 |
servers = yield self.client.keys('rhumba.server.*.heartbeat')
d = {}
now = time.time()
for s in servers:
sname = s.split('.', 2)[-1].rsplit('.', 1)[0]
last = yield self.client.get('rhumba.server.%s.heartbeat' % sname)
... | def clusterStatus(self) | Returns a dict of cluster nodes and their status information | 3.217617 | 3.219169 | 0.999518 |
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid in uids:
self._get_client().lpush('rhumba.dq.%s.%s' % (
uid, queue), json.dumps(d))
... | def queue(self, queue, message, params={}, uids=[]) | Queue a job in Rhumba | 3.235571 | 2.816569 | 1.148763 |
if suid:
r = self._get_client().get('rhumba.dq.%s.%s.%s' % (suid, queue, uid))
else:
r = self._get_client().get('rhumba.q.%s.%s' % (queue, uid))
if r:
return json.loads(r)
else:
return None | def getResult(self, queue, uid, suid=None) | Retrieve the result of a job from its ID | 3.400696 | 3.532227 | 0.962763 |
c = self._get_client()
servers = c.keys('rhumba.server.*.heartbeat')
d = {}
now = time.time()
for s in servers:
sname = s.split('.', 2)[-1].rsplit('.', 1)[0]
last = float(c.get('rhumba.server.%s.heartbeat' % sname))
status ... | def clusterStatus(self) | Returns a dict of cluster nodes and their status information | 3.427585 | 3.374121 | 1.015846 |
proc_out = subprocess.run(
['geo2topo'],
input=bytes(
json.dumps(geojson),
'utf-8'),
stdout=subprocess.PIPE
)
proc_out = subprocess.run(
['toposimplify', '-P', p],
input=proc_out.stdout,
... | def toposimplify(geojson, p) | Convert geojson and simplify topology.
geojson is a dict representing geojson.
p is a simplification threshold value between 0 and 1. | 3.371616 | 3.530983 | 0.954866 |
assert is_sqlserver(engine), (
"Only call get_sqlserver_product_version() for Microsoft SQL Server "
"instances."
)
sql = "SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)"
rp = engine.execute(sql) # type: ResultProxy
row = rp.fetchone()
dotted_version = row[0] # t... | def get_sqlserver_product_version(engine: "Engine") -> Tuple[int] | Gets SQL Server version information.
Attempted to use ``dialect.server_version_info``:
.. code-block:: python
from sqlalchemy import create_engine
url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME"
engine = create_engine(url)
dialect = engine.dialect
vi = dialect.server_v... | 3.637259 | 3.631901 | 1.001475 |
if not is_sqlserver(engine):
return False
version_tuple = get_sqlserver_product_version(engine)
return version_tuple >= (SQLSERVER_MAJOR_VERSION_2008, ) | def is_sqlserver_2008_or_later(engine: "Engine") -> bool | Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server,
version 2008 or later? | 4.523152 | 3.696424 | 1.223656 |
arr = N.ones((a.shape[0],a.shape[1]+1))
arr[:,:-1] = a
return arr | def add_ones(a) | Adds a column of 1s at the end of the array | 3.481784 | 3.553413 | 0.979842 |
if cls._hook:
sys.meta_path.remove(cls._hook)
cls._hook = None | def _uninstall(cls) | uninstall the hook if installed | 4.845697 | 2.904413 | 1.668391 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.