repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
openstax/cnx-archive | cnxarchive/sitemap.py | SitemapIndex.to_string | def to_string(self):
"""Convert SitemapIndex into a string."""
root = etree.Element('sitemapindex', nsmap={None: SITEMAP_NS})
for sitemap in self.sitemaps:
sm = etree.SubElement(root, 'sitemap')
etree.SubElement(sm, 'loc').text = sitemap.url
if hasattr(sitemap... | python | def to_string(self):
"""Convert SitemapIndex into a string."""
root = etree.Element('sitemapindex', nsmap={None: SITEMAP_NS})
for sitemap in self.sitemaps:
sm = etree.SubElement(root, 'sitemap')
etree.SubElement(sm, 'loc').text = sitemap.url
if hasattr(sitemap... | [
"def",
"to_string",
"(",
"self",
")",
":",
"root",
"=",
"etree",
".",
"Element",
"(",
"'sitemapindex'",
",",
"nsmap",
"=",
"{",
"None",
":",
"SITEMAP_NS",
"}",
")",
"for",
"sitemap",
"in",
"self",
".",
"sitemaps",
":",
"sm",
"=",
"etree",
".",
"SubEl... | Convert SitemapIndex into a string. | [
"Convert",
"SitemapIndex",
"into",
"a",
"string",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/sitemap.py#L37-L49 |
openstax/cnx-archive | cnxarchive/sitemap.py | Sitemap.add_url | def add_url(self, *args, **kwargs):
"""Add a new url to the sitemap.
This function can either be called with a :class:`UrlEntry`
or some keyword and positional arguments that are forwarded to
the :class:`UrlEntry` constructor.
"""
if len(args) == 1 and not kwargs and isi... | python | def add_url(self, *args, **kwargs):
"""Add a new url to the sitemap.
This function can either be called with a :class:`UrlEntry`
or some keyword and positional arguments that are forwarded to
the :class:`UrlEntry` constructor.
"""
if len(args) == 1 and not kwargs and isi... | [
"def",
"add_url",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"not",
"kwargs",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"UrlEntry",
")",
":",
"self",
".",
"urls... | Add a new url to the sitemap.
This function can either be called with a :class:`UrlEntry`
or some keyword and positional arguments that are forwarded to
the :class:`UrlEntry` constructor. | [
"Add",
"a",
"new",
"url",
"to",
"the",
"sitemap",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/sitemap.py#L74-L84 |
openstax/cnx-archive | cnxarchive/sitemap.py | Sitemap.to_string | def to_string(self):
"""Convert the sitemap into a string."""
root = etree.Element('urlset', nsmap={None: SITEMAP_NS})
for url in self.urls:
url.generate(root)
return etree.tostring(root, pretty_print=True, xml_declaration=True,
encoding='utf-8') | python | def to_string(self):
"""Convert the sitemap into a string."""
root = etree.Element('urlset', nsmap={None: SITEMAP_NS})
for url in self.urls:
url.generate(root)
return etree.tostring(root, pretty_print=True, xml_declaration=True,
encoding='utf-8') | [
"def",
"to_string",
"(",
"self",
")",
":",
"root",
"=",
"etree",
".",
"Element",
"(",
"'urlset'",
",",
"nsmap",
"=",
"{",
"None",
":",
"SITEMAP_NS",
"}",
")",
"for",
"url",
"in",
"self",
".",
"urls",
":",
"url",
".",
"generate",
"(",
"root",
")",
... | Convert the sitemap into a string. | [
"Convert",
"the",
"sitemap",
"into",
"a",
"string",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/sitemap.py#L93-L99 |
openstax/cnx-archive | cnxarchive/sitemap.py | UrlEntry.generate | def generate(self, root_element=None):
"""Create <url> element under root_element."""
if root_element is not None:
url = etree.SubElement(root_element, 'url')
else:
url = etree.Element('url')
etree.SubElement(url, 'loc').text = self.loc
if self.lastmod:
... | python | def generate(self, root_element=None):
"""Create <url> element under root_element."""
if root_element is not None:
url = etree.SubElement(root_element, 'url')
else:
url = etree.Element('url')
etree.SubElement(url, 'loc').text = self.loc
if self.lastmod:
... | [
"def",
"generate",
"(",
"self",
",",
"root_element",
"=",
"None",
")",
":",
"if",
"root_element",
"is",
"not",
"None",
":",
"url",
"=",
"etree",
".",
"SubElement",
"(",
"root_element",
",",
"'url'",
")",
"else",
":",
"url",
"=",
"etree",
".",
"Element"... | Create <url> element under root_element. | [
"Create",
"<url",
">",
"element",
"under",
"root_element",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/sitemap.py#L153-L170 |
xenon-middleware/pyxenon | examples/interactive.py | make_input_stream | def make_input_stream():
"""Creates a :py:class:`Queue` object and a co-routine yielding from that
queue. The queue should be populated with 2-tuples of the form `(command,
message)`, where `command` is one of [`msg`, `end`].
When the `end` command is recieved, the co-routine returns, ending the
st... | python | def make_input_stream():
"""Creates a :py:class:`Queue` object and a co-routine yielding from that
queue. The queue should be populated with 2-tuples of the form `(command,
message)`, where `command` is one of [`msg`, `end`].
When the `end` command is recieved, the co-routine returns, ending the
st... | [
"def",
"make_input_stream",
"(",
")",
":",
"input_queue",
"=",
"Queue",
"(",
")",
"def",
"input_stream",
"(",
")",
":",
"while",
"True",
":",
"cmd",
",",
"msg",
"=",
"input_queue",
".",
"get",
"(",
")",
"if",
"cmd",
"==",
"'end'",
":",
"input_queue",
... | Creates a :py:class:`Queue` object and a co-routine yielding from that
queue. The queue should be populated with 2-tuples of the form `(command,
message)`, where `command` is one of [`msg`, `end`].
When the `end` command is recieved, the co-routine returns, ending the
stream.
When a `msg` command ... | [
"Creates",
"a",
":",
"py",
":",
"class",
":",
"Queue",
"object",
"and",
"a",
"co",
"-",
"routine",
"yielding",
"from",
"that",
"queue",
".",
"The",
"queue",
"should",
"be",
"populated",
"with",
"2",
"-",
"tuples",
"of",
"the",
"form",
"(",
"command",
... | train | https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/examples/interactive.py#L6-L30 |
openstax/cnx-archive | cnxarchive/views/sitemap.py | notblocked | def notblocked(page):
"""Determine if given url is a page that should be in sitemap."""
for blocked in PAGES_TO_BLOCK:
if blocked[0] != '*':
blocked = '*' + blocked
rx = re.compile(blocked.replace('*', '[^$]*'))
if rx.match(page):
return False
return True | python | def notblocked(page):
"""Determine if given url is a page that should be in sitemap."""
for blocked in PAGES_TO_BLOCK:
if blocked[0] != '*':
blocked = '*' + blocked
rx = re.compile(blocked.replace('*', '[^$]*'))
if rx.match(page):
return False
return True | [
"def",
"notblocked",
"(",
"page",
")",
":",
"for",
"blocked",
"in",
"PAGES_TO_BLOCK",
":",
"if",
"blocked",
"[",
"0",
"]",
"!=",
"'*'",
":",
"blocked",
"=",
"'*'",
"+",
"blocked",
"rx",
"=",
"re",
".",
"compile",
"(",
"blocked",
".",
"replace",
"(",
... | Determine if given url is a page that should be in sitemap. | [
"Determine",
"if",
"given",
"url",
"is",
"a",
"page",
"that",
"should",
"be",
"in",
"sitemap",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/sitemap.py#L39-L47 |
openstax/cnx-archive | cnxarchive/views/sitemap.py | sitemap | def sitemap(request):
"""Return a sitemap xml file for search engines."""
xml = Sitemap()
author = request.matchdict.get('from_id')
if author is not None:
match = "AND '{}' = authors[1]".format(author)
else:
match = ''
with db_connect() as db_connection:
with db_connecti... | python | def sitemap(request):
"""Return a sitemap xml file for search engines."""
xml = Sitemap()
author = request.matchdict.get('from_id')
if author is not None:
match = "AND '{}' = authors[1]".format(author)
else:
match = ''
with db_connect() as db_connection:
with db_connecti... | [
"def",
"sitemap",
"(",
"request",
")",
":",
"xml",
"=",
"Sitemap",
"(",
")",
"author",
"=",
"request",
".",
"matchdict",
".",
"get",
"(",
"'from_id'",
")",
"if",
"author",
"is",
"not",
"None",
":",
"match",
"=",
"\"AND '{}' = authors[1]\"",
".",
"format"... | Return a sitemap xml file for search engines. | [
"Return",
"a",
"sitemap",
"xml",
"file",
"for",
"search",
"engines",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/sitemap.py#L56-L96 |
openstax/cnx-archive | cnxarchive/views/sitemap.py | sitemap_index | def sitemap_index(request):
"""Return a sitemap index xml file for search engines."""
sitemaps = []
with db_connect() as db_connection:
with db_connection.cursor() as cursor:
cursor.execute("""\
SELECT authors[1], max(revised)
FROM latest_modules
... | python | def sitemap_index(request):
"""Return a sitemap index xml file for search engines."""
sitemaps = []
with db_connect() as db_connection:
with db_connection.cursor() as cursor:
cursor.execute("""\
SELECT authors[1], max(revised)
FROM latest_modules
... | [
"def",
"sitemap_index",
"(",
"request",
")",
":",
"sitemaps",
"=",
"[",
"]",
"with",
"db_connect",
"(",
")",
"as",
"db_connection",
":",
"with",
"db_connection",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"cursor",
".",
"execute",
"(",
"\"\"\"\\\n ... | Return a sitemap index xml file for search engines. | [
"Return",
"a",
"sitemap",
"index",
"xml",
"file",
"for",
"search",
"engines",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/sitemap.py#L101-L123 |
ZELLMECHANIK-DRESDEN/dclab | dclab/features/volume.py | get_volume | def get_volume(cont, pos_x, pos_y, pix):
"""Calculate the volume of a polygon revolved around an axis
The volume estimation assumes rotational symmetry.
Green`s theorem and the Gaussian divergence theorem allow to
formulate the volume as a line integral.
Parameters
----------
cont: ndarray... | python | def get_volume(cont, pos_x, pos_y, pix):
"""Calculate the volume of a polygon revolved around an axis
The volume estimation assumes rotational symmetry.
Green`s theorem and the Gaussian divergence theorem allow to
formulate the volume as a line integral.
Parameters
----------
cont: ndarray... | [
"def",
"get_volume",
"(",
"cont",
",",
"pos_x",
",",
"pos_y",
",",
"pix",
")",
":",
"if",
"np",
".",
"isscalar",
"(",
"pos_x",
")",
":",
"cont",
"=",
"[",
"cont",
"]",
"ret_list",
"=",
"False",
"else",
":",
"ret_list",
"=",
"True",
"# Convert input t... | Calculate the volume of a polygon revolved around an axis
The volume estimation assumes rotational symmetry.
Green`s theorem and the Gaussian divergence theorem allow to
formulate the volume as a line integral.
Parameters
----------
cont: ndarray or list of ndarrays of shape (N,2)
A 2D... | [
"Calculate",
"the",
"volume",
"of",
"a",
"polygon",
"revolved",
"around",
"an",
"axis"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/volume.py#L9-L121 |
ZELLMECHANIK-DRESDEN/dclab | dclab/features/volume.py | counter_clockwise | def counter_clockwise(cx, cy):
"""Put contour coordinates into counter-clockwise order
Parameters
----------
cx, cy: 1d ndarrays
The x- and y-coordinates of the contour
Returns
-------
cx_cc, cy_cc:
The x- and y-coordinates of the contour in
counter-clockwise orient... | python | def counter_clockwise(cx, cy):
"""Put contour coordinates into counter-clockwise order
Parameters
----------
cx, cy: 1d ndarrays
The x- and y-coordinates of the contour
Returns
-------
cx_cc, cy_cc:
The x- and y-coordinates of the contour in
counter-clockwise orient... | [
"def",
"counter_clockwise",
"(",
"cx",
",",
"cy",
")",
":",
"# test orientation",
"angles",
"=",
"np",
".",
"unwrap",
"(",
"np",
".",
"arctan2",
"(",
"cy",
",",
"cx",
")",
")",
"grad",
"=",
"np",
".",
"gradient",
"(",
"angles",
")",
"if",
"np",
"."... | Put contour coordinates into counter-clockwise order
Parameters
----------
cx, cy: 1d ndarrays
The x- and y-coordinates of the contour
Returns
-------
cx_cc, cy_cc:
The x- and y-coordinates of the contour in
counter-clockwise orientation. | [
"Put",
"contour",
"coordinates",
"into",
"counter",
"-",
"clockwise",
"order"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/volume.py#L124-L144 |
robmcmullen/atrcopy | atrcopy/dos33.py | Dos33Dirent.add_metadata_sectors | def add_metadata_sectors(self, vtoc, sector_list, header):
"""Add track/sector list
"""
tslist = BaseSectorList(header)
for start in range(0, len(sector_list), header.ts_pairs):
end = min(start + header.ts_pairs, len(sector_list))
if _xd: log.debug("ts: %d-%d" % (... | python | def add_metadata_sectors(self, vtoc, sector_list, header):
"""Add track/sector list
"""
tslist = BaseSectorList(header)
for start in range(0, len(sector_list), header.ts_pairs):
end = min(start + header.ts_pairs, len(sector_list))
if _xd: log.debug("ts: %d-%d" % (... | [
"def",
"add_metadata_sectors",
"(",
"self",
",",
"vtoc",
",",
"sector_list",
",",
"header",
")",
":",
"tslist",
"=",
"BaseSectorList",
"(",
"header",
")",
"for",
"start",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"sector_list",
")",
",",
"header",
".",
... | Add track/sector list | [
"Add",
"track",
"/",
"sector",
"list"
] | train | https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/dos33.py#L268-L282 |
openstax/cnx-archive | cnxarchive/views/extras.py | _get_subject_list_generator | def _get_subject_list_generator(cursor):
"""Return all subjects (tags) in the database except "internal" scheme."""
subject = None
last_tagid = None
cursor.execute(SQL['get-subject-list'])
for s in cursor.fetchall():
tagid, tagname, portal_type, count = s
if tagid != last_tagid:
... | python | def _get_subject_list_generator(cursor):
"""Return all subjects (tags) in the database except "internal" scheme."""
subject = None
last_tagid = None
cursor.execute(SQL['get-subject-list'])
for s in cursor.fetchall():
tagid, tagname, portal_type, count = s
if tagid != last_tagid:
... | [
"def",
"_get_subject_list_generator",
"(",
"cursor",
")",
":",
"subject",
"=",
"None",
"last_tagid",
"=",
"None",
"cursor",
".",
"execute",
"(",
"SQL",
"[",
"'get-subject-list'",
"]",
")",
"for",
"s",
"in",
"cursor",
".",
"fetchall",
"(",
")",
":",
"tagid"... | Return all subjects (tags) in the database except "internal" scheme. | [
"Return",
"all",
"subjects",
"(",
"tags",
")",
"in",
"the",
"database",
"except",
"internal",
"scheme",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/extras.py#L32-L54 |
openstax/cnx-archive | cnxarchive/views/extras.py | extras | def extras(request):
"""Return a dict with archive metadata for webview."""
key = request.matchdict.get('key', '').lstrip('/')
key_map = {
'languages': _get_available_languages_and_count,
'subjects': _get_subject_list,
'featured': _get_featured_links,
'messages': _get_service... | python | def extras(request):
"""Return a dict with archive metadata for webview."""
key = request.matchdict.get('key', '').lstrip('/')
key_map = {
'languages': _get_available_languages_and_count,
'subjects': _get_subject_list,
'featured': _get_featured_links,
'messages': _get_service... | [
"def",
"extras",
"(",
"request",
")",
":",
"key",
"=",
"request",
".",
"matchdict",
".",
"get",
"(",
"'key'",
",",
"''",
")",
".",
"lstrip",
"(",
"'/'",
")",
"key_map",
"=",
"{",
"'languages'",
":",
"_get_available_languages_and_count",
",",
"'subjects'",
... | Return a dict with archive metadata for webview. | [
"Return",
"a",
"dict",
"with",
"archive",
"metadata",
"for",
"webview",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/extras.py#L86-L110 |
xenon-middleware/pyxenon | examples/timeout.py | timeout | def timeout(delay, call, *args, **kwargs):
"""Run a function call for `delay` seconds, and raise a RuntimeError
if the operation didn't complete."""
return_value = None
def target():
nonlocal return_value
return_value = call(*args, **kwargs)
t = Thread(target=target)
t.start()
... | python | def timeout(delay, call, *args, **kwargs):
"""Run a function call for `delay` seconds, and raise a RuntimeError
if the operation didn't complete."""
return_value = None
def target():
nonlocal return_value
return_value = call(*args, **kwargs)
t = Thread(target=target)
t.start()
... | [
"def",
"timeout",
"(",
"delay",
",",
"call",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return_value",
"=",
"None",
"def",
"target",
"(",
")",
":",
"nonlocal",
"return_value",
"return_value",
"=",
"call",
"(",
"*",
"args",
",",
"*",
"*",
... | Run a function call for `delay` seconds, and raise a RuntimeError
if the operation didn't complete. | [
"Run",
"a",
"function",
"call",
"for",
"delay",
"seconds",
"and",
"raise",
"a",
"RuntimeError",
"if",
"the",
"operation",
"didn",
"t",
"complete",
"."
] | train | https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/examples/timeout.py#L4-L19 |
openstax/cnx-archive | cnxarchive/scripts/_utils.py | create_parser | def create_parser(name, description=None):
"""Create an argument parser with the given ``name`` and ``description``.
The name is used to make ``cnx-archive-<name>`` program name.
This creates and returns a parser with
the ``config_uri`` argument declared.
"""
prog = _gen_prog_name(name)
par... | python | def create_parser(name, description=None):
"""Create an argument parser with the given ``name`` and ``description``.
The name is used to make ``cnx-archive-<name>`` program name.
This creates and returns a parser with
the ``config_uri`` argument declared.
"""
prog = _gen_prog_name(name)
par... | [
"def",
"create_parser",
"(",
"name",
",",
"description",
"=",
"None",
")",
":",
"prog",
"=",
"_gen_prog_name",
"(",
"name",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"prog",
",",
"description",
"=",
"description",
")",
"parse... | Create an argument parser with the given ``name`` and ``description``.
The name is used to make ``cnx-archive-<name>`` program name.
This creates and returns a parser with
the ``config_uri`` argument declared. | [
"Create",
"an",
"argument",
"parser",
"with",
"the",
"given",
"name",
"and",
"description",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/_utils.py#L28-L42 |
openstax/cnx-archive | cnxarchive/scripts/_utils.py | get_app_settings_from_arguments | def get_app_settings_from_arguments(args):
"""Parse ``argparse`` style arguments into app settings.
Given an ``argparse`` set of arguments as ``args``
parse the arguments to return the application settings.
This assumes the parser was created using ``create_parser``.
"""
config_filepath = os.pa... | python | def get_app_settings_from_arguments(args):
"""Parse ``argparse`` style arguments into app settings.
Given an ``argparse`` set of arguments as ``args``
parse the arguments to return the application settings.
This assumes the parser was created using ``create_parser``.
"""
config_filepath = os.pa... | [
"def",
"get_app_settings_from_arguments",
"(",
"args",
")",
":",
"config_filepath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"args",
".",
"config_uri",
")",
"return",
"get_appsettings",
"(",
"config_filepath",
",",
"name",
"=",
"args",
".",
"config_name",
... | Parse ``argparse`` style arguments into app settings.
Given an ``argparse`` set of arguments as ``args``
parse the arguments to return the application settings.
This assumes the parser was created using ``create_parser``. | [
"Parse",
"argparse",
"style",
"arguments",
"into",
"app",
"settings",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/_utils.py#L45-L53 |
xenon-middleware/pyxenon | xenon/server.py | check_socket | def check_socket(host, port):
"""Checks if port is open on host. This is used to check if the
Xenon-GRPC server is running."""
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
return sock.connect_ex((host, port)) == 0 | python | def check_socket(host, port):
"""Checks if port is open on host. This is used to check if the
Xenon-GRPC server is running."""
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
return sock.connect_ex((host, port)) == 0 | [
"def",
"check_socket",
"(",
"host",
",",
"port",
")",
":",
"with",
"closing",
"(",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
")",
"as",
"sock",
":",
"return",
"sock",
".",
"connect_ex",
"(",
"(",
... | Checks if port is open on host. This is used to check if the
Xenon-GRPC server is running. | [
"Checks",
"if",
"port",
"is",
"open",
"on",
"host",
".",
"This",
"is",
"used",
"to",
"check",
"if",
"the",
"Xenon",
"-",
"GRPC",
"server",
"is",
"running",
"."
] | train | https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/server.py#L19-L23 |
xenon-middleware/pyxenon | xenon/server.py | get_secure_channel | def get_secure_channel(crt_file, key_file, port=50051):
"""Try to connect over a secure channel."""
creds = grpc.ssl_channel_credentials(
root_certificates=open(str(crt_file), 'rb').read(),
private_key=open(str(key_file), 'rb').read(),
certificate_chain=open(str(crt_file), 'rb').read())... | python | def get_secure_channel(crt_file, key_file, port=50051):
"""Try to connect over a secure channel."""
creds = grpc.ssl_channel_credentials(
root_certificates=open(str(crt_file), 'rb').read(),
private_key=open(str(key_file), 'rb').read(),
certificate_chain=open(str(crt_file), 'rb').read())... | [
"def",
"get_secure_channel",
"(",
"crt_file",
",",
"key_file",
",",
"port",
"=",
"50051",
")",
":",
"creds",
"=",
"grpc",
".",
"ssl_channel_credentials",
"(",
"root_certificates",
"=",
"open",
"(",
"str",
"(",
"crt_file",
")",
",",
"'rb'",
")",
".",
"read"... | Try to connect over a secure channel. | [
"Try",
"to",
"connect",
"over",
"a",
"secure",
"channel",
"."
] | train | https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/server.py#L26-L36 |
xenon-middleware/pyxenon | xenon/server.py | find_free_port | def find_free_port():
"""Finds a free port."""
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.bind(('', 0))
return sock.getsockname()[1] | python | def find_free_port():
"""Finds a free port."""
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.bind(('', 0))
return sock.getsockname()[1] | [
"def",
"find_free_port",
"(",
")",
":",
"with",
"closing",
"(",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
")",
"as",
"sock",
":",
"sock",
".",
"bind",
"(",
"(",
"''",
",",
"0",
")",
")",
"return... | Finds a free port. | [
"Finds",
"a",
"free",
"port",
"."
] | train | https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/server.py#L39-L43 |
xenon-middleware/pyxenon | xenon/server.py | print_stream | def print_stream(file, name):
"""Print stream from file to logger."""
logger = logging.getLogger('xenon.{}'.format(name))
for line in file:
logger.info('[{}] {}'.format(name, line.strip())) | python | def print_stream(file, name):
"""Print stream from file to logger."""
logger = logging.getLogger('xenon.{}'.format(name))
for line in file:
logger.info('[{}] {}'.format(name, line.strip())) | [
"def",
"print_stream",
"(",
"file",
",",
"name",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'xenon.{}'",
".",
"format",
"(",
"name",
")",
")",
"for",
"line",
"in",
"file",
":",
"logger",
".",
"info",
"(",
"'[{}] {}'",
".",
"format",
... | Print stream from file to logger. | [
"Print",
"stream",
"from",
"file",
"to",
"logger",
"."
] | train | https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/server.py#L46-L50 |
xenon-middleware/pyxenon | xenon/server.py | init | def init(port=None, do_not_exit=False, disable_tls=False, log_level='WARNING'):
"""Start the Xenon GRPC server on the specified port, or, if a service
is already running on that port, connect to that.
If no port is given, a random port is selected. This means that, by
default, every python instance wil... | python | def init(port=None, do_not_exit=False, disable_tls=False, log_level='WARNING'):
"""Start the Xenon GRPC server on the specified port, or, if a service
is already running on that port, connect to that.
If no port is given, a random port is selected. This means that, by
default, every python instance wil... | [
"def",
"init",
"(",
"port",
"=",
"None",
",",
"do_not_exit",
"=",
"False",
",",
"disable_tls",
"=",
"False",
",",
"log_level",
"=",
"'WARNING'",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'xenon'",
")",
"logger",
".",
"setLevel",
"(",
... | Start the Xenon GRPC server on the specified port, or, if a service
is already running on that port, connect to that.
If no port is given, a random port is selected. This means that, by
default, every python instance will start its own instance of a xenon-grpc
process.
:param port: the port number... | [
"Start",
"the",
"Xenon",
"GRPC",
"server",
"on",
"the",
"specified",
"port",
"or",
"if",
"a",
"service",
"is",
"already",
"running",
"on",
"that",
"port",
"connect",
"to",
"that",
"."
] | train | https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/server.py#L116-L151 |
openstax/cnx-archive | cnxarchive/events.py | add_cors_headers | def add_cors_headers(request, response):
"""Add cors headers needed for web app implementation."""
response.headerlist.append(('Access-Control-Allow-Origin', '*'))
response.headerlist.append(
('Access-Control-Allow-Methods', 'GET, OPTIONS'))
response.headerlist.append(
('Access-Control-A... | python | def add_cors_headers(request, response):
"""Add cors headers needed for web app implementation."""
response.headerlist.append(('Access-Control-Allow-Origin', '*'))
response.headerlist.append(
('Access-Control-Allow-Methods', 'GET, OPTIONS'))
response.headerlist.append(
('Access-Control-A... | [
"def",
"add_cors_headers",
"(",
"request",
",",
"response",
")",
":",
"response",
".",
"headerlist",
".",
"append",
"(",
"(",
"'Access-Control-Allow-Origin'",
",",
"'*'",
")",
")",
"response",
".",
"headerlist",
".",
"append",
"(",
"(",
"'Access-Control-Allow-Me... | Add cors headers needed for web app implementation. | [
"Add",
"cors",
"headers",
"needed",
"for",
"web",
"app",
"implementation",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/events.py#L15-L22 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/fmt_tdms/event_trace.py | TraceColumn.trace | def trace(self):
"""Initializes the trace data"""
if self._trace is None:
self._trace = self.load_trace(self.mname)
return self._trace | python | def trace(self):
"""Initializes the trace data"""
if self._trace is None:
self._trace = self.load_trace(self.mname)
return self._trace | [
"def",
"trace",
"(",
"self",
")",
":",
"if",
"self",
".",
"_trace",
"is",
"None",
":",
"self",
".",
"_trace",
"=",
"self",
".",
"load_trace",
"(",
"self",
".",
"mname",
")",
"return",
"self",
".",
"_trace"
] | Initializes the trace data | [
"Initializes",
"the",
"trace",
"data"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/event_trace.py#L58-L62 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/fmt_tdms/event_trace.py | TraceColumn.load_trace | def load_trace(mname):
"""Loads the traces and returns them as a dictionary
Currently, only loading traces from tdms files is supported.
This forces us to load the full tdms file into memory which
takes some time.
"""
tname = TraceColumn.find_trace_file(mname)
#... | python | def load_trace(mname):
"""Loads the traces and returns them as a dictionary
Currently, only loading traces from tdms files is supported.
This forces us to load the full tdms file into memory which
takes some time.
"""
tname = TraceColumn.find_trace_file(mname)
#... | [
"def",
"load_trace",
"(",
"mname",
")",
":",
"tname",
"=",
"TraceColumn",
".",
"find_trace_file",
"(",
"mname",
")",
"# Initialize empty trace dictionary",
"trace",
"=",
"{",
"}",
"if",
"tname",
"is",
"None",
":",
"pass",
"elif",
"tname",
".",
"suffix",
"=="... | Loads the traces and returns them as a dictionary
Currently, only loading traces from tdms files is supported.
This forces us to load the full tdms file into memory which
takes some time. | [
"Loads",
"the",
"traces",
"and",
"returns",
"them",
"as",
"a",
"dictionary"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/event_trace.py#L65-L101 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/fmt_tdms/event_trace.py | TraceColumn.find_trace_file | def find_trace_file(mname):
"""Tries to find the traces tdms file name
Returns None if no trace file is found.
"""
mname = pathlib.Path(mname)
tname = None
if mname.exists():
cand = mname.with_name(mname.name[:-5] + "_traces.tdms")
if cand.exists... | python | def find_trace_file(mname):
"""Tries to find the traces tdms file name
Returns None if no trace file is found.
"""
mname = pathlib.Path(mname)
tname = None
if mname.exists():
cand = mname.with_name(mname.name[:-5] + "_traces.tdms")
if cand.exists... | [
"def",
"find_trace_file",
"(",
"mname",
")",
":",
"mname",
"=",
"pathlib",
".",
"Path",
"(",
"mname",
")",
"tname",
"=",
"None",
"if",
"mname",
".",
"exists",
"(",
")",
":",
"cand",
"=",
"mname",
".",
"with_name",
"(",
"mname",
".",
"name",
"[",
":... | Tries to find the traces tdms file name
Returns None if no trace file is found. | [
"Tries",
"to",
"find",
"the",
"traces",
"tdms",
"file",
"name"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/event_trace.py#L104-L117 |
Fischerfredl/get-docker-secret | get_docker_secret.py | get_docker_secret | def get_docker_secret(name, default=None, cast_to=str, autocast_name=True, getenv=True, safe=True,
secrets_dir=os.path.join(root, 'var', 'run', 'secrets')):
"""This function fetches a docker secret
:param name: the name of the docker secret
:param default: the default value if no secr... | python | def get_docker_secret(name, default=None, cast_to=str, autocast_name=True, getenv=True, safe=True,
secrets_dir=os.path.join(root, 'var', 'run', 'secrets')):
"""This function fetches a docker secret
:param name: the name of the docker secret
:param default: the default value if no secr... | [
"def",
"get_docker_secret",
"(",
"name",
",",
"default",
"=",
"None",
",",
"cast_to",
"=",
"str",
",",
"autocast_name",
"=",
"True",
",",
"getenv",
"=",
"True",
",",
"safe",
"=",
"True",
",",
"secrets_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"... | This function fetches a docker secret
:param name: the name of the docker secret
:param default: the default value if no secret found
:param cast_to: casts the value to the given type
:param autocast_name: whether the name should be lowercase for secrets and upper case for environment
:param getenv... | [
"This",
"function",
"fetches",
"a",
"docker",
"secret"
] | train | https://github.com/Fischerfredl/get-docker-secret/blob/1fa7f7e2d8b727fd95b6257041e0498fde2d3880/get_docker_secret.py#L6-L61 |
ZELLMECHANIK-DRESDEN/dclab | dclab/cached.py | Cache._update_hash | def _update_hash(self, arg):
""" Takes an argument and updates the hash.
The argument can be an np.array, string, or list
of things that are convertable to strings.
"""
if isinstance(arg, np.ndarray):
self.ahash.update(arg.view(np.uint8))
elif isinstance(arg, ... | python | def _update_hash(self, arg):
""" Takes an argument and updates the hash.
The argument can be an np.array, string, or list
of things that are convertable to strings.
"""
if isinstance(arg, np.ndarray):
self.ahash.update(arg.view(np.uint8))
elif isinstance(arg, ... | [
"def",
"_update_hash",
"(",
"self",
",",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"np",
".",
"ndarray",
")",
":",
"self",
".",
"ahash",
".",
"update",
"(",
"arg",
".",
"view",
"(",
"np",
".",
"uint8",
")",
")",
"elif",
"isinstance",
... | Takes an argument and updates the hash.
The argument can be an np.array, string, or list
of things that are convertable to strings. | [
"Takes",
"an",
"argument",
"and",
"updates",
"the",
"hash",
".",
"The",
"argument",
"can",
"be",
"an",
"np",
".",
"array",
"string",
"or",
"list",
"of",
"things",
"that",
"are",
"convertable",
"to",
"strings",
"."
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/cached.py#L81-L91 |
ZELLMECHANIK-DRESDEN/dclab | dclab/cached.py | Cache.clear_cache | def clear_cache():
"""Remove all cached objects"""
del Cache._keys
for k in list(Cache._cache.keys()):
it = Cache._cache.pop(k)
del it
del Cache._cache
Cache._keys = []
Cache._cache = {}
gc.collect() | python | def clear_cache():
"""Remove all cached objects"""
del Cache._keys
for k in list(Cache._cache.keys()):
it = Cache._cache.pop(k)
del it
del Cache._cache
Cache._keys = []
Cache._cache = {}
gc.collect() | [
"def",
"clear_cache",
"(",
")",
":",
"del",
"Cache",
".",
"_keys",
"for",
"k",
"in",
"list",
"(",
"Cache",
".",
"_cache",
".",
"keys",
"(",
")",
")",
":",
"it",
"=",
"Cache",
".",
"_cache",
".",
"pop",
"(",
"k",
")",
"del",
"it",
"del",
"Cache"... | Remove all cached objects | [
"Remove",
"all",
"cached",
"objects"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/cached.py#L94-L103 |
robmcmullen/atrcopy | atrcopy/diskimages.py | BaseHeader.get_pos | def get_pos(self, sector):
"""Get index (into the raw data of the disk image) of start of sector
This base class method assumes the sectors are one after another, in
order starting from the beginning of the raw data.
"""
if not self.sector_is_valid(sector):
raise Byt... | python | def get_pos(self, sector):
"""Get index (into the raw data of the disk image) of start of sector
This base class method assumes the sectors are one after another, in
order starting from the beginning of the raw data.
"""
if not self.sector_is_valid(sector):
raise Byt... | [
"def",
"get_pos",
"(",
"self",
",",
"sector",
")",
":",
"if",
"not",
"self",
".",
"sector_is_valid",
"(",
"sector",
")",
":",
"raise",
"ByteNotInFile166",
"(",
"\"Sector %d out of range\"",
"%",
"sector",
")",
"pos",
"=",
"sector",
"*",
"self",
".",
"secto... | Get index (into the raw data of the disk image) of start of sector
This base class method assumes the sectors are one after another, in
order starting from the beginning of the raw data. | [
"Get",
"index",
"(",
"into",
"the",
"raw",
"data",
"of",
"the",
"disk",
"image",
")",
"of",
"start",
"of",
"sector"
] | train | https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/diskimages.py#L64-L74 |
robmcmullen/atrcopy | atrcopy/diskimages.py | DiskImageBase.get_sector_slice | def get_sector_slice(self, start, end=None):
""" Get contiguous sectors
:param start: first sector number to read (note: numbering starts from 1)
:param end: last sector number to read
:returns: bytes
"""
pos, size = self.header.get_pos(start)
if end is N... | python | def get_sector_slice(self, start, end=None):
""" Get contiguous sectors
:param start: first sector number to read (note: numbering starts from 1)
:param end: last sector number to read
:returns: bytes
"""
pos, size = self.header.get_pos(start)
if end is N... | [
"def",
"get_sector_slice",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"pos",
",",
"size",
"=",
"self",
".",
"header",
".",
"get_pos",
"(",
"start",
")",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"start",
"while",
"start",
"<",
... | Get contiguous sectors
:param start: first sector number to read (note: numbering starts from 1)
:param end: last sector number to read
:returns: bytes | [
"Get",
"contiguous",
"sectors",
":",
"param",
"start",
":",
"first",
"sector",
"number",
"to",
"read",
"(",
"note",
":",
"numbering",
"starts",
"from",
"1",
")",
":",
"param",
"end",
":",
"last",
"sector",
"number",
"to",
"read",
":",
"returns",
":",
"... | train | https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/diskimages.py#L225-L239 |
robmcmullen/atrcopy | atrcopy/diskimages.py | DiskImageBase.get_sectors | def get_sectors(self, start, end=None):
""" Get contiguous sectors
:param start: first sector number to read (note: numbering starts from 1)
:param end: last sector number to read
:returns: bytes
"""
s = self.get_sector_slice(start, end)
return self.bytes... | python | def get_sectors(self, start, end=None):
""" Get contiguous sectors
:param start: first sector number to read (note: numbering starts from 1)
:param end: last sector number to read
:returns: bytes
"""
s = self.get_sector_slice(start, end)
return self.bytes... | [
"def",
"get_sectors",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"s",
"=",
"self",
".",
"get_sector_slice",
"(",
"start",
",",
"end",
")",
"return",
"self",
".",
"bytes",
"[",
"s",
"]",
",",
"self",
".",
"style",
"[",
"s",
"]"
... | Get contiguous sectors
:param start: first sector number to read (note: numbering starts from 1)
:param end: last sector number to read
:returns: bytes | [
"Get",
"contiguous",
"sectors",
":",
"param",
"start",
":",
"first",
"sector",
"number",
"to",
"read",
"(",
"note",
":",
"numbering",
"starts",
"from",
"1",
")",
":",
"param",
"end",
":",
"last",
"sector",
"number",
"to",
"read",
":",
"returns",
":",
"... | train | https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/diskimages.py#L241-L249 |
robmcmullen/atrcopy | atrcopy/diskimages.py | DiskImageBase.write_file | def write_file(self, filename, filetype, data):
"""Write data to a file on disk
This throws various exceptions on failures, for instance if there is
not enough space on disk or a free entry is not available in the
catalog.
"""
state = self.begin_transaction()
try... | python | def write_file(self, filename, filetype, data):
"""Write data to a file on disk
This throws various exceptions on failures, for instance if there is
not enough space on disk or a free entry is not available in the
catalog.
"""
state = self.begin_transaction()
try... | [
"def",
"write_file",
"(",
"self",
",",
"filename",
",",
"filetype",
",",
"data",
")",
":",
"state",
"=",
"self",
".",
"begin_transaction",
"(",
")",
"try",
":",
"directory",
"=",
"self",
".",
"directory_class",
"(",
"self",
".",
"header",
")",
"self",
... | Write data to a file on disk
This throws various exceptions on failures, for instance if there is
not enough space on disk or a free entry is not available in the
catalog. | [
"Write",
"data",
"to",
"a",
"file",
"on",
"disk"
] | train | https://github.com/robmcmullen/atrcopy/blob/dafba8e74c718e95cf81fd72c184fa193ecec730/atrcopy/diskimages.py#L337-L360 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/core.py | RTDCBase._apply_scale | def _apply_scale(self, a, scale, feat):
"""Helper function for transforming an aray to log-scale
Parameters
----------
a: np.ndarray
Input array
scale:
If set to "log", take the logarithm of `a`; if set to
"linear" return `a` unchanged.
... | python | def _apply_scale(self, a, scale, feat):
"""Helper function for transforming an aray to log-scale
Parameters
----------
a: np.ndarray
Input array
scale:
If set to "log", take the logarithm of `a`; if set to
"linear" return `a` unchanged.
... | [
"def",
"_apply_scale",
"(",
"self",
",",
"a",
",",
"scale",
",",
"feat",
")",
":",
"if",
"scale",
"==",
"\"linear\"",
":",
"b",
"=",
"a",
"elif",
"scale",
"==",
"\"log\"",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
"True",
")... | Helper function for transforming an aray to log-scale
Parameters
----------
a: np.ndarray
Input array
scale:
If set to "log", take the logarithm of `a`; if set to
"linear" return `a` unchanged.
Returns
-------
b: np.ndarray
... | [
"Helper",
"function",
"for",
"transforming",
"an",
"aray",
"to",
"log",
"-",
"scale"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/core.py#L148-L184 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/core.py | RTDCBase.features | def features(self):
"""All available features"""
mycols = []
for col in dfn.feature_names:
if col in self:
mycols.append(col)
mycols.sort()
return mycols | python | def features(self):
"""All available features"""
mycols = []
for col in dfn.feature_names:
if col in self:
mycols.append(col)
mycols.sort()
return mycols | [
"def",
"features",
"(",
"self",
")",
":",
"mycols",
"=",
"[",
"]",
"for",
"col",
"in",
"dfn",
".",
"feature_names",
":",
"if",
"col",
"in",
"self",
":",
"mycols",
".",
"append",
"(",
"col",
")",
"mycols",
".",
"sort",
"(",
")",
"return",
"mycols"
] | All available features | [
"All",
"available",
"features"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/core.py#L206-L213 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/core.py | RTDCBase.get_downsampled_scatter | def get_downsampled_scatter(self, xax="area_um", yax="deform",
downsample=0, xscale="linear",
yscale="linear"):
"""Downsampling by removing points at dense locations
Parameters
----------
xax: str
Identifier for... | python | def get_downsampled_scatter(self, xax="area_um", yax="deform",
downsample=0, xscale="linear",
yscale="linear"):
"""Downsampling by removing points at dense locations
Parameters
----------
xax: str
Identifier for... | [
"def",
"get_downsampled_scatter",
"(",
"self",
",",
"xax",
"=",
"\"area_um\"",
",",
"yax",
"=",
"\"deform\"",
",",
"downsample",
"=",
"0",
",",
"xscale",
"=",
"\"linear\"",
",",
"yscale",
"=",
"\"linear\"",
")",
":",
"if",
"downsample",
"<",
"0",
":",
"r... | Downsampling by removing points at dense locations
Parameters
----------
xax: str
Identifier for x axis (e.g. "area_um", "aspect", "deform")
yax: str
Identifier for y axis
downsample: int
Number of points to draw in the down-sampled plot.
... | [
"Downsampling",
"by",
"removing",
"points",
"at",
"dense",
"locations"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/core.py#L223-L271 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/core.py | RTDCBase.get_kde_contour | def get_kde_contour(self, xax="area_um", yax="deform", xacc=None,
yacc=None, kde_type="histogram", kde_kwargs={},
xscale="linear", yscale="linear"):
"""Evaluate the kernel density estimate for contour plots
Parameters
----------
xax: str
... | python | def get_kde_contour(self, xax="area_um", yax="deform", xacc=None,
yacc=None, kde_type="histogram", kde_kwargs={},
xscale="linear", yscale="linear"):
"""Evaluate the kernel density estimate for contour plots
Parameters
----------
xax: str
... | [
"def",
"get_kde_contour",
"(",
"self",
",",
"xax",
"=",
"\"area_um\"",
",",
"yax",
"=",
"\"deform\"",
",",
"xacc",
"=",
"None",
",",
"yacc",
"=",
"None",
",",
"kde_type",
"=",
"\"histogram\"",
",",
"kde_kwargs",
"=",
"{",
"}",
",",
"xscale",
"=",
"\"li... | Evaluate the kernel density estimate for contour plots
Parameters
----------
xax: str
Identifier for X axis (e.g. "area_um", "aspect", "deform")
yax: str
Identifier for Y axis
xacc: float
Contour accuracy in x direction
yacc: float
... | [
"Evaluate",
"the",
"kernel",
"density",
"estimate",
"for",
"contour",
"plots"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/core.py#L273-L351 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/core.py | RTDCBase.get_kde_scatter | def get_kde_scatter(self, xax="area_um", yax="deform", positions=None,
kde_type="histogram", kde_kwargs={}, xscale="linear",
yscale="linear"):
"""Evaluate the kernel density estimate for scatter plots
Parameters
----------
xax: str
... | python | def get_kde_scatter(self, xax="area_um", yax="deform", positions=None,
kde_type="histogram", kde_kwargs={}, xscale="linear",
yscale="linear"):
"""Evaluate the kernel density estimate for scatter plots
Parameters
----------
xax: str
... | [
"def",
"get_kde_scatter",
"(",
"self",
",",
"xax",
"=",
"\"area_um\"",
",",
"yax",
"=",
"\"deform\"",
",",
"positions",
"=",
"None",
",",
"kde_type",
"=",
"\"histogram\"",
",",
"kde_kwargs",
"=",
"{",
"}",
",",
"xscale",
"=",
"\"linear\"",
",",
"yscale",
... | Evaluate the kernel density estimate for scatter plots
Parameters
----------
xax: str
Identifier for X axis (e.g. "area_um", "aspect", "deform")
yax: str
Identifier for Y axis
positions: list of two 1d ndarrays or ndarray of shape (2, N)
The p... | [
"Evaluate",
"the",
"kernel",
"density",
"estimate",
"for",
"scatter",
"plots"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/core.py#L353-L413 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/core.py | RTDCBase.polygon_filter_add | def polygon_filter_add(self, filt):
"""Associate a Polygon Filter with this instance
Parameters
----------
filt: int or instance of `PolygonFilter`
The polygon filter to add
"""
if not isinstance(filt, (PolygonFilter, int, float)):
msg = "`filt` m... | python | def polygon_filter_add(self, filt):
"""Associate a Polygon Filter with this instance
Parameters
----------
filt: int or instance of `PolygonFilter`
The polygon filter to add
"""
if not isinstance(filt, (PolygonFilter, int, float)):
msg = "`filt` m... | [
"def",
"polygon_filter_add",
"(",
"self",
",",
"filt",
")",
":",
"if",
"not",
"isinstance",
"(",
"filt",
",",
"(",
"PolygonFilter",
",",
"int",
",",
"float",
")",
")",
":",
"msg",
"=",
"\"`filt` must be a number or instance of PolygonFilter!\"",
"raise",
"ValueE... | Associate a Polygon Filter with this instance
Parameters
----------
filt: int or instance of `PolygonFilter`
The polygon filter to add | [
"Associate",
"a",
"Polygon",
"Filter",
"with",
"this",
"instance"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/core.py#L415-L432 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/core.py | RTDCBase.polygon_filter_rm | def polygon_filter_rm(self, filt):
"""Remove a polygon filter from this instance
Parameters
----------
filt: int or instance of `PolygonFilter`
The polygon filter to remove
"""
if not isinstance(filt, (PolygonFilter, int, float)):
msg = "`filt` mu... | python | def polygon_filter_rm(self, filt):
"""Remove a polygon filter from this instance
Parameters
----------
filt: int or instance of `PolygonFilter`
The polygon filter to remove
"""
if not isinstance(filt, (PolygonFilter, int, float)):
msg = "`filt` mu... | [
"def",
"polygon_filter_rm",
"(",
"self",
",",
"filt",
")",
":",
"if",
"not",
"isinstance",
"(",
"filt",
",",
"(",
"PolygonFilter",
",",
"int",
",",
"float",
")",
")",
":",
"msg",
"=",
"\"`filt` must be a number or instance of PolygonFilter!\"",
"raise",
"ValueEr... | Remove a polygon filter from this instance
Parameters
----------
filt: int or instance of `PolygonFilter`
The polygon filter to remove | [
"Remove",
"a",
"polygon",
"filter",
"from",
"this",
"instance"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/core.py#L434-L451 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/load.py | check_dataset | def check_dataset(path_or_ds):
"""Check whether a dataset is complete
Parameters
----------
path_or_ds: str or RTDCBase
Full path to a dataset on disk or an instance of RTDCBase
Returns
-------
violations: list of str
Dataset format violations (hard)
alerts: list of str... | python | def check_dataset(path_or_ds):
"""Check whether a dataset is complete
Parameters
----------
path_or_ds: str or RTDCBase
Full path to a dataset on disk or an instance of RTDCBase
Returns
-------
violations: list of str
Dataset format violations (hard)
alerts: list of str... | [
"def",
"check_dataset",
"(",
"path_or_ds",
")",
":",
"aler",
"=",
"[",
"]",
"info",
"=",
"[",
"]",
"viol",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"path_or_ds",
",",
"RTDCBase",
")",
":",
"ds",
"=",
"path_or_ds",
"else",
":",
"ds",
"=",
"load_file",
... | Check whether a dataset is complete
Parameters
----------
path_or_ds: str or RTDCBase
Full path to a dataset on disk or an instance of RTDCBase
Returns
-------
violations: list of str
Dataset format violations (hard)
alerts: list of str
Dataset format alerts (soft)
... | [
"Check",
"whether",
"a",
"dataset",
"is",
"complete"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/load.py#L60-L216 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/load.py | new_dataset | def new_dataset(data, identifier=None):
"""Initialize a new RT-DC dataset
Parameters
----------
data:
can be one of the following:
- dict
- .tdms file
- .rtdc file
- subclass of `RTDCBase`
(will create a hierarchy child)
identifier: str
A u... | python | def new_dataset(data, identifier=None):
"""Initialize a new RT-DC dataset
Parameters
----------
data:
can be one of the following:
- dict
- .tdms file
- .rtdc file
- subclass of `RTDCBase`
(will create a hierarchy child)
identifier: str
A u... | [
"def",
"new_dataset",
"(",
"data",
",",
"identifier",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"return",
"fmt_dict",
".",
"RTDC_Dict",
"(",
"data",
",",
"identifier",
"=",
"identifier",
")",
"elif",
"isinstance",
"("... | Initialize a new RT-DC dataset
Parameters
----------
data:
can be one of the following:
- dict
- .tdms file
- .rtdc file
- subclass of `RTDCBase`
(will create a hierarchy child)
identifier: str
A unique identifier for this dataset. If set to `N... | [
"Initialize",
"a",
"new",
"RT",
"-",
"DC",
"dataset"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/load.py#L229-L259 |
openstax/cnx-archive | cnxarchive/scripts/hits_counter.py | parse_log | def parse_log(log, url_pattern):
"""Parse ``log`` buffer based on ``url_pattern``.
Given a buffer as ``log``, parse the log buffer into
a mapping of ident-hashes to a hit count,
the timestamp of the initial log,
and the last timestamp in the log.
"""
hits = {}
initial_timestamp = None
... | python | def parse_log(log, url_pattern):
"""Parse ``log`` buffer based on ``url_pattern``.
Given a buffer as ``log``, parse the log buffer into
a mapping of ident-hashes to a hit count,
the timestamp of the initial log,
and the last timestamp in the log.
"""
hits = {}
initial_timestamp = None
... | [
"def",
"parse_log",
"(",
"log",
",",
"url_pattern",
")",
":",
"hits",
"=",
"{",
"}",
"initial_timestamp",
"=",
"None",
"def",
"clean_timestamp",
"(",
"v",
")",
":",
"return",
"' '",
".",
"join",
"(",
"v",
")",
".",
"strip",
"(",
"'[]'",
")",
"for",
... | Parse ``log`` buffer based on ``url_pattern``.
Given a buffer as ``log``, parse the log buffer into
a mapping of ident-hashes to a hit count,
the timestamp of the initial log,
and the last timestamp in the log. | [
"Parse",
"log",
"buffer",
"based",
"on",
"url_pattern",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/hits_counter.py#L34-L58 |
openstax/cnx-archive | cnxarchive/scripts/hits_counter.py | main | def main(argv=None):
"""Count the hits from logfile."""
parser = create_parser('hits_counter', description=__doc__)
parser.add_argument('--hostname', default='cnx.org',
help="hostname of the site (default: cnx.org)")
parser.add_argument('--log-format',
def... | python | def main(argv=None):
"""Count the hits from logfile."""
parser = create_parser('hits_counter', description=__doc__)
parser.add_argument('--hostname', default='cnx.org',
help="hostname of the site (default: cnx.org)")
parser.add_argument('--log-format',
def... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"create_parser",
"(",
"'hits_counter'",
",",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'--hostname'",
",",
"default",
"=",
"'cnx.org'",
",",
"help",
"=",
"\"ho... | Count the hits from logfile. | [
"Count",
"the",
"hits",
"from",
"logfile",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/scripts/hits_counter.py#L61-L103 |
ZELLMECHANIK-DRESDEN/dclab | dclab/parse_funcs.py | fbool | def fbool(value):
"""boolean"""
if isinstance(value, str_types):
value = value.lower()
if value == "false":
value = False
elif value == "true":
value = True
elif value:
value = bool(float(value))
else:
raise ValueError("empt... | python | def fbool(value):
"""boolean"""
if isinstance(value, str_types):
value = value.lower()
if value == "false":
value = False
elif value == "true":
value = True
elif value:
value = bool(float(value))
else:
raise ValueError("empt... | [
"def",
"fbool",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str_types",
")",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"if",
"value",
"==",
"\"false\"",
":",
"value",
"=",
"False",
"elif",
"value",
"==",
"\"true\"",
":",... | boolean | [
"boolean"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/parse_funcs.py#L8-L22 |
ZELLMECHANIK-DRESDEN/dclab | dclab/parse_funcs.py | fint | def fint(value):
"""integer"""
if isinstance(value, str_types):
# strings might have been saved wrongly as booleans
value = value.lower()
if value == "false":
value = 0
elif value == "true":
value = 1
elif value:
value = int(float(value... | python | def fint(value):
"""integer"""
if isinstance(value, str_types):
# strings might have been saved wrongly as booleans
value = value.lower()
if value == "false":
value = 0
elif value == "true":
value = 1
elif value:
value = int(float(value... | [
"def",
"fint",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str_types",
")",
":",
"# strings might have been saved wrongly as booleans",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"if",
"value",
"==",
"\"false\"",
":",
"value",
"=",
"0... | integer | [
"integer"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/parse_funcs.py#L25-L40 |
ZELLMECHANIK-DRESDEN/dclab | dclab/parse_funcs.py | fintlist | def fintlist(alist):
"""A list of integers"""
outlist = []
if not isinstance(alist, (list, tuple)):
# we have a string (comma-separated integers)
alist = alist.strip().strip("[] ").split(",")
for it in alist:
if it:
outlist.append(fint(it))
return outlist | python | def fintlist(alist):
"""A list of integers"""
outlist = []
if not isinstance(alist, (list, tuple)):
# we have a string (comma-separated integers)
alist = alist.strip().strip("[] ").split(",")
for it in alist:
if it:
outlist.append(fint(it))
return outlist | [
"def",
"fintlist",
"(",
"alist",
")",
":",
"outlist",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"alist",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"# we have a string (comma-separated integers)",
"alist",
"=",
"alist",
".",
"strip",
"(",
")",
"... | A list of integers | [
"A",
"list",
"of",
"integers"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/parse_funcs.py#L43-L52 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/export.py | Export.avi | def avi(self, path, filtered=True, override=False):
"""Exports filtered event images to an avi file
Parameters
----------
path: str
Path to a .tsv file. The ending .tsv is added automatically.
filtered: bool
If set to `True`, only the filtered data (index... | python | def avi(self, path, filtered=True, override=False):
"""Exports filtered event images to an avi file
Parameters
----------
path: str
Path to a .tsv file. The ending .tsv is added automatically.
filtered: bool
If set to `True`, only the filtered data (index... | [
"def",
"avi",
"(",
"self",
",",
"path",
",",
"filtered",
"=",
"True",
",",
"override",
"=",
"False",
")",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"path",
")",
"ds",
"=",
"self",
".",
"rtdc_ds",
"# Make sure that path ends with .avi",
"if",
"path",... | Exports filtered event images to an avi file
Parameters
----------
path: str
Path to a .tsv file. The ending .tsv is added automatically.
filtered: bool
If set to `True`, only the filtered data (index in ds._filter)
are used.
override: bool
... | [
"Exports",
"filtered",
"event",
"images",
"to",
"an",
"avi",
"file"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/export.py#L26-L85 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/export.py | Export.fcs | def fcs(self, path, features, filtered=True, override=False):
"""Export the data of an RT-DC dataset to an .fcs file
Parameters
----------
mm: instance of dclab.RTDCBase
The dataset that will be exported.
path: str
Path to a .tsv file. The ending .tsv is ... | python | def fcs(self, path, features, filtered=True, override=False):
"""Export the data of an RT-DC dataset to an .fcs file
Parameters
----------
mm: instance of dclab.RTDCBase
The dataset that will be exported.
path: str
Path to a .tsv file. The ending .tsv is ... | [
"def",
"fcs",
"(",
"self",
",",
"path",
",",
"features",
",",
"filtered",
"=",
"True",
",",
"override",
"=",
"False",
")",
":",
"features",
"=",
"[",
"c",
".",
"lower",
"(",
")",
"for",
"c",
"in",
"features",
"]",
"ds",
"=",
"self",
".",
"rtdc_ds... | Export the data of an RT-DC dataset to an .fcs file
Parameters
----------
mm: instance of dclab.RTDCBase
The dataset that will be exported.
path: str
Path to a .tsv file. The ending .tsv is added automatically.
features: list of str
The featur... | [
"Export",
"the",
"data",
"of",
"an",
"RT",
"-",
"DC",
"dataset",
"to",
"an",
".",
"fcs",
"file"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/export.py#L87-L142 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/export.py | Export.hdf5 | def hdf5(self, path, features, filtered=True, override=False,
compression="gzip"):
"""Export the data of the current instance to an HDF5 file
Parameters
----------
path: str
Path to an .rtdc file. The ending .rtdc is added
automatically.
feat... | python | def hdf5(self, path, features, filtered=True, override=False,
compression="gzip"):
"""Export the data of the current instance to an HDF5 file
Parameters
----------
path: str
Path to an .rtdc file. The ending .rtdc is added
automatically.
feat... | [
"def",
"hdf5",
"(",
"self",
",",
"path",
",",
"features",
",",
"filtered",
"=",
"True",
",",
"override",
"=",
"False",
",",
"compression",
"=",
"\"gzip\"",
")",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"path",
")",
"# Make sure that path ends with .r... | Export the data of the current instance to an HDF5 file
Parameters
----------
path: str
Path to an .rtdc file. The ending .rtdc is added
automatically.
features: list of str
The features in the resulting .tsv file. These are strings
that a... | [
"Export",
"the",
"data",
"of",
"the",
"current",
"instance",
"to",
"an",
"HDF5",
"file"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/export.py#L144-L263 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/export.py | Export.tsv | def tsv(self, path, features, filtered=True, override=False):
"""Export the data of the current instance to a .tsv file
Parameters
----------
path: str
Path to a .tsv file. The ending .tsv is added automatically.
features: list of str
The features in the ... | python | def tsv(self, path, features, filtered=True, override=False):
"""Export the data of the current instance to a .tsv file
Parameters
----------
path: str
Path to a .tsv file. The ending .tsv is added automatically.
features: list of str
The features in the ... | [
"def",
"tsv",
"(",
"self",
",",
"path",
",",
"features",
",",
"filtered",
"=",
"True",
",",
"override",
"=",
"False",
")",
":",
"features",
"=",
"[",
"c",
".",
"lower",
"(",
")",
"for",
"c",
"in",
"features",
"]",
"path",
"=",
"pathlib",
".",
"Pa... | Export the data of the current instance to a .tsv file
Parameters
----------
path: str
Path to a .tsv file. The ending .tsv is added automatically.
features: list of str
The features in the resulting .tsv file. These are strings
that are defined in `d... | [
"Export",
"the",
"data",
"of",
"the",
"current",
"instance",
"to",
"a",
".",
"tsv",
"file"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/export.py#L265-L317 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/util.py | hashfile | def hashfile(fname, blocksize=65536, count=0):
"""Compute md5 hex-hash of a file
Parameters
----------
fname: str
path to the file
blocksize: int
block size in bytes read from the file
(set to `0` to hash the entire file)
count: int
number of blocks read from the... | python | def hashfile(fname, blocksize=65536, count=0):
"""Compute md5 hex-hash of a file
Parameters
----------
fname: str
path to the file
blocksize: int
block size in bytes read from the file
(set to `0` to hash the entire file)
count: int
number of blocks read from the... | [
"def",
"hashfile",
"(",
"fname",
",",
"blocksize",
"=",
"65536",
",",
"count",
"=",
"0",
")",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"fname",
"=",
"pathlib",
".",
"Path",
"(",
"fname",
")",
"with",
"fname",
".",
"open",
"(",
"'rb'",
... | Compute md5 hex-hash of a file
Parameters
----------
fname: str
path to the file
blocksize: int
block size in bytes read from the file
(set to `0` to hash the entire file)
count: int
number of blocks read from the file | [
"Compute",
"md5",
"hex",
"-",
"hash",
"of",
"a",
"file"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/util.py#L15-L39 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/util.py | obj2str | def obj2str(obj):
"""String representation of an object for hashing"""
if isinstance(obj, str_types):
return obj.encode("utf-8")
elif isinstance(obj, pathlib.Path):
return obj2str(str(obj))
elif isinstance(obj, (bool, int, float)):
return str(obj).encode("utf-8")
elif obj is ... | python | def obj2str(obj):
"""String representation of an object for hashing"""
if isinstance(obj, str_types):
return obj.encode("utf-8")
elif isinstance(obj, pathlib.Path):
return obj2str(str(obj))
elif isinstance(obj, (bool, int, float)):
return str(obj).encode("utf-8")
elif obj is ... | [
"def",
"obj2str",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str_types",
")",
":",
"return",
"obj",
".",
"encode",
"(",
"\"utf-8\"",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"pathlib",
".",
"Path",
")",
":",
"return",
"obj2str",
"... | String representation of an object for hashing | [
"String",
"representation",
"of",
"an",
"object",
"for",
"hashing"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/util.py#L47-L71 |
xenon-middleware/pyxenon | xenon/create_keys.py | create_self_signed_cert | def create_self_signed_cert():
"""Creates a self-signed certificate key pair."""
config_dir = Path(BaseDirectory.xdg_config_home) / 'xenon-grpc'
config_dir.mkdir(parents=True, exist_ok=True)
key_prefix = gethostname()
crt_file = config_dir / ('%s.crt' % key_prefix)
key_file = config_dir / ('%s.... | python | def create_self_signed_cert():
"""Creates a self-signed certificate key pair."""
config_dir = Path(BaseDirectory.xdg_config_home) / 'xenon-grpc'
config_dir.mkdir(parents=True, exist_ok=True)
key_prefix = gethostname()
crt_file = config_dir / ('%s.crt' % key_prefix)
key_file = config_dir / ('%s.... | [
"def",
"create_self_signed_cert",
"(",
")",
":",
"config_dir",
"=",
"Path",
"(",
"BaseDirectory",
".",
"xdg_config_home",
")",
"/",
"'xenon-grpc'",
"config_dir",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"key_prefix",
"=",
... | Creates a self-signed certificate key pair. | [
"Creates",
"a",
"self",
"-",
"signed",
"certificate",
"key",
"pair",
"."
] | train | https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/create_keys.py#L14-L49 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/fmt_tdms/__init__.py | get_project_name_from_path | def get_project_name_from_path(path, append_mx=False):
"""Get the project name from a path.
For a path "/home/peter/hans/HLC12398/online/M1_13.tdms" or
For a path "/home/peter/hans/HLC12398/online/data/M1_13.tdms" or
without the ".tdms" file, this will return always "HLC12398".
Parameters
----... | python | def get_project_name_from_path(path, append_mx=False):
"""Get the project name from a path.
For a path "/home/peter/hans/HLC12398/online/M1_13.tdms" or
For a path "/home/peter/hans/HLC12398/online/data/M1_13.tdms" or
without the ".tdms" file, this will return always "HLC12398".
Parameters
----... | [
"def",
"get_project_name_from_path",
"(",
"path",
",",
"append_mx",
"=",
"False",
")",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"path",
")",
"if",
"path",
".",
"suffix",
"==",
"\".tdms\"",
":",
"dirn",
"=",
"path",
".",
"parent",
"mx",
"=",
"path... | Get the project name from a path.
For a path "/home/peter/hans/HLC12398/online/M1_13.tdms" or
For a path "/home/peter/hans/HLC12398/online/data/M1_13.tdms" or
without the ".tdms" file, this will return always "HLC12398".
Parameters
----------
path: str
path to tdms file
append_mx: ... | [
"Get",
"the",
"project",
"name",
"from",
"a",
"path",
"."
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/__init__.py#L183-L240 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/fmt_tdms/__init__.py | get_tdms_files | def get_tdms_files(directory):
"""Recursively find projects based on '.tdms' file endings
Searches the `directory` recursively and return a sorted list
of all found '.tdms' project files, except fluorescence
data trace files which end with `_traces.tdms`.
"""
path = pathlib.Path(directory).reso... | python | def get_tdms_files(directory):
"""Recursively find projects based on '.tdms' file endings
Searches the `directory` recursively and return a sorted list
of all found '.tdms' project files, except fluorescence
data trace files which end with `_traces.tdms`.
"""
path = pathlib.Path(directory).reso... | [
"def",
"get_tdms_files",
"(",
"directory",
")",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"directory",
")",
".",
"resolve",
"(",
")",
"# get all tdms files",
"tdmslist",
"=",
"[",
"r",
"for",
"r",
"in",
"path",
".",
"rglob",
"(",
"\"*.tdms\"",
")",
... | Recursively find projects based on '.tdms' file endings
Searches the `directory` recursively and return a sorted list
of all found '.tdms' project files, except fluorescence
data trace files which end with `_traces.tdms`. | [
"Recursively",
"find",
"projects",
"based",
"on",
".",
"tdms",
"file",
"endings"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/__init__.py#L243-L255 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/fmt_tdms/__init__.py | RTDC_TDMS._init_data_with_tdms | def _init_data_with_tdms(self, tdms_filename):
"""Initializes the current RT-DC dataset with a tdms file.
"""
tdms_file = TdmsFile(str(tdms_filename))
# time is always there
table = "Cell Track"
# Edit naming.dclab2tdms to add features
for arg in naming.tdms2dclab... | python | def _init_data_with_tdms(self, tdms_filename):
"""Initializes the current RT-DC dataset with a tdms file.
"""
tdms_file = TdmsFile(str(tdms_filename))
# time is always there
table = "Cell Track"
# Edit naming.dclab2tdms to add features
for arg in naming.tdms2dclab... | [
"def",
"_init_data_with_tdms",
"(",
"self",
",",
"tdms_filename",
")",
":",
"tdms_file",
"=",
"TdmsFile",
"(",
"str",
"(",
"tdms_filename",
")",
")",
"# time is always there",
"table",
"=",
"\"Cell Track\"",
"# Edit naming.dclab2tdms to add features",
"for",
"arg",
"i... | Initializes the current RT-DC dataset with a tdms file. | [
"Initializes",
"the",
"current",
"RT",
"-",
"DC",
"dataset",
"with",
"a",
"tdms",
"file",
"."
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/__init__.py#L69-L111 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/fmt_tdms/__init__.py | RTDC_TDMS.hash | def hash(self):
"""Hash value based on file name and .ini file content"""
if self._hash is None:
# Only hash _camera.ini and _para.ini
fsh = [self.path.with_name(self._mid + "_camera.ini"),
self.path.with_name(self._mid + "_para.ini")]
tohash = [has... | python | def hash(self):
"""Hash value based on file name and .ini file content"""
if self._hash is None:
# Only hash _camera.ini and _para.ini
fsh = [self.path.with_name(self._mid + "_camera.ini"),
self.path.with_name(self._mid + "_para.ini")]
tohash = [has... | [
"def",
"hash",
"(",
"self",
")",
":",
"if",
"self",
".",
"_hash",
"is",
"None",
":",
"# Only hash _camera.ini and _para.ini",
"fsh",
"=",
"[",
"self",
".",
"path",
".",
"with_name",
"(",
"self",
".",
"_mid",
"+",
"\"_camera.ini\"",
")",
",",
"self",
".",... | Hash value based on file name and .ini file content | [
"Hash",
"value",
"based",
"on",
"file",
"name",
"and",
".",
"ini",
"file",
"content"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/__init__.py#L169-L180 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/fmt_tdms/event_contour.py | ContourColumn.determine_offset | def determine_offset(self):
"""Determines the offset of the contours w.r.t. other data columns
Notes
-----
- the "frame" column of `rtdc_dataset` is compared to
the first contour in the contour text file to determine an
offset by one event
- modifies the pro... | python | def determine_offset(self):
"""Determines the offset of the contours w.r.t. other data columns
Notes
-----
- the "frame" column of `rtdc_dataset` is compared to
the first contour in the contour text file to determine an
offset by one event
- modifies the pro... | [
"def",
"determine_offset",
"(",
"self",
")",
":",
"# In case of regular RTDC, the first contour is",
"# missing. In case of fRTDC, it is there, so we",
"# might have an offset. We find out if the first",
"# contour frame is missing by comparing it to",
"# the \"frame\" column of the rtdc dataset... | Determines the offset of the contours w.r.t. other data columns
Notes
-----
- the "frame" column of `rtdc_dataset` is compared to
the first contour in the contour text file to determine an
offset by one event
- modifies the property `event_offset` and sets `_initial... | [
"Determines",
"the",
"offset",
"of",
"the",
"contours",
"w",
".",
"r",
".",
"t",
".",
"other",
"data",
"columns"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/event_contour.py#L61-L89 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/fmt_tdms/event_contour.py | ContourColumn.find_contour_file | def find_contour_file(rtdc_dataset):
"""Tries to find a contour file that belongs to an RTDC dataset
Returns None if no contour file is found.
"""
cont_id = rtdc_dataset.path.stem
cands = [c.name for c in rtdc_dataset._fdir.rglob("*_contours.txt")]
cands = sorted(cands)
... | python | def find_contour_file(rtdc_dataset):
"""Tries to find a contour file that belongs to an RTDC dataset
Returns None if no contour file is found.
"""
cont_id = rtdc_dataset.path.stem
cands = [c.name for c in rtdc_dataset._fdir.rglob("*_contours.txt")]
cands = sorted(cands)
... | [
"def",
"find_contour_file",
"(",
"rtdc_dataset",
")",
":",
"cont_id",
"=",
"rtdc_dataset",
".",
"path",
".",
"stem",
"cands",
"=",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"rtdc_dataset",
".",
"_fdir",
".",
"rglob",
"(",
"\"*_contours.txt\"",
")",
"]",
"... | Tries to find a contour file that belongs to an RTDC dataset
Returns None if no contour file is found. | [
"Tries",
"to",
"find",
"a",
"contour",
"file",
"that",
"belongs",
"to",
"an",
"RTDC",
"dataset"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/event_contour.py#L92-L120 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/fmt_tdms/event_contour.py | ContourData._index_file | def _index_file(self):
"""Open and index the contour file
This function populates the internal list of contours
as strings which will be available as `self.data`.
"""
with self.filename.open() as fd:
data = fd.read()
ident = "Contour in frame"
self._... | python | def _index_file(self):
"""Open and index the contour file
This function populates the internal list of contours
as strings which will be available as `self.data`.
"""
with self.filename.open() as fd:
data = fd.read()
ident = "Contour in frame"
self._... | [
"def",
"_index_file",
"(",
"self",
")",
":",
"with",
"self",
".",
"filename",
".",
"open",
"(",
")",
"as",
"fd",
":",
"data",
"=",
"fd",
".",
"read",
"(",
")",
"ident",
"=",
"\"Contour in frame\"",
"self",
".",
"_data",
"=",
"data",
".",
"split",
"... | Open and index the contour file
This function populates the internal list of contours
as strings which will be available as `self.data`. | [
"Open",
"and",
"index",
"the",
"contour",
"file"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/event_contour.py#L152-L163 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/fmt_tdms/event_contour.py | ContourData.get_frame | def get_frame(self, idx):
"""Return the frame number of a contour"""
cont = self.data[idx]
frame = int(cont.strip().split(" ", 1)[0])
return frame | python | def get_frame(self, idx):
"""Return the frame number of a contour"""
cont = self.data[idx]
frame = int(cont.strip().split(" ", 1)[0])
return frame | [
"def",
"get_frame",
"(",
"self",
",",
"idx",
")",
":",
"cont",
"=",
"self",
".",
"data",
"[",
"idx",
"]",
"frame",
"=",
"int",
"(",
"cont",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\" \"",
",",
"1",
")",
"[",
"0",
"]",
")",
"return",
"fram... | Return the frame number of a contour | [
"Return",
"the",
"frame",
"number",
"of",
"a",
"contour"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_tdms/event_contour.py#L175-L179 |
ZELLMECHANIK-DRESDEN/dclab | dclab/features/emodulus_viscosity.py | get_viscosity | def get_viscosity(medium="CellCarrier", channel_width=20.0, flow_rate=0.16,
temperature=23.0):
"""Returns the viscosity for RT-DC-specific media
Parameters
----------
medium: str
The medium to compute the viscosity for.
One of ["CellCarrier", "CellCarrier B", "water"].... | python | def get_viscosity(medium="CellCarrier", channel_width=20.0, flow_rate=0.16,
temperature=23.0):
"""Returns the viscosity for RT-DC-specific media
Parameters
----------
medium: str
The medium to compute the viscosity for.
One of ["CellCarrier", "CellCarrier B", "water"].... | [
"def",
"get_viscosity",
"(",
"medium",
"=",
"\"CellCarrier\"",
",",
"channel_width",
"=",
"20.0",
",",
"flow_rate",
"=",
"0.16",
",",
"temperature",
"=",
"23.0",
")",
":",
"if",
"medium",
".",
"lower",
"(",
")",
"not",
"in",
"[",
"\"cellcarrier\"",
",",
... | Returns the viscosity for RT-DC-specific media
Parameters
----------
medium: str
The medium to compute the viscosity for.
One of ["CellCarrier", "CellCarrier B", "water"].
channel_width: float
The channel width in µm
flow_rate: float
Flow rate in µl/s
temperature... | [
"Returns",
"the",
"viscosity",
"for",
"RT",
"-",
"DC",
"-",
"specific",
"media"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/emodulus_viscosity.py#L9-L66 |
ZELLMECHANIK-DRESDEN/dclab | dclab/statistics.py | get_statistics | def get_statistics(ds, methods=None, features=None):
"""Compute statistics for an RT-DC dataset
Parameters
----------
ds: dclab.rtdc_dataset.RTDCBase
The dataset for which to compute the statistics.
methods: list of str or None
The methods wih which to compute the statistics.
... | python | def get_statistics(ds, methods=None, features=None):
"""Compute statistics for an RT-DC dataset
Parameters
----------
ds: dclab.rtdc_dataset.RTDCBase
The dataset for which to compute the statistics.
methods: list of str or None
The methods wih which to compute the statistics.
... | [
"def",
"get_statistics",
"(",
"ds",
",",
"methods",
"=",
"None",
",",
"features",
"=",
"None",
")",
":",
"if",
"methods",
"is",
"None",
":",
"cls",
"=",
"list",
"(",
"Statistics",
".",
"available_methods",
".",
"keys",
"(",
")",
")",
"# sort the features... | Compute statistics for an RT-DC dataset
Parameters
----------
ds: dclab.rtdc_dataset.RTDCBase
The dataset for which to compute the statistics.
methods: list of str or None
The methods wih which to compute the statistics.
The list of available methods is given with
`dclab... | [
"Compute",
"statistics",
"for",
"an",
"RT",
"-",
"DC",
"dataset"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/statistics.py#L92-L150 |
ZELLMECHANIK-DRESDEN/dclab | dclab/statistics.py | mode | def mode(data):
"""Compute an intelligent value for the mode
The most common value in experimental is not very useful if there
are a lot of digits after the comma. This method approaches this
issue by rounding to bin size that is determined by the
Freedman–Diaconis rule.
Parameters
-------... | python | def mode(data):
"""Compute an intelligent value for the mode
The most common value in experimental is not very useful if there
are a lot of digits after the comma. This method approaches this
issue by rounding to bin size that is determined by the
Freedman–Diaconis rule.
Parameters
-------... | [
"def",
"mode",
"(",
"data",
")",
":",
"# size",
"n",
"=",
"data",
".",
"shape",
"[",
"0",
"]",
"# interquartile range",
"iqr",
"=",
"np",
".",
"percentile",
"(",
"data",
",",
"75",
")",
"-",
"np",
".",
"percentile",
"(",
"data",
",",
"25",
")",
"... | Compute an intelligent value for the mode
The most common value in experimental is not very useful if there
are a lot of digits after the comma. This method approaches this
issue by rounding to bin size that is determined by the
Freedman–Diaconis rule.
Parameters
----------
data: 1d ndarra... | [
"Compute",
"an",
"intelligent",
"value",
"for",
"the",
"mode"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/statistics.py#L153-L187 |
ZELLMECHANIK-DRESDEN/dclab | dclab/statistics.py | Statistics._get_data | def _get_data(self, kwargs):
"""Convenience wrapper to get statistics data"""
if "ds" not in kwargs:
raise ValueError("Keyword argument 'ds' missing.")
ds = kwargs["ds"]
if self.req_feature:
if "feature" not in kwargs:
raise ValueError("Keyword a... | python | def _get_data(self, kwargs):
"""Convenience wrapper to get statistics data"""
if "ds" not in kwargs:
raise ValueError("Keyword argument 'ds' missing.")
ds = kwargs["ds"]
if self.req_feature:
if "feature" not in kwargs:
raise ValueError("Keyword a... | [
"def",
"_get_data",
"(",
"self",
",",
"kwargs",
")",
":",
"if",
"\"ds\"",
"not",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"Keyword argument 'ds' missing.\"",
")",
"ds",
"=",
"kwargs",
"[",
"\"ds\"",
"]",
"if",
"self",
".",
"req_feature",
":",
"if... | Convenience wrapper to get statistics data | [
"Convenience",
"wrapper",
"to",
"get",
"statistics",
"data"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/statistics.py#L46-L58 |
ZELLMECHANIK-DRESDEN/dclab | dclab/statistics.py | Statistics.get_feature | def get_feature(self, ds, feat):
"""Return filtered feature data
The features are filtered according to the user-defined filters,
using the information in `ds._filter`. In addition, all
`nan` and `inf` values are purged.
Parameters
----------
ds: dclab.rtdc_data... | python | def get_feature(self, ds, feat):
"""Return filtered feature data
The features are filtered according to the user-defined filters,
using the information in `ds._filter`. In addition, all
`nan` and `inf` values are purged.
Parameters
----------
ds: dclab.rtdc_data... | [
"def",
"get_feature",
"(",
"self",
",",
"ds",
",",
"feat",
")",
":",
"if",
"ds",
".",
"config",
"[",
"\"filtering\"",
"]",
"[",
"\"enable filters\"",
"]",
":",
"x",
"=",
"ds",
"[",
"feat",
"]",
"[",
"ds",
".",
"_filter",
"]",
"else",
":",
"x",
"=... | Return filtered feature data
The features are filtered according to the user-defined filters,
using the information in `ds._filter`. In addition, all
`nan` and `inf` values are purged.
Parameters
----------
ds: dclab.rtdc_dataset.RTDCBase
The dataset contain... | [
"Return",
"filtered",
"feature",
"data"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/statistics.py#L60-L80 |
kpn-digital/py-timeexecution | time_execution/decorator.py | time_execution.get_exception | def get_exception(self):
"""Retrieve the exception"""
if self.exc_info:
try:
six.reraise(*self.exc_info)
except Exception as e:
return e | python | def get_exception(self):
"""Retrieve the exception"""
if self.exc_info:
try:
six.reraise(*self.exc_info)
except Exception as e:
return e | [
"def",
"get_exception",
"(",
"self",
")",
":",
"if",
"self",
".",
"exc_info",
":",
"try",
":",
"six",
".",
"reraise",
"(",
"*",
"self",
".",
"exc_info",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"e"
] | Retrieve the exception | [
"Retrieve",
"the",
"exception"
] | train | https://github.com/kpn-digital/py-timeexecution/blob/79b991e83f783196c41b830d0acef21ac5462596/time_execution/decorator.py#L72-L78 |
capless/sammy | sammy/__init__.py | SAM.check_global_valid | def check_global_valid(self):
"""
Makes sure there aren't any SAM resources in a template that will be used in a CloudFormation StackSet
:return: bool
"""
serverless_cnt = len(list(filter(lambda x: x._serverless_type, self._data['resources'])))
if serverless_cnt > 0:
... | python | def check_global_valid(self):
"""
Makes sure there aren't any SAM resources in a template that will be used in a CloudFormation StackSet
:return: bool
"""
serverless_cnt = len(list(filter(lambda x: x._serverless_type, self._data['resources'])))
if serverless_cnt > 0:
... | [
"def",
"check_global_valid",
"(",
"self",
")",
":",
"serverless_cnt",
"=",
"len",
"(",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"_serverless_type",
",",
"self",
".",
"_data",
"[",
"'resources'",
"]",
")",
")",
")",
"if",
"serverless_cnt"... | Makes sure there aren't any SAM resources in a template that will be used in a CloudFormation StackSet
:return: bool | [
"Makes",
"sure",
"there",
"aren",
"t",
"any",
"SAM",
"resources",
"in",
"a",
"template",
"that",
"will",
"be",
"used",
"in",
"a",
"CloudFormation",
"StackSet",
":",
"return",
":",
"bool"
] | train | https://github.com/capless/sammy/blob/4fa9680ccfad108537de7de08e70644ac13bc8e8/sammy/__init__.py#L433-L441 |
capless/sammy | sammy/__init__.py | SAM.has_stack | def has_stack(self, stack_name):
"""
Checks if a CloudFormation stack with given name exists
:param stack_name: Name or ID of the stack
:return: True if stack exists. False otherwise
"""
cf = self.cf_client
try:
resp = cf.describe_stacks(StackName=stac... | python | def has_stack(self, stack_name):
"""
Checks if a CloudFormation stack with given name exists
:param stack_name: Name or ID of the stack
:return: True if stack exists. False otherwise
"""
cf = self.cf_client
try:
resp = cf.describe_stacks(StackName=stac... | [
"def",
"has_stack",
"(",
"self",
",",
"stack_name",
")",
":",
"cf",
"=",
"self",
".",
"cf_client",
"try",
":",
"resp",
"=",
"cf",
".",
"describe_stacks",
"(",
"StackName",
"=",
"stack_name",
")",
"if",
"len",
"(",
"resp",
"[",
"\"Stacks\"",
"]",
")",
... | Checks if a CloudFormation stack with given name exists
:param stack_name: Name or ID of the stack
:return: True if stack exists. False otherwise | [
"Checks",
"if",
"a",
"CloudFormation",
"stack",
"with",
"given",
"name",
"exists",
":",
"param",
"stack_name",
":",
"Name",
"or",
"ID",
"of",
"the",
"stack",
":",
"return",
":",
"True",
"if",
"stack",
"exists",
".",
"False",
"otherwise"
] | train | https://github.com/capless/sammy/blob/4fa9680ccfad108537de7de08e70644ac13bc8e8/sammy/__init__.py#L480-L514 |
mhostetter/nhl | nhl/flyweight.py | Flyweight.has_key | def has_key(cls, *args):
"""
Check whether flyweight object with specified key has already been created.
Returns:
bool: True if already created, False if not
"""
key = args if len(args) > 1 else args[0]
return key in cls._instances | python | def has_key(cls, *args):
"""
Check whether flyweight object with specified key has already been created.
Returns:
bool: True if already created, False if not
"""
key = args if len(args) > 1 else args[0]
return key in cls._instances | [
"def",
"has_key",
"(",
"cls",
",",
"*",
"args",
")",
":",
"key",
"=",
"args",
"if",
"len",
"(",
"args",
")",
">",
"1",
"else",
"args",
"[",
"0",
"]",
"return",
"key",
"in",
"cls",
".",
"_instances"
] | Check whether flyweight object with specified key has already been created.
Returns:
bool: True if already created, False if not | [
"Check",
"whether",
"flyweight",
"object",
"with",
"specified",
"key",
"has",
"already",
"been",
"created",
"."
] | train | https://github.com/mhostetter/nhl/blob/32c91cc392826e9de728563d57ab527421734ee1/nhl/flyweight.py#L42-L50 |
mhostetter/nhl | nhl/flyweight.py | Flyweight.from_key | def from_key(cls, *args):
"""
Return flyweight object with specified key, if it has already been created.
Returns:
cls or None: Previously constructed flyweight object with given
key or None if key not found
"""
key = args if len(args) > 1 else args[0]
... | python | def from_key(cls, *args):
"""
Return flyweight object with specified key, if it has already been created.
Returns:
cls or None: Previously constructed flyweight object with given
key or None if key not found
"""
key = args if len(args) > 1 else args[0]
... | [
"def",
"from_key",
"(",
"cls",
",",
"*",
"args",
")",
":",
"key",
"=",
"args",
"if",
"len",
"(",
"args",
")",
">",
"1",
"else",
"args",
"[",
"0",
"]",
"return",
"cls",
".",
"_instances",
".",
"get",
"(",
"key",
",",
"None",
")"
] | Return flyweight object with specified key, if it has already been created.
Returns:
cls or None: Previously constructed flyweight object with given
key or None if key not found | [
"Return",
"flyweight",
"object",
"with",
"specified",
"key",
"if",
"it",
"has",
"already",
"been",
"created",
"."
] | train | https://github.com/mhostetter/nhl/blob/32c91cc392826e9de728563d57ab527421734ee1/nhl/flyweight.py#L53-L62 |
kpn-digital/py-timeexecution | time_execution/backends/elasticsearch.py | ElasticsearchBackend.write | def write(self, name, **data):
"""
Write the metric to elasticsearch
Args:
name (str): The name of the metric to write
data (dict): Additional data to store with the metric
"""
data["name"] = name
if not ("timestamp" in data):
data["t... | python | def write(self, name, **data):
"""
Write the metric to elasticsearch
Args:
name (str): The name of the metric to write
data (dict): Additional data to store with the metric
"""
data["name"] = name
if not ("timestamp" in data):
data["t... | [
"def",
"write",
"(",
"self",
",",
"name",
",",
"*",
"*",
"data",
")",
":",
"data",
"[",
"\"name\"",
"]",
"=",
"name",
"if",
"not",
"(",
"\"timestamp\"",
"in",
"data",
")",
":",
"data",
"[",
"\"timestamp\"",
"]",
"=",
"datetime",
".",
"utcnow",
"(",... | Write the metric to elasticsearch
Args:
name (str): The name of the metric to write
data (dict): Additional data to store with the metric | [
"Write",
"the",
"metric",
"to",
"elasticsearch"
] | train | https://github.com/kpn-digital/py-timeexecution/blob/79b991e83f783196c41b830d0acef21ac5462596/time_execution/backends/elasticsearch.py#L87-L108 |
kpn-digital/py-timeexecution | time_execution/backends/elasticsearch.py | ElasticsearchBackend.bulk_write | def bulk_write(self, metrics):
"""
Write multiple metrics to elasticsearch in one request
Args:
metrics (list): data with mappings to send to elasticsearch
"""
actions = []
index = self.get_index()
for metric in metrics:
actions.append({'i... | python | def bulk_write(self, metrics):
"""
Write multiple metrics to elasticsearch in one request
Args:
metrics (list): data with mappings to send to elasticsearch
"""
actions = []
index = self.get_index()
for metric in metrics:
actions.append({'i... | [
"def",
"bulk_write",
"(",
"self",
",",
"metrics",
")",
":",
"actions",
"=",
"[",
"]",
"index",
"=",
"self",
".",
"get_index",
"(",
")",
"for",
"metric",
"in",
"metrics",
":",
"actions",
".",
"append",
"(",
"{",
"'index'",
":",
"{",
"'_index'",
":",
... | Write multiple metrics to elasticsearch in one request
Args:
metrics (list): data with mappings to send to elasticsearch | [
"Write",
"multiple",
"metrics",
"to",
"elasticsearch",
"in",
"one",
"request"
] | train | https://github.com/kpn-digital/py-timeexecution/blob/79b991e83f783196c41b830d0acef21ac5462596/time_execution/backends/elasticsearch.py#L110-L125 |
ZELLMECHANIK-DRESDEN/dclab | dclab/features/bright.py | get_bright | def get_bright(mask, image, ret_data="avg,sd"):
"""Compute avg and/or std of the event brightness
The event brightness is defined by the gray-scale values of the
image data within the event mask area.
Parameters
----------
mask: ndarray or list of ndarrays of shape (M,N) and dtype bool
... | python | def get_bright(mask, image, ret_data="avg,sd"):
"""Compute avg and/or std of the event brightness
The event brightness is defined by the gray-scale values of the
image data within the event mask area.
Parameters
----------
mask: ndarray or list of ndarrays of shape (M,N) and dtype bool
... | [
"def",
"get_bright",
"(",
"mask",
",",
"image",
",",
"ret_data",
"=",
"\"avg,sd\"",
")",
":",
"# This method is based on a pull request by Maik Herbig.",
"ret_avg",
"=",
"\"avg\"",
"in",
"ret_data",
"ret_std",
"=",
"\"sd\"",
"in",
"ret_data",
"if",
"ret_avg",
"+",
... | Compute avg and/or std of the event brightness
The event brightness is defined by the gray-scale values of the
image data within the event mask area.
Parameters
----------
mask: ndarray or list of ndarrays of shape (M,N) and dtype bool
The mask values, True where the event is located in `i... | [
"Compute",
"avg",
"and",
"/",
"or",
"std",
"of",
"the",
"event",
"brightness"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/bright.py#L12-L85 |
openstax/cnx-archive | cnxarchive/cache.py | search | def search(query, query_type, nocache=False):
"""Search archive contents.
Look up search results in cache, if not in cache,
do a database search and cache the result
"""
settings = get_current_registry().settings
memcache_servers = settings['memcache-servers'].split()
if not memcache_server... | python | def search(query, query_type, nocache=False):
"""Search archive contents.
Look up search results in cache, if not in cache,
do a database search and cache the result
"""
settings = get_current_registry().settings
memcache_servers = settings['memcache-servers'].split()
if not memcache_server... | [
"def",
"search",
"(",
"query",
",",
"query_type",
",",
"nocache",
"=",
"False",
")",
":",
"settings",
"=",
"get_current_registry",
"(",
")",
".",
"settings",
"memcache_servers",
"=",
"settings",
"[",
"'memcache-servers'",
"]",
".",
"split",
"(",
")",
"if",
... | Search archive contents.
Look up search results in cache, if not in cache,
do a database search and cache the result | [
"Search",
"archive",
"contents",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/cache.py#L20-L79 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/ancillaries/ancillary_feature.py | AncillaryFeature.available_features | def available_features(rtdc_ds):
"""Determine available features for an RT-DC dataset
Parameters
----------
rtdc_ds: instance of RTDCBase
The dataset to check availability for
Returns
-------
features: dict
Dictionary with feature names a... | python | def available_features(rtdc_ds):
"""Determine available features for an RT-DC dataset
Parameters
----------
rtdc_ds: instance of RTDCBase
The dataset to check availability for
Returns
-------
features: dict
Dictionary with feature names a... | [
"def",
"available_features",
"(",
"rtdc_ds",
")",
":",
"cols",
"=",
"{",
"}",
"for",
"inst",
"in",
"AncillaryFeature",
".",
"features",
":",
"if",
"inst",
".",
"is_available",
"(",
"rtdc_ds",
")",
":",
"cols",
"[",
"inst",
".",
"feature_name",
"]",
"=",
... | Determine available features for an RT-DC dataset
Parameters
----------
rtdc_ds: instance of RTDCBase
The dataset to check availability for
Returns
-------
features: dict
Dictionary with feature names as keys and instances
of `Ancilla... | [
"Determine",
"available",
"features",
"for",
"an",
"RT",
"-",
"DC",
"dataset"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/ancillaries/ancillary_feature.py#L85-L103 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/ancillaries/ancillary_feature.py | AncillaryFeature.compute | def compute(self, rtdc_ds):
"""Compute the feature with self.method
Parameters
----------
rtdc_ds: instance of RTDCBase
The dataset to compute the feature for
Returns
-------
feature: array- or list-like
The computed data feature (read-on... | python | def compute(self, rtdc_ds):
"""Compute the feature with self.method
Parameters
----------
rtdc_ds: instance of RTDCBase
The dataset to compute the feature for
Returns
-------
feature: array- or list-like
The computed data feature (read-on... | [
"def",
"compute",
"(",
"self",
",",
"rtdc_ds",
")",
":",
"data",
"=",
"self",
".",
"method",
"(",
"rtdc_ds",
")",
"dsize",
"=",
"len",
"(",
"rtdc_ds",
")",
"-",
"len",
"(",
"data",
")",
"if",
"dsize",
">",
"0",
":",
"msg",
"=",
"\"Growing feature {... | Compute the feature with self.method
Parameters
----------
rtdc_ds: instance of RTDCBase
The dataset to compute the feature for
Returns
-------
feature: array- or list-like
The computed data feature (read-only). | [
"Compute",
"the",
"feature",
"with",
"self",
".",
"method"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/ancillaries/ancillary_feature.py#L105-L140 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/ancillaries/ancillary_feature.py | AncillaryFeature.get_instances | def get_instances(feature_name):
"""Return all all instances that compute `feature_name`"""
feats = []
for ft in AncillaryFeature.features:
if ft.feature_name == feature_name:
feats.append(ft)
return feats | python | def get_instances(feature_name):
"""Return all all instances that compute `feature_name`"""
feats = []
for ft in AncillaryFeature.features:
if ft.feature_name == feature_name:
feats.append(ft)
return feats | [
"def",
"get_instances",
"(",
"feature_name",
")",
":",
"feats",
"=",
"[",
"]",
"for",
"ft",
"in",
"AncillaryFeature",
".",
"features",
":",
"if",
"ft",
".",
"feature_name",
"==",
"feature_name",
":",
"feats",
".",
"append",
"(",
"ft",
")",
"return",
"fea... | Return all all instances that compute `feature_name` | [
"Return",
"all",
"all",
"instances",
"that",
"compute",
"feature_name"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/ancillaries/ancillary_feature.py#L143-L149 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/ancillaries/ancillary_feature.py | AncillaryFeature.hash | def hash(self, rtdc_ds):
"""Used for identifying an ancillary computation
The data columns and the used configuration keys/values
are hashed.
"""
hasher = hashlib.md5()
# data columns
for col in self.req_features:
hasher.update(obj2str(rtdc_ds[col]))
... | python | def hash(self, rtdc_ds):
"""Used for identifying an ancillary computation
The data columns and the used configuration keys/values
are hashed.
"""
hasher = hashlib.md5()
# data columns
for col in self.req_features:
hasher.update(obj2str(rtdc_ds[col]))
... | [
"def",
"hash",
"(",
"self",
",",
"rtdc_ds",
")",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"# data columns",
"for",
"col",
"in",
"self",
".",
"req_features",
":",
"hasher",
".",
"update",
"(",
"obj2str",
"(",
"rtdc_ds",
"[",
"col",
"]",
")... | Used for identifying an ancillary computation
The data columns and the used configuration keys/values
are hashed. | [
"Used",
"for",
"identifying",
"an",
"ancillary",
"computation"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/ancillaries/ancillary_feature.py#L151-L167 |
ZELLMECHANIK-DRESDEN/dclab | dclab/rtdc_dataset/ancillaries/ancillary_feature.py | AncillaryFeature.is_available | def is_available(self, rtdc_ds, verbose=False):
"""Check whether the feature is available
Parameters
----------
rtdc_ds: instance of RTDCBase
The dataset to check availability for
Returns
-------
available: bool
`True`, if feature can be ... | python | def is_available(self, rtdc_ds, verbose=False):
"""Check whether the feature is available
Parameters
----------
rtdc_ds: instance of RTDCBase
The dataset to check availability for
Returns
-------
available: bool
`True`, if feature can be ... | [
"def",
"is_available",
"(",
"self",
",",
"rtdc_ds",
",",
"verbose",
"=",
"False",
")",
":",
"# Check config keys",
"for",
"item",
"in",
"self",
".",
"req_config",
":",
"section",
",",
"keys",
"=",
"item",
"if",
"section",
"not",
"in",
"rtdc_ds",
".",
"co... | Check whether the feature is available
Parameters
----------
rtdc_ds: instance of RTDCBase
The dataset to check availability for
Returns
-------
available: bool
`True`, if feature can be computed with `compute`
Notes
-----
... | [
"Check",
"whether",
"the",
"feature",
"is",
"available"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/ancillaries/ancillary_feature.py#L169-L229 |
kpn-digital/py-timeexecution | time_execution/backends/kafka.py | KafkaBackend.producer | def producer(self):
"""
:raises: kafka.errors.NoBrokersAvailable if the connection is broken
"""
if self._producer:
return self._producer
self._producer = KafkaProducer(
bootstrap_servers=self.hosts,
value_serializer=lambda v: self._serializer... | python | def producer(self):
"""
:raises: kafka.errors.NoBrokersAvailable if the connection is broken
"""
if self._producer:
return self._producer
self._producer = KafkaProducer(
bootstrap_servers=self.hosts,
value_serializer=lambda v: self._serializer... | [
"def",
"producer",
"(",
"self",
")",
":",
"if",
"self",
".",
"_producer",
":",
"return",
"self",
".",
"_producer",
"self",
".",
"_producer",
"=",
"KafkaProducer",
"(",
"bootstrap_servers",
"=",
"self",
".",
"hosts",
",",
"value_serializer",
"=",
"lambda",
... | :raises: kafka.errors.NoBrokersAvailable if the connection is broken | [
":",
"raises",
":",
"kafka",
".",
"errors",
".",
"NoBrokersAvailable",
"if",
"the",
"connection",
"is",
"broken"
] | train | https://github.com/kpn-digital/py-timeexecution/blob/79b991e83f783196c41b830d0acef21ac5462596/time_execution/backends/kafka.py#L35-L48 |
kpn-digital/py-timeexecution | time_execution/backends/kafka.py | KafkaBackend.write | def write(self, name, **data):
"""
Write the metric to kafka
Args:
name (str): The name of the metric to write
data (dict): Additional data to store with the metric
"""
data["name"] = name
if not ("timestamp" in data):
data["timestamp... | python | def write(self, name, **data):
"""
Write the metric to kafka
Args:
name (str): The name of the metric to write
data (dict): Additional data to store with the metric
"""
data["name"] = name
if not ("timestamp" in data):
data["timestamp... | [
"def",
"write",
"(",
"self",
",",
"name",
",",
"*",
"*",
"data",
")",
":",
"data",
"[",
"\"name\"",
"]",
"=",
"name",
"if",
"not",
"(",
"\"timestamp\"",
"in",
"data",
")",
":",
"data",
"[",
"\"timestamp\"",
"]",
"=",
"datetime",
".",
"utcnow",
"(",... | Write the metric to kafka
Args:
name (str): The name of the metric to write
data (dict): Additional data to store with the metric | [
"Write",
"the",
"metric",
"to",
"kafka"
] | train | https://github.com/kpn-digital/py-timeexecution/blob/79b991e83f783196c41b830d0acef21ac5462596/time_execution/backends/kafka.py#L50-L67 |
kpn-digital/py-timeexecution | time_execution/backends/kafka.py | KafkaBackend.bulk_write | def bulk_write(self, metrics):
"""
Write multiple metrics to kafka in one request
Args:
metrics (list):
"""
try:
for metric in metrics:
self.producer.send(self.topic, metric)
self.producer.flush()
except (KafkaTimeoutEr... | python | def bulk_write(self, metrics):
"""
Write multiple metrics to kafka in one request
Args:
metrics (list):
"""
try:
for metric in metrics:
self.producer.send(self.topic, metric)
self.producer.flush()
except (KafkaTimeoutEr... | [
"def",
"bulk_write",
"(",
"self",
",",
"metrics",
")",
":",
"try",
":",
"for",
"metric",
"in",
"metrics",
":",
"self",
".",
"producer",
".",
"send",
"(",
"self",
".",
"topic",
",",
"metric",
")",
"self",
".",
"producer",
".",
"flush",
"(",
")",
"ex... | Write multiple metrics to kafka in one request
Args:
metrics (list): | [
"Write",
"multiple",
"metrics",
"to",
"kafka",
"in",
"one",
"request"
] | train | https://github.com/kpn-digital/py-timeexecution/blob/79b991e83f783196c41b830d0acef21ac5462596/time_execution/backends/kafka.py#L69-L81 |
kpn-digital/py-timeexecution | docs/apidoc.py | create_module_file | def create_module_file(package, module, opts):
"""Build the text of the file and write the file."""
if not opts.noheadings:
text = format_heading(1, '%s module' % module)
else:
text = ''
# text += format_heading(2, ':mod:`%s` Module' % module)
text += format_directive(module, package... | python | def create_module_file(package, module, opts):
"""Build the text of the file and write the file."""
if not opts.noheadings:
text = format_heading(1, '%s module' % module)
else:
text = ''
# text += format_heading(2, ':mod:`%s` Module' % module)
text += format_directive(module, package... | [
"def",
"create_module_file",
"(",
"package",
",",
"module",
",",
"opts",
")",
":",
"if",
"not",
"opts",
".",
"noheadings",
":",
"text",
"=",
"format_heading",
"(",
"1",
",",
"'%s module'",
"%",
"module",
")",
"else",
":",
"text",
"=",
"''",
"# text += fo... | Build the text of the file and write the file. | [
"Build",
"the",
"text",
"of",
"the",
"file",
"and",
"write",
"the",
"file",
"."
] | train | https://github.com/kpn-digital/py-timeexecution/blob/79b991e83f783196c41b830d0acef21ac5462596/docs/apidoc.py#L85-L93 |
kpn-digital/py-timeexecution | docs/apidoc.py | create_package_file | def create_package_file(root, master_package, subroot, py_files, opts, subs):
"""Build the text of the file and write the file."""
text = format_heading(1, '%s' % makename(master_package, subroot))
if opts.modulefirst:
text += format_directive(subroot, master_package)
text += '\n'
# bu... | python | def create_package_file(root, master_package, subroot, py_files, opts, subs):
"""Build the text of the file and write the file."""
text = format_heading(1, '%s' % makename(master_package, subroot))
if opts.modulefirst:
text += format_directive(subroot, master_package)
text += '\n'
# bu... | [
"def",
"create_package_file",
"(",
"root",
",",
"master_package",
",",
"subroot",
",",
"py_files",
",",
"opts",
",",
"subs",
")",
":",
"text",
"=",
"format_heading",
"(",
"1",
",",
"'%s'",
"%",
"makename",
"(",
"master_package",
",",
"subroot",
")",
")",
... | Build the text of the file and write the file. | [
"Build",
"the",
"text",
"of",
"the",
"file",
"and",
"write",
"the",
"file",
"."
] | train | https://github.com/kpn-digital/py-timeexecution/blob/79b991e83f783196c41b830d0acef21ac5462596/docs/apidoc.py#L96-L147 |
kpn-digital/py-timeexecution | docs/apidoc.py | shall_skip | def shall_skip(module, opts):
"""Check if we want to skip this module."""
# skip it if there is nothing (or just \n or \r\n) in the file
if path.getsize(module) <= 2:
return True
# skip if it has a "private" name and this is selected
filename = path.basename(module)
if filename != '__ini... | python | def shall_skip(module, opts):
"""Check if we want to skip this module."""
# skip it if there is nothing (or just \n or \r\n) in the file
if path.getsize(module) <= 2:
return True
# skip if it has a "private" name and this is selected
filename = path.basename(module)
if filename != '__ini... | [
"def",
"shall_skip",
"(",
"module",
",",
"opts",
")",
":",
"# skip it if there is nothing (or just \\n or \\r\\n) in the file",
"if",
"path",
".",
"getsize",
"(",
"module",
")",
"<=",
"2",
":",
"return",
"True",
"# skip if it has a \"private\" name and this is selected",
... | Check if we want to skip this module. | [
"Check",
"if",
"we",
"want",
"to",
"skip",
"this",
"module",
"."
] | train | https://github.com/kpn-digital/py-timeexecution/blob/79b991e83f783196c41b830d0acef21ac5462596/docs/apidoc.py#L168-L178 |
openstax/cnx-archive | cnxarchive/utils/safe.py | safe_stat | def safe_stat(path, timeout=1, cmd=None):
"Use threads and a subproc to bodge a timeout on top of filesystem access"
global safe_stat_process
if cmd is None:
cmd = ['/usr/bin/stat']
cmd.append(path)
def target():
global safe_stat_process
logger.debug('Stat thread started')... | python | def safe_stat(path, timeout=1, cmd=None):
"Use threads and a subproc to bodge a timeout on top of filesystem access"
global safe_stat_process
if cmd is None:
cmd = ['/usr/bin/stat']
cmd.append(path)
def target():
global safe_stat_process
logger.debug('Stat thread started')... | [
"def",
"safe_stat",
"(",
"path",
",",
"timeout",
"=",
"1",
",",
"cmd",
"=",
"None",
")",
":",
"global",
"safe_stat_process",
"if",
"cmd",
"is",
"None",
":",
"cmd",
"=",
"[",
"'/usr/bin/stat'",
"]",
"cmd",
".",
"append",
"(",
"path",
")",
"def",
"targ... | Use threads and a subproc to bodge a timeout on top of filesystem access | [
"Use",
"threads",
"and",
"a",
"subproc",
"to",
"bodge",
"a",
"timeout",
"on",
"top",
"of",
"filesystem",
"access"
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/utils/safe.py#L12-L36 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | get_polygon_filter_names | def get_polygon_filter_names():
"""Get the names of all polygon filters in the order of creation"""
names = []
for p in PolygonFilter.instances:
names.append(p.name)
return names | python | def get_polygon_filter_names():
"""Get the names of all polygon filters in the order of creation"""
names = []
for p in PolygonFilter.instances:
names.append(p.name)
return names | [
"def",
"get_polygon_filter_names",
"(",
")",
":",
"names",
"=",
"[",
"]",
"for",
"p",
"in",
"PolygonFilter",
".",
"instances",
":",
"names",
".",
"append",
"(",
"p",
".",
"name",
")",
"return",
"names"
] | Get the names of all polygon filters in the order of creation | [
"Get",
"the",
"names",
"of",
"all",
"polygon",
"filters",
"in",
"the",
"order",
"of",
"creation"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L366-L371 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | PolygonFilter._check_data | def _check_data(self):
"""Check if the data given is valid"""
if self.axes is None:
raise PolygonFilterError("`axes` parm not set.")
if self.points is None:
raise PolygonFilterError("`points` parm not set.")
self.points = np.array(self.points)
if self.poin... | python | def _check_data(self):
"""Check if the data given is valid"""
if self.axes is None:
raise PolygonFilterError("`axes` parm not set.")
if self.points is None:
raise PolygonFilterError("`points` parm not set.")
self.points = np.array(self.points)
if self.poin... | [
"def",
"_check_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"axes",
"is",
"None",
":",
"raise",
"PolygonFilterError",
"(",
"\"`axes` parm not set.\"",
")",
"if",
"self",
".",
"points",
"is",
"None",
":",
"raise",
"PolygonFilterError",
"(",
"\"`points` parm... | Check if the data given is valid | [
"Check",
"if",
"the",
"data",
"given",
"is",
"valid"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L92-L104 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | PolygonFilter._load | def _load(self, filename):
"""Import all filters from a text file"""
filename = pathlib.Path(filename)
with filename.open() as fd:
data = fd.readlines()
# Get the strings that correspond to self.fileid
bool_head = [l.strip().startswith("[") for l in data]
in... | python | def _load(self, filename):
"""Import all filters from a text file"""
filename = pathlib.Path(filename)
with filename.open() as fd:
data = fd.readlines()
# Get the strings that correspond to self.fileid
bool_head = [l.strip().startswith("[") for l in data]
in... | [
"def",
"_load",
"(",
"self",
",",
"filename",
")",
":",
"filename",
"=",
"pathlib",
".",
"Path",
"(",
"filename",
")",
"with",
"filename",
".",
"open",
"(",
")",
"as",
"fd",
":",
"data",
"=",
"fd",
".",
"readlines",
"(",
")",
"# Get the strings that co... | Import all filters from a text file | [
"Import",
"all",
"filters",
"from",
"a",
"text",
"file"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L106-L156 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | PolygonFilter._set_unique_id | def _set_unique_id(self, unique_id):
"""Define a unique id"""
assert isinstance(unique_id, int), "unique_id must be an integer"
if PolygonFilter.instace_exists(unique_id):
newid = max(PolygonFilter._instance_counter, unique_id+1)
msg = "PolygonFilter with unique_id '{}' ... | python | def _set_unique_id(self, unique_id):
"""Define a unique id"""
assert isinstance(unique_id, int), "unique_id must be an integer"
if PolygonFilter.instace_exists(unique_id):
newid = max(PolygonFilter._instance_counter, unique_id+1)
msg = "PolygonFilter with unique_id '{}' ... | [
"def",
"_set_unique_id",
"(",
"self",
",",
"unique_id",
")",
":",
"assert",
"isinstance",
"(",
"unique_id",
",",
"int",
")",
",",
"\"unique_id must be an integer\"",
"if",
"PolygonFilter",
".",
"instace_exists",
"(",
"unique_id",
")",
":",
"newid",
"=",
"max",
... | Define a unique id | [
"Define",
"a",
"unique",
"id"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L158-L171 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | PolygonFilter.copy | def copy(self, invert=False):
"""Return a copy of the current instance
Parameters
----------
invert: bool
The copy will be inverted w.r.t. the original
"""
if invert:
inverted = not self.inverted
else:
inverted = self.inverted
... | python | def copy(self, invert=False):
"""Return a copy of the current instance
Parameters
----------
invert: bool
The copy will be inverted w.r.t. the original
"""
if invert:
inverted = not self.inverted
else:
inverted = self.inverted
... | [
"def",
"copy",
"(",
"self",
",",
"invert",
"=",
"False",
")",
":",
"if",
"invert",
":",
"inverted",
"=",
"not",
"self",
".",
"inverted",
"else",
":",
"inverted",
"=",
"self",
".",
"inverted",
"return",
"PolygonFilter",
"(",
"axes",
"=",
"self",
".",
... | Return a copy of the current instance
Parameters
----------
invert: bool
The copy will be inverted w.r.t. the original | [
"Return",
"a",
"copy",
"of",
"the",
"current",
"instance"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L179-L195 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | PolygonFilter.filter | def filter(self, datax, datay):
"""Filter a set of datax and datay according to `self.points`"""
f = np.ones(datax.shape, dtype=bool)
for i, p in enumerate(zip(datax, datay)):
f[i] = PolygonFilter.point_in_poly(p, self.points)
if self.inverted:
np.invert(f, f)
... | python | def filter(self, datax, datay):
"""Filter a set of datax and datay according to `self.points`"""
f = np.ones(datax.shape, dtype=bool)
for i, p in enumerate(zip(datax, datay)):
f[i] = PolygonFilter.point_in_poly(p, self.points)
if self.inverted:
np.invert(f, f)
... | [
"def",
"filter",
"(",
"self",
",",
"datax",
",",
"datay",
")",
":",
"f",
"=",
"np",
".",
"ones",
"(",
"datax",
".",
"shape",
",",
"dtype",
"=",
"bool",
")",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"zip",
"(",
"datax",
",",
"datay",
")",
... | Filter a set of datax and datay according to `self.points` | [
"Filter",
"a",
"set",
"of",
"datax",
"and",
"datay",
"according",
"to",
"self",
".",
"points"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L197-L206 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | PolygonFilter.get_instance_from_id | def get_instance_from_id(unique_id):
"""Get an instance of the `PolygonFilter` using a unique id"""
for instance in PolygonFilter.instances:
if instance.unique_id == unique_id:
return instance
# if this does not work:
raise KeyError("PolygonFilter with unique_... | python | def get_instance_from_id(unique_id):
"""Get an instance of the `PolygonFilter` using a unique id"""
for instance in PolygonFilter.instances:
if instance.unique_id == unique_id:
return instance
# if this does not work:
raise KeyError("PolygonFilter with unique_... | [
"def",
"get_instance_from_id",
"(",
"unique_id",
")",
":",
"for",
"instance",
"in",
"PolygonFilter",
".",
"instances",
":",
"if",
"instance",
".",
"unique_id",
"==",
"unique_id",
":",
"return",
"instance",
"# if this does not work:",
"raise",
"KeyError",
"(",
"\"P... | Get an instance of the `PolygonFilter` using a unique id | [
"Get",
"an",
"instance",
"of",
"the",
"PolygonFilter",
"using",
"a",
"unique",
"id"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L209-L216 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | PolygonFilter.import_all | def import_all(path):
"""Import all polygons from a .poly file.
Returns a list of the imported polygon filters
"""
plist = []
fid = 0
while True:
try:
p = PolygonFilter(filename=path, fileid=fid)
plist.append(p)
... | python | def import_all(path):
"""Import all polygons from a .poly file.
Returns a list of the imported polygon filters
"""
plist = []
fid = 0
while True:
try:
p = PolygonFilter(filename=path, fileid=fid)
plist.append(p)
... | [
"def",
"import_all",
"(",
"path",
")",
":",
"plist",
"=",
"[",
"]",
"fid",
"=",
"0",
"while",
"True",
":",
"try",
":",
"p",
"=",
"PolygonFilter",
"(",
"filename",
"=",
"path",
",",
"fileid",
"=",
"fid",
")",
"plist",
".",
"append",
"(",
"p",
")",... | Import all polygons from a .poly file.
Returns a list of the imported polygon filters | [
"Import",
"all",
"polygons",
"from",
"a",
".",
"poly",
"file",
"."
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L219-L233 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | PolygonFilter.point_in_poly | def point_in_poly(p, poly):
"""Determine whether a point is within a polygon area
Uses the ray casting algorithm.
Parameters
----------
p: float
Coordinates of the point
poly: array_like of shape (N, 2)
Polygon (`PolygonFilter.points`)
R... | python | def point_in_poly(p, poly):
"""Determine whether a point is within a polygon area
Uses the ray casting algorithm.
Parameters
----------
p: float
Coordinates of the point
poly: array_like of shape (N, 2)
Polygon (`PolygonFilter.points`)
R... | [
"def",
"point_in_poly",
"(",
"p",
",",
"poly",
")",
":",
"poly",
"=",
"np",
".",
"array",
"(",
"poly",
")",
"n",
"=",
"poly",
".",
"shape",
"[",
"0",
"]",
"inside",
"=",
"False",
"x",
",",
"y",
"=",
"p",
"# Coarse bounding box exclusion:",
"if",
"(... | Determine whether a point is within a polygon area
Uses the ray casting algorithm.
Parameters
----------
p: float
Coordinates of the point
poly: array_like of shape (N, 2)
Polygon (`PolygonFilter.points`)
Returns
-------
inside: ... | [
"Determine",
"whether",
"a",
"point",
"is",
"within",
"a",
"polygon",
"area"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L246-L301 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | PolygonFilter.remove | def remove(unique_id):
"""Remove a polygon filter from `PolygonFilter.instances`"""
for p in PolygonFilter.instances:
if p.unique_id == unique_id:
PolygonFilter.instances.remove(p) | python | def remove(unique_id):
"""Remove a polygon filter from `PolygonFilter.instances`"""
for p in PolygonFilter.instances:
if p.unique_id == unique_id:
PolygonFilter.instances.remove(p) | [
"def",
"remove",
"(",
"unique_id",
")",
":",
"for",
"p",
"in",
"PolygonFilter",
".",
"instances",
":",
"if",
"p",
".",
"unique_id",
"==",
"unique_id",
":",
"PolygonFilter",
".",
"instances",
".",
"remove",
"(",
"p",
")"
] | Remove a polygon filter from `PolygonFilter.instances` | [
"Remove",
"a",
"polygon",
"filter",
"from",
"PolygonFilter",
".",
"instances"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L304-L308 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | PolygonFilter.save | def save(self, polyfile, ret_fobj=False):
"""Save all data to a text file (appends data if file exists).
Polyfile can be either a path to a file or a file object that
was opened with the write "w" parameter. By using the file
object, multiple instances of this class can write their data... | python | def save(self, polyfile, ret_fobj=False):
"""Save all data to a text file (appends data if file exists).
Polyfile can be either a path to a file or a file object that
was opened with the write "w" parameter. By using the file
object, multiple instances of this class can write their data... | [
"def",
"save",
"(",
"self",
",",
"polyfile",
",",
"ret_fobj",
"=",
"False",
")",
":",
"if",
"is_file_obj",
"(",
"polyfile",
")",
":",
"fobj",
"=",
"polyfile",
"else",
":",
"fobj",
"=",
"pathlib",
".",
"Path",
"(",
"polyfile",
")",
".",
"open",
"(",
... | Save all data to a text file (appends data if file exists).
Polyfile can be either a path to a file or a file object that
was opened with the write "w" parameter. By using the file
object, multiple instances of this class can write their data.
If `ret_fobj` is `True`, then the file obj... | [
"Save",
"all",
"data",
"to",
"a",
"text",
"file",
"(",
"appends",
"data",
"if",
"file",
"exists",
")",
"."
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L310-L347 |
ZELLMECHANIK-DRESDEN/dclab | dclab/polygon_filter.py | PolygonFilter.save_all | def save_all(polyfile):
"""Save all polygon filters"""
nump = len(PolygonFilter.instances)
if nump == 0:
raise PolygonFilterError("There are not polygon filters to save.")
for p in PolygonFilter.instances:
# we return the ret_obj, so we don't need to open and
... | python | def save_all(polyfile):
"""Save all polygon filters"""
nump = len(PolygonFilter.instances)
if nump == 0:
raise PolygonFilterError("There are not polygon filters to save.")
for p in PolygonFilter.instances:
# we return the ret_obj, so we don't need to open and
... | [
"def",
"save_all",
"(",
"polyfile",
")",
":",
"nump",
"=",
"len",
"(",
"PolygonFilter",
".",
"instances",
")",
"if",
"nump",
"==",
"0",
":",
"raise",
"PolygonFilterError",
"(",
"\"There are not polygon filters to save.\"",
")",
"for",
"p",
"in",
"PolygonFilter",... | Save all polygon filters | [
"Save",
"all",
"polygon",
"filters"
] | train | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/polygon_filter.py#L350-L359 |
openstax/cnx-archive | cnxarchive/views/resource.py | get_resource | def get_resource(request):
"""Retrieve a file's data."""
hash = request.matchdict['hash']
# Do the file lookup
with db_connect() as db_connection:
with db_connection.cursor() as cursor:
args = dict(hash=hash)
cursor.execute(SQL['get-resource'], args)
try:
... | python | def get_resource(request):
"""Retrieve a file's data."""
hash = request.matchdict['hash']
# Do the file lookup
with db_connect() as db_connection:
with db_connection.cursor() as cursor:
args = dict(hash=hash)
cursor.execute(SQL['get-resource'], args)
try:
... | [
"def",
"get_resource",
"(",
"request",
")",
":",
"hash",
"=",
"request",
".",
"matchdict",
"[",
"'hash'",
"]",
"# Do the file lookup",
"with",
"db_connect",
"(",
")",
"as",
"db_connection",
":",
"with",
"db_connection",
".",
"cursor",
"(",
")",
"as",
"cursor... | Retrieve a file's data. | [
"Retrieve",
"a",
"file",
"s",
"data",
"."
] | train | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/resource.py#L32-L50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.