partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test | Table.chart_plot | Plot a nuclear chart with (N,Z) as axis and the values
of the Table as a color scale
Parameters
----------
ax: optional matplotlib axes
defaults to current axes
cmap: a matplotlib colormap
default: 'RdBu'
xlabel: string representing the la... | masstable/masstable.py | def chart_plot(self, ax=None, cmap='RdBu',
xlabel='N', ylabel='Z', grid_on=True, colorbar=True):
"""Plot a nuclear chart with (N,Z) as axis and the values
of the Table as a color scale
Parameters
----------
ax: optional matplotlib axes
defaults to ... | def chart_plot(self, ax=None, cmap='RdBu',
xlabel='N', ylabel='Z', grid_on=True, colorbar=True):
"""Plot a nuclear chart with (N,Z) as axis and the values
of the Table as a color scale
Parameters
----------
ax: optional matplotlib axes
defaults to ... | [
"Plot",
"a",
"nuclear",
"chart",
"with",
"(",
"N",
"Z",
")",
"as",
"axis",
"and",
"the",
"values",
"of",
"the",
"Table",
"as",
"a",
"color",
"scale"
] | elyase/masstable | python | https://github.com/elyase/masstable/blob/3eb72b22cd3337bc5c6bb95bb7bb73fdbe6ae9e2/masstable/masstable.py#L519-L576 | [
"def",
"chart_plot",
"(",
"self",
",",
"ax",
"=",
"None",
",",
"cmap",
"=",
"'RdBu'",
",",
"xlabel",
"=",
"'N'",
",",
"ylabel",
"=",
"'Z'",
",",
"grid_on",
"=",
"True",
",",
"colorbar",
"=",
"True",
")",
":",
"from",
"matplotlib",
".",
"mlab",
"imp... | 3eb72b22cd3337bc5c6bb95bb7bb73fdbe6ae9e2 |
test | _uses_db | Use as a decorator for operations on the database, to ensure connection setup and
teardown. Can only be used on methods on objects with a `self.session` attribute. | pwm/core.py | def _uses_db(func, self, *args, **kwargs):
""" Use as a decorator for operations on the database, to ensure connection setup and
teardown. Can only be used on methods on objects with a `self.session` attribute.
"""
if not self.session:
_logger.debug('Creating new db session')
self._init_... | def _uses_db(func, self, *args, **kwargs):
""" Use as a decorator for operations on the database, to ensure connection setup and
teardown. Can only be used on methods on objects with a `self.session` attribute.
"""
if not self.session:
_logger.debug('Creating new db session')
self._init_... | [
"Use",
"as",
"a",
"decorator",
"for",
"operations",
"on",
"the",
"database",
"to",
"ensure",
"connection",
"setup",
"and",
"teardown",
".",
"Can",
"only",
"be",
"used",
"on",
"methods",
"on",
"objects",
"with",
"a",
"self",
".",
"session",
"attribute",
"."... | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/core.py#L112-L130 | [
"def",
"_uses_db",
"(",
"func",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"session",
":",
"_logger",
".",
"debug",
"(",
"'Creating new db session'",
")",
"self",
".",
"_init_db_session",
"(",
")",
"try"... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | Domain.derive_key | Computes the key from the salt and the master password. | pwm/core.py | def derive_key(self, master_password):
""" Computes the key from the salt and the master password. """
encoder = encoding.Encoder(self.charset)
bytes = ('%s:%s' % (master_password, self.name)).encode('utf8')
start_time = time.clock()
# we fix the scrypt parameters in case the d... | def derive_key(self, master_password):
""" Computes the key from the salt and the master password. """
encoder = encoding.Encoder(self.charset)
bytes = ('%s:%s' % (master_password, self.name)).encode('utf8')
start_time = time.clock()
# we fix the scrypt parameters in case the d... | [
"Computes",
"the",
"key",
"from",
"the",
"salt",
"and",
"the",
"master",
"password",
"."
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/core.py#L67-L81 | [
"def",
"derive_key",
"(",
"self",
",",
"master_password",
")",
":",
"encoder",
"=",
"encoding",
".",
"Encoder",
"(",
"self",
".",
"charset",
")",
"bytes",
"=",
"(",
"'%s:%s'",
"%",
"(",
"master_password",
",",
"self",
".",
"name",
")",
")",
".",
"encod... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | PWM.bootstrap | Initialize a database.
:param database_path: The absolute path to the database to initialize. | pwm/core.py | def bootstrap(self, path_or_uri):
""" Initialize a database.
:param database_path: The absolute path to the database to initialize.
"""
_logger.debug("Bootstrapping new database: %s", path_or_uri)
self.database_uri = _urify_db(path_or_uri)
db = sa.create_engine(self.data... | def bootstrap(self, path_or_uri):
""" Initialize a database.
:param database_path: The absolute path to the database to initialize.
"""
_logger.debug("Bootstrapping new database: %s", path_or_uri)
self.database_uri = _urify_db(path_or_uri)
db = sa.create_engine(self.data... | [
"Initialize",
"a",
"database",
"."
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/core.py#L147-L155 | [
"def",
"bootstrap",
"(",
"self",
",",
"path_or_uri",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Bootstrapping new database: %s\"",
",",
"path_or_uri",
")",
"self",
".",
"database_uri",
"=",
"_urify_db",
"(",
"path_or_uri",
")",
"db",
"=",
"sa",
".",
"create_en... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | PWM.search | Search the database for the given query. Will find partial matches. | pwm/core.py | def search(self, query):
""" Search the database for the given query. Will find partial matches. """
results = self.session.query(Domain).filter(Domain.name.ilike('%%%s%%' % query)).all()
return results | def search(self, query):
""" Search the database for the given query. Will find partial matches. """
results = self.session.query(Domain).filter(Domain.name.ilike('%%%s%%' % query)).all()
return results | [
"Search",
"the",
"database",
"for",
"the",
"given",
"query",
".",
"Will",
"find",
"partial",
"matches",
"."
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/core.py#L159-L162 | [
"def",
"search",
"(",
"self",
",",
"query",
")",
":",
"results",
"=",
"self",
".",
"session",
".",
"query",
"(",
"Domain",
")",
".",
"filter",
"(",
"Domain",
".",
"name",
".",
"ilike",
"(",
"'%%%s%%'",
"%",
"query",
")",
")",
".",
"all",
"(",
")"... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | PWM.get_domain | Get the :class:`Domain <pwm.Domain>` object from a name.
:param domain_name: The domain name to fetch the object for.
:returns: The :class:`Domain <pwm.core.Domain>` class with this domain_name if found, else
None. | pwm/core.py | def get_domain(self, domain_name):
""" Get the :class:`Domain <pwm.Domain>` object from a name.
:param domain_name: The domain name to fetch the object for.
:returns: The :class:`Domain <pwm.core.Domain>` class with this domain_name if found, else
None.
"""
protocol ... | def get_domain(self, domain_name):
""" Get the :class:`Domain <pwm.Domain>` object from a name.
:param domain_name: The domain name to fetch the object for.
:returns: The :class:`Domain <pwm.core.Domain>` class with this domain_name if found, else
None.
"""
protocol ... | [
"Get",
"the",
":",
"class",
":",
"Domain",
"<pwm",
".",
"Domain",
">",
"object",
"from",
"a",
"name",
"."
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/core.py#L166-L181 | [
"def",
"get_domain",
"(",
"self",
",",
"domain_name",
")",
":",
"protocol",
"=",
"self",
".",
"database_uri",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"0",
"]",
"if",
"protocol",
"in",
"(",
"'https'",
",",
"'http'",
")",
":",
"return",
"self",
... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | PWM.modify_domain | Modify an existing domain.
:param domain_name: The name of the domain to modify.
:param new_salt: Whether to generate a new salt for the domain.
:param username: If given, change domain username to this value.
:returns: The modified :class:`Domain <pwm.core.Domain>` object. | pwm/core.py | def modify_domain(self, domain_name, new_salt=False, username=None):
""" Modify an existing domain.
:param domain_name: The name of the domain to modify.
:param new_salt: Whether to generate a new salt for the domain.
:param username: If given, change domain username to this value.
... | def modify_domain(self, domain_name, new_salt=False, username=None):
""" Modify an existing domain.
:param domain_name: The name of the domain to modify.
:param new_salt: Whether to generate a new salt for the domain.
:param username: If given, change domain username to this value.
... | [
"Modify",
"an",
"existing",
"domain",
"."
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/core.py#L217-L233 | [
"def",
"modify_domain",
"(",
"self",
",",
"domain_name",
",",
"new_salt",
"=",
"False",
",",
"username",
"=",
"None",
")",
":",
"domain",
"=",
"self",
".",
"_get_domain_from_db",
"(",
"domain_name",
")",
"if",
"domain",
"is",
"None",
":",
"raise",
"NoSuchD... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | PWM.create_domain | Create a new domain entry in the database.
:param username: The username to associate with this domain.
:param alphabet: A character set restriction to impose on keys generated for this domain.
:param length: The length of the generated key, in case of restrictions on the site. | pwm/core.py | def create_domain(self, domain_name, username=None, alphabet=Domain.DEFAULT_ALPHABET,
length=Domain.DEFAULT_KEY_LENGTH):
""" Create a new domain entry in the database.
:param username: The username to associate with this domain.
:param alphabet: A character set restriction to impose... | def create_domain(self, domain_name, username=None, alphabet=Domain.DEFAULT_ALPHABET,
length=Domain.DEFAULT_KEY_LENGTH):
""" Create a new domain entry in the database.
:param username: The username to associate with this domain.
:param alphabet: A character set restriction to impose... | [
"Create",
"a",
"new",
"domain",
"entry",
"in",
"the",
"database",
"."
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/core.py#L236-L249 | [
"def",
"create_domain",
"(",
"self",
",",
"domain_name",
",",
"username",
"=",
"None",
",",
"alphabet",
"=",
"Domain",
".",
"DEFAULT_ALPHABET",
",",
"length",
"=",
"Domain",
".",
"DEFAULT_KEY_LENGTH",
")",
":",
"# Wrap the actual implementation to do some error handli... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | from_bbox | Yields tile (x, y, z) tuples for a bounding box and zoom levels.
Arguments:
bbox - bounding box as a 4-length sequence
zlevs - sequence of tile zoom levels | greenwich/tile.py | def from_bbox(bbox, zlevs):
"""Yields tile (x, y, z) tuples for a bounding box and zoom levels.
Arguments:
bbox - bounding box as a 4-length sequence
zlevs - sequence of tile zoom levels
"""
env = Envelope(bbox)
for z in zlevs:
corners = [to_tile(*coord + (z,)) for coord in (env.ul,... | def from_bbox(bbox, zlevs):
"""Yields tile (x, y, z) tuples for a bounding box and zoom levels.
Arguments:
bbox - bounding box as a 4-length sequence
zlevs - sequence of tile zoom levels
"""
env = Envelope(bbox)
for z in zlevs:
corners = [to_tile(*coord + (z,)) for coord in (env.ul,... | [
"Yields",
"tile",
"(",
"x",
"y",
"z",
")",
"tuples",
"for",
"a",
"bounding",
"box",
"and",
"zoom",
"levels",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/tile.py#L6-L18 | [
"def",
"from_bbox",
"(",
"bbox",
",",
"zlevs",
")",
":",
"env",
"=",
"Envelope",
"(",
"bbox",
")",
"for",
"z",
"in",
"zlevs",
":",
"corners",
"=",
"[",
"to_tile",
"(",
"*",
"coord",
"+",
"(",
"z",
",",
")",
")",
"for",
"coord",
"in",
"(",
"env"... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | to_lonlat | Returns a tuple of (longitude, latitude) from a map tile xyz coordinate.
See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_2
Arguments:
xtile - x tile location as int or float
ytile - y tile location as int or float
zoom - zoom level as int or float | greenwich/tile.py | def to_lonlat(xtile, ytile, zoom):
"""Returns a tuple of (longitude, latitude) from a map tile xyz coordinate.
See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_2
Arguments:
xtile - x tile location as int or float
ytile - y tile location as int or float
zo... | def to_lonlat(xtile, ytile, zoom):
"""Returns a tuple of (longitude, latitude) from a map tile xyz coordinate.
See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Lon..2Flat._to_tile_numbers_2
Arguments:
xtile - x tile location as int or float
ytile - y tile location as int or float
zo... | [
"Returns",
"a",
"tuple",
"of",
"(",
"longitude",
"latitude",
")",
"from",
"a",
"map",
"tile",
"xyz",
"coordinate",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/tile.py#L20-L40 | [
"def",
"to_lonlat",
"(",
"xtile",
",",
"ytile",
",",
"zoom",
")",
":",
"n",
"=",
"2.0",
"**",
"zoom",
"lon",
"=",
"xtile",
"/",
"n",
"*",
"360.0",
"-",
"180.0",
"# Caculate latitude in radians and convert to degrees constrained from -90",
"# to 90. Values too big fo... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | to_tile | Returns a tuple of (xtile, ytile) from a (longitude, latitude) coordinate.
See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
Arguments:
lon - longitude as int or float
lat - latitude as int or float
zoom - zoom level as int or float | greenwich/tile.py | def to_tile(lon, lat, zoom):
"""Returns a tuple of (xtile, ytile) from a (longitude, latitude) coordinate.
See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
Arguments:
lon - longitude as int or float
lat - latitude as int or float
zoom - zoom level as int or float
"""
lat_rad... | def to_tile(lon, lat, zoom):
"""Returns a tuple of (xtile, ytile) from a (longitude, latitude) coordinate.
See http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
Arguments:
lon - longitude as int or float
lat - latitude as int or float
zoom - zoom level as int or float
"""
lat_rad... | [
"Returns",
"a",
"tuple",
"of",
"(",
"xtile",
"ytile",
")",
"from",
"a",
"(",
"longitude",
"latitude",
")",
"coordinate",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/tile.py#L42-L57 | [
"def",
"to_tile",
"(",
"lon",
",",
"lat",
",",
"zoom",
")",
":",
"lat_rad",
"=",
"math",
".",
"radians",
"(",
"lat",
")",
"n",
"=",
"2.0",
"**",
"zoom",
"xtile",
"=",
"int",
"(",
"(",
"lon",
"+",
"180.0",
")",
"/",
"360.0",
"*",
"n",
")",
"yt... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | extract_hbs | Extract messages from Handlebars templates.
It returns an iterator yielding tuples in the following form ``(lineno,
funcname, message, comments)``.
TODO: Things to improve:
--- Return comments | pybabel_hbs/extractor.py | def extract_hbs(fileobj, keywords, comment_tags, options):
"""Extract messages from Handlebars templates.
It returns an iterator yielding tuples in the following form ``(lineno,
funcname, message, comments)``.
TODO: Things to improve:
--- Return comments
"""
server = get_pipeserver()
... | def extract_hbs(fileobj, keywords, comment_tags, options):
"""Extract messages from Handlebars templates.
It returns an iterator yielding tuples in the following form ``(lineno,
funcname, message, comments)``.
TODO: Things to improve:
--- Return comments
"""
server = get_pipeserver()
... | [
"Extract",
"messages",
"from",
"Handlebars",
"templates",
"."
] | tigrawap/pybabel-hbs | python | https://github.com/tigrawap/pybabel-hbs/blob/5289bc0f8a5e97044f5b074c9532dcd2115625b9/pybabel_hbs/extractor.py#L34-L54 | [
"def",
"extract_hbs",
"(",
"fileobj",
",",
"keywords",
",",
"comment_tags",
",",
"options",
")",
":",
"server",
"=",
"get_pipeserver",
"(",
")",
"server",
".",
"sendline",
"(",
"COMMAND",
"+",
"u'PARSE FILE:'",
"+",
"fileobj",
".",
"name",
")",
"server",
"... | 5289bc0f8a5e97044f5b074c9532dcd2115625b9 |
test | vsiprefix | Returns a GDAL virtual filesystem prefixed path.
Arguments:
path -- file path as str | greenwich/io.py | def vsiprefix(path):
"""Returns a GDAL virtual filesystem prefixed path.
Arguments:
path -- file path as str
"""
vpath = path.lower()
scheme = VSI_SCHEMES.get(urlparse(vpath).scheme, '')
for ext in VSI_TYPES:
if ext in vpath:
filesys = VSI_TYPES[ext]
break
... | def vsiprefix(path):
"""Returns a GDAL virtual filesystem prefixed path.
Arguments:
path -- file path as str
"""
vpath = path.lower()
scheme = VSI_SCHEMES.get(urlparse(vpath).scheme, '')
for ext in VSI_TYPES:
if ext in vpath:
filesys = VSI_TYPES[ext]
break
... | [
"Returns",
"a",
"GDAL",
"virtual",
"filesystem",
"prefixed",
"path",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/io.py#L16-L32 | [
"def",
"vsiprefix",
"(",
"path",
")",
":",
"vpath",
"=",
"path",
".",
"lower",
"(",
")",
"scheme",
"=",
"VSI_SCHEMES",
".",
"get",
"(",
"urlparse",
"(",
"vpath",
")",
".",
"scheme",
",",
"''",
")",
"for",
"ext",
"in",
"VSI_TYPES",
":",
"if",
"ext",... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | SpatialReference.srid | Returns the EPSG ID as int if it exists. | greenwich/srs.py | def srid(self):
"""Returns the EPSG ID as int if it exists."""
epsg_id = (self.GetAuthorityCode('PROJCS') or
self.GetAuthorityCode('GEOGCS'))
try:
return int(epsg_id)
except TypeError:
return | def srid(self):
"""Returns the EPSG ID as int if it exists."""
epsg_id = (self.GetAuthorityCode('PROJCS') or
self.GetAuthorityCode('GEOGCS'))
try:
return int(epsg_id)
except TypeError:
return | [
"Returns",
"the",
"EPSG",
"ID",
"as",
"int",
"if",
"it",
"exists",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/srs.py#L44-L51 | [
"def",
"srid",
"(",
"self",
")",
":",
"epsg_id",
"=",
"(",
"self",
".",
"GetAuthorityCode",
"(",
"'PROJCS'",
")",
"or",
"self",
".",
"GetAuthorityCode",
"(",
"'GEOGCS'",
")",
")",
"try",
":",
"return",
"int",
"(",
"epsg_id",
")",
"except",
"TypeError",
... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | main | Main entry point for the CLI. | pwm/cli.py | def main():
""" Main entry point for the CLI. """
args = get_args()
ret_code = args.target(args)
_logger.debug('Exiting with code %d', ret_code)
sys.exit(ret_code) | def main():
""" Main entry point for the CLI. """
args = get_args()
ret_code = args.target(args)
_logger.debug('Exiting with code %d', ret_code)
sys.exit(ret_code) | [
"Main",
"entry",
"point",
"for",
"the",
"CLI",
"."
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/cli.py#L30-L35 | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
")",
"ret_code",
"=",
"args",
".",
"target",
"(",
"args",
")",
"_logger",
".",
"debug",
"(",
"'Exiting with code %d'",
",",
"ret_code",
")",
"sys",
".",
"exit",
"(",
"ret_code",
")"
] | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | _init_logging | Initialize loggers. | pwm/cli.py | def _init_logging(verbose=False):
""" Initialize loggers. """
config = {
'version': 1,
'formatters': {
'console': {
'format': '* %(message)s',
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
... | def _init_logging(verbose=False):
""" Initialize loggers. """
config = {
'version': 1,
'formatters': {
'console': {
'format': '* %(message)s',
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
... | [
"Initialize",
"loggers",
"."
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/cli.py#L207-L238 | [
"def",
"_init_logging",
"(",
"verbose",
"=",
"False",
")",
":",
"config",
"=",
"{",
"'version'",
":",
"1",
",",
"'formatters'",
":",
"{",
"'console'",
":",
"{",
"'format'",
":",
"'* %(message)s'",
",",
"}",
"}",
",",
"'handlers'",
":",
"{",
"'console'",
... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | update_file | Update the content of a single file. | scripts/update-lists.py | def update_file(url, filename):
"""Update the content of a single file."""
resp = urlopen(url)
if resp.code != 200:
raise Exception('GET {} failed.'.format(url))
with open(_get_package_path(filename), 'w') as fp:
for l in resp:
if not l.startswith(b'#'):
fp.wr... | def update_file(url, filename):
"""Update the content of a single file."""
resp = urlopen(url)
if resp.code != 200:
raise Exception('GET {} failed.'.format(url))
with open(_get_package_path(filename), 'w') as fp:
for l in resp:
if not l.startswith(b'#'):
fp.wr... | [
"Update",
"the",
"content",
"of",
"a",
"single",
"file",
"."
] | inveniosoftware/counter-robots | python | https://github.com/inveniosoftware/counter-robots/blob/484943fdc7e08f41d3ad7a9e2229afe0cec05547/scripts/update-lists.py#L43-L52 | [
"def",
"update_file",
"(",
"url",
",",
"filename",
")",
":",
"resp",
"=",
"urlopen",
"(",
"url",
")",
"if",
"resp",
".",
"code",
"!=",
"200",
":",
"raise",
"Exception",
"(",
"'GET {} failed.'",
".",
"format",
"(",
"url",
")",
")",
"with",
"open",
"("... | 484943fdc7e08f41d3ad7a9e2229afe0cec05547 |
test | available_drivers | Returns a dictionary of enabled GDAL Driver metadata keyed by the
'ShortName' attribute. | greenwich/raster.py | def available_drivers():
"""Returns a dictionary of enabled GDAL Driver metadata keyed by the
'ShortName' attribute.
"""
drivers = {}
for i in range(gdal.GetDriverCount()):
d = gdal.GetDriver(i)
drivers[d.ShortName] = d.GetMetadata()
return drivers | def available_drivers():
"""Returns a dictionary of enabled GDAL Driver metadata keyed by the
'ShortName' attribute.
"""
drivers = {}
for i in range(gdal.GetDriverCount()):
d = gdal.GetDriver(i)
drivers[d.ShortName] = d.GetMetadata()
return drivers | [
"Returns",
"a",
"dictionary",
"of",
"enabled",
"GDAL",
"Driver",
"metadata",
"keyed",
"by",
"the",
"ShortName",
"attribute",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L18-L26 | [
"def",
"available_drivers",
"(",
")",
":",
"drivers",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"gdal",
".",
"GetDriverCount",
"(",
")",
")",
":",
"d",
"=",
"gdal",
".",
"GetDriver",
"(",
"i",
")",
"drivers",
"[",
"d",
".",
"ShortName",
"]",
... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | driver_for_path | Returns the gdal.Driver for a path or None based on the file extension.
Arguments:
path -- file path as str with a GDAL supported file extension | greenwich/raster.py | def driver_for_path(path, drivers=None):
"""Returns the gdal.Driver for a path or None based on the file extension.
Arguments:
path -- file path as str with a GDAL supported file extension
"""
ext = (os.path.splitext(path)[1][1:] or path).lower()
drivers = drivers or ImageDriver.registry if ext... | def driver_for_path(path, drivers=None):
"""Returns the gdal.Driver for a path or None based on the file extension.
Arguments:
path -- file path as str with a GDAL supported file extension
"""
ext = (os.path.splitext(path)[1][1:] or path).lower()
drivers = drivers or ImageDriver.registry if ext... | [
"Returns",
"the",
"gdal",
".",
"Driver",
"for",
"a",
"path",
"or",
"None",
"based",
"on",
"the",
"file",
"extension",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L28-L39 | [
"def",
"driver_for_path",
"(",
"path",
",",
"drivers",
"=",
"None",
")",
":",
"ext",
"=",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
"or",
"path",
")",
".",
"lower",
"(",
")",
"drivers",
"=",
... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | geom_to_array | Converts an OGR polygon to a 2D NumPy array.
Arguments:
geom -- OGR Geometry
size -- array size in pixels as a tuple of (width, height)
affine -- AffineTransform | greenwich/raster.py | def geom_to_array(geom, size, affine):
"""Converts an OGR polygon to a 2D NumPy array.
Arguments:
geom -- OGR Geometry
size -- array size in pixels as a tuple of (width, height)
affine -- AffineTransform
"""
driver = ImageDriver('MEM')
rast = driver.raster(driver.ShortName, size)
ra... | def geom_to_array(geom, size, affine):
"""Converts an OGR polygon to a 2D NumPy array.
Arguments:
geom -- OGR Geometry
size -- array size in pixels as a tuple of (width, height)
affine -- AffineTransform
"""
driver = ImageDriver('MEM')
rast = driver.raster(driver.ShortName, size)
ra... | [
"Converts",
"an",
"OGR",
"polygon",
"to",
"a",
"2D",
"NumPy",
"array",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L45-L61 | [
"def",
"geom_to_array",
"(",
"geom",
",",
"size",
",",
"affine",
")",
":",
"driver",
"=",
"ImageDriver",
"(",
"'MEM'",
")",
"rast",
"=",
"driver",
".",
"raster",
"(",
"driver",
".",
"ShortName",
",",
"size",
")",
"rast",
".",
"affine",
"=",
"affine",
... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | rasterize | Returns a Raster from layer features.
Arguments:
layer -- Layer to rasterize
rast -- Raster with target affine, size, and sref | greenwich/raster.py | def rasterize(layer, rast):
"""Returns a Raster from layer features.
Arguments:
layer -- Layer to rasterize
rast -- Raster with target affine, size, and sref
"""
driver = ImageDriver('MEM')
r2 = driver.raster(driver.ShortName, rast.size)
r2.affine = rast.affine
sref = rast.sref
... | def rasterize(layer, rast):
"""Returns a Raster from layer features.
Arguments:
layer -- Layer to rasterize
rast -- Raster with target affine, size, and sref
"""
driver = ImageDriver('MEM')
r2 = driver.raster(driver.ShortName, rast.size)
r2.affine = rast.affine
sref = rast.sref
... | [
"Returns",
"a",
"Raster",
"from",
"layer",
"features",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L63-L82 | [
"def",
"rasterize",
"(",
"layer",
",",
"rast",
")",
":",
"driver",
"=",
"ImageDriver",
"(",
"'MEM'",
")",
"r2",
"=",
"driver",
".",
"raster",
"(",
"driver",
".",
"ShortName",
",",
"rast",
".",
"size",
")",
"r2",
".",
"affine",
"=",
"rast",
".",
"af... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | open | Returns a Raster instance.
Arguments:
path -- local or remote path as str or file-like object
Keyword args:
mode -- gdal constant representing access mode | greenwich/raster.py | def open(path, mode=gdalconst.GA_ReadOnly):
"""Returns a Raster instance.
Arguments:
path -- local or remote path as str or file-like object
Keyword args:
mode -- gdal constant representing access mode
"""
path = getattr(path, 'name', path)
try:
return Raster(vsiprefix(path), mo... | def open(path, mode=gdalconst.GA_ReadOnly):
"""Returns a Raster instance.
Arguments:
path -- local or remote path as str or file-like object
Keyword args:
mode -- gdal constant representing access mode
"""
path = getattr(path, 'name', path)
try:
return Raster(vsiprefix(path), mo... | [
"Returns",
"a",
"Raster",
"instance",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L685-L705 | [
"def",
"open",
"(",
"path",
",",
"mode",
"=",
"gdalconst",
".",
"GA_ReadOnly",
")",
":",
"path",
"=",
"getattr",
"(",
"path",
",",
"'name'",
",",
"path",
")",
"try",
":",
"return",
"Raster",
"(",
"vsiprefix",
"(",
"path",
")",
",",
"mode",
")",
"ex... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | frombytes | Returns an in-memory raster initialized from a pixel buffer.
Arguments:
data -- byte buffer of raw pixel data
size -- two or three-tuple of (xsize, ysize, bandcount)
bandtype -- band data type | greenwich/raster.py | def frombytes(data, size, bandtype=gdal.GDT_Byte):
"""Returns an in-memory raster initialized from a pixel buffer.
Arguments:
data -- byte buffer of raw pixel data
size -- two or three-tuple of (xsize, ysize, bandcount)
bandtype -- band data type
"""
r = ImageDriver('MEM').raster('', size, ... | def frombytes(data, size, bandtype=gdal.GDT_Byte):
"""Returns an in-memory raster initialized from a pixel buffer.
Arguments:
data -- byte buffer of raw pixel data
size -- two or three-tuple of (xsize, ysize, bandcount)
bandtype -- band data type
"""
r = ImageDriver('MEM').raster('', size, ... | [
"Returns",
"an",
"in",
"-",
"memory",
"raster",
"initialized",
"from",
"a",
"pixel",
"buffer",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L707-L717 | [
"def",
"frombytes",
"(",
"data",
",",
"size",
",",
"bandtype",
"=",
"gdal",
".",
"GDT_Byte",
")",
":",
"r",
"=",
"ImageDriver",
"(",
"'MEM'",
")",
".",
"raster",
"(",
"''",
",",
"size",
",",
"bandtype",
")",
"r",
".",
"frombytes",
"(",
"data",
")",... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | AffineTransform.project | Convert image pixel/line coordinates to georeferenced x/y, return a
generator of two-tuples.
Arguments:
coords -- input coordinates as iterable containing two-tuples/lists
such as ((0, 0), (10, 10)) | greenwich/raster.py | def project(self, coords):
"""Convert image pixel/line coordinates to georeferenced x/y, return a
generator of two-tuples.
Arguments:
coords -- input coordinates as iterable containing two-tuples/lists
such as ((0, 0), (10, 10))
"""
geotransform = self.tuple
... | def project(self, coords):
"""Convert image pixel/line coordinates to georeferenced x/y, return a
generator of two-tuples.
Arguments:
coords -- input coordinates as iterable containing two-tuples/lists
such as ((0, 0), (10, 10))
"""
geotransform = self.tuple
... | [
"Convert",
"image",
"pixel",
"/",
"line",
"coordinates",
"to",
"georeferenced",
"x",
"/",
"y",
"return",
"a",
"generator",
"of",
"two",
"-",
"tuples",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L129-L144 | [
"def",
"project",
"(",
"self",
",",
"coords",
")",
":",
"geotransform",
"=",
"self",
".",
"tuple",
"for",
"x",
",",
"y",
"in",
"coords",
":",
"geo_x",
"=",
"geotransform",
"[",
"0",
"]",
"+",
"geotransform",
"[",
"1",
"]",
"*",
"x",
"+",
"geotransf... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | AffineTransform.transform | Transform from projection coordinates (Xp,Yp) space to pixel/line
(P,L) raster space, based on the provided geotransformation.
Arguments:
coords -- input coordinates as iterable containing two-tuples/lists
such as ((-120, 38), (-121, 39)) | greenwich/raster.py | def transform(self, coords):
"""Transform from projection coordinates (Xp,Yp) space to pixel/line
(P,L) raster space, based on the provided geotransformation.
Arguments:
coords -- input coordinates as iterable containing two-tuples/lists
such as ((-120, 38), (-121, 39))
... | def transform(self, coords):
"""Transform from projection coordinates (Xp,Yp) space to pixel/line
(P,L) raster space, based on the provided geotransformation.
Arguments:
coords -- input coordinates as iterable containing two-tuples/lists
such as ((-120, 38), (-121, 39))
... | [
"Transform",
"from",
"projection",
"coordinates",
"(",
"Xp",
"Yp",
")",
"space",
"to",
"pixel",
"/",
"line",
"(",
"P",
"L",
")",
"raster",
"space",
"based",
"on",
"the",
"provided",
"geotransformation",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L146-L159 | [
"def",
"transform",
"(",
"self",
",",
"coords",
")",
":",
"# Use local vars for better performance here.",
"origin_x",
",",
"origin_y",
"=",
"self",
".",
"origin",
"sx",
",",
"sy",
"=",
"self",
".",
"scale",
"return",
"[",
"(",
"int",
"(",
"math",
".",
"fl... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | ImageDriver.copy | Returns a copied Raster instance.
Arguments:
source -- the source Raster instance or filepath as str
dest -- destination filepath as str | greenwich/raster.py | def copy(self, source, dest):
"""Returns a copied Raster instance.
Arguments:
source -- the source Raster instance or filepath as str
dest -- destination filepath as str
"""
if not self.copyable:
raise IOError('Driver does not support raster copying')
... | def copy(self, source, dest):
"""Returns a copied Raster instance.
Arguments:
source -- the source Raster instance or filepath as str
dest -- destination filepath as str
"""
if not self.copyable:
raise IOError('Driver does not support raster copying')
... | [
"Returns",
"a",
"copied",
"Raster",
"instance",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L204-L226 | [
"def",
"copy",
"(",
"self",
",",
"source",
",",
"dest",
")",
":",
"if",
"not",
"self",
".",
"copyable",
":",
"raise",
"IOError",
"(",
"'Driver does not support raster copying'",
")",
"if",
"not",
"isinstance",
"(",
"source",
",",
"Raster",
")",
":",
"sourc... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | ImageDriver.Create | Calls Driver.Create() with optionally provided creation options as
dict, or falls back to driver specific defaults. | greenwich/raster.py | def Create(self, *args, **kwargs):
"""Calls Driver.Create() with optionally provided creation options as
dict, or falls back to driver specific defaults.
"""
if not self.writable:
raise IOError('Driver does not support raster creation')
options = kwargs.pop('options',... | def Create(self, *args, **kwargs):
"""Calls Driver.Create() with optionally provided creation options as
dict, or falls back to driver specific defaults.
"""
if not self.writable:
raise IOError('Driver does not support raster creation')
options = kwargs.pop('options',... | [
"Calls",
"Driver",
".",
"Create",
"()",
"with",
"optionally",
"provided",
"creation",
"options",
"as",
"dict",
"or",
"falls",
"back",
"to",
"driver",
"specific",
"defaults",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L228-L236 | [
"def",
"Create",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"writable",
":",
"raise",
"IOError",
"(",
"'Driver does not support raster creation'",
")",
"options",
"=",
"kwargs",
".",
"pop",
"(",
"'options'",... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | ImageDriver.options | Returns a dict of driver specific raster creation options.
See GDAL format docs at http://www.gdal.org/formats_list.html | greenwich/raster.py | def options(self):
"""Returns a dict of driver specific raster creation options.
See GDAL format docs at http://www.gdal.org/formats_list.html
"""
if self._options is None:
try:
elem = ET.fromstring(
self.info.get('DMD_CREATIONOPTIONLIST',... | def options(self):
"""Returns a dict of driver specific raster creation options.
See GDAL format docs at http://www.gdal.org/formats_list.html
"""
if self._options is None:
try:
elem = ET.fromstring(
self.info.get('DMD_CREATIONOPTIONLIST',... | [
"Returns",
"a",
"dict",
"of",
"driver",
"specific",
"raster",
"creation",
"options",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L253-L271 | [
"def",
"options",
"(",
"self",
")",
":",
"if",
"self",
".",
"_options",
"is",
"None",
":",
"try",
":",
"elem",
"=",
"ET",
".",
"fromstring",
"(",
"self",
".",
"info",
".",
"get",
"(",
"'DMD_CREATIONOPTIONLIST'",
",",
"''",
")",
")",
"except",
"ET",
... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | ImageDriver.raster | Returns a new Raster instance.
gdal.Driver.Create() does not support all formats.
Arguments:
path -- file object or path as str
size -- two or three-tuple of (xsize, ysize, bandcount)
bandtype -- GDAL pixel data type | greenwich/raster.py | def raster(self, path, size, bandtype=gdal.GDT_Byte):
"""Returns a new Raster instance.
gdal.Driver.Create() does not support all formats.
Arguments:
path -- file object or path as str
size -- two or three-tuple of (xsize, ysize, bandcount)
bandtype -- GDAL pixel data t... | def raster(self, path, size, bandtype=gdal.GDT_Byte):
"""Returns a new Raster instance.
gdal.Driver.Create() does not support all formats.
Arguments:
path -- file object or path as str
size -- two or three-tuple of (xsize, ysize, bandcount)
bandtype -- GDAL pixel data t... | [
"Returns",
"a",
"new",
"Raster",
"instance",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L281-L307 | [
"def",
"raster",
"(",
"self",
",",
"path",
",",
"size",
",",
"bandtype",
"=",
"gdal",
".",
"GDT_Byte",
")",
":",
"path",
"=",
"getattr",
"(",
"path",
",",
"'name'",
",",
"path",
")",
"try",
":",
"is_multiband",
"=",
"len",
"(",
"size",
")",
">",
... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.SetGeoTransform | Sets the affine transformation.
Intercepts the gdal.Dataset call to ensure use as a property setter.
Arguments:
affine -- AffineTransform or six-tuple of geotransformation values | greenwich/raster.py | def SetGeoTransform(self, affine):
"""Sets the affine transformation.
Intercepts the gdal.Dataset call to ensure use as a property setter.
Arguments:
affine -- AffineTransform or six-tuple of geotransformation values
"""
if isinstance(affine, collections.Sequence):
... | def SetGeoTransform(self, affine):
"""Sets the affine transformation.
Intercepts the gdal.Dataset call to ensure use as a property setter.
Arguments:
affine -- AffineTransform or six-tuple of geotransformation values
"""
if isinstance(affine, collections.Sequence):
... | [
"Sets",
"the",
"affine",
"transformation",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L410-L421 | [
"def",
"SetGeoTransform",
"(",
"self",
",",
"affine",
")",
":",
"if",
"isinstance",
"(",
"affine",
",",
"collections",
".",
"Sequence",
")",
":",
"affine",
"=",
"AffineTransform",
"(",
"*",
"affine",
")",
"self",
".",
"_affine",
"=",
"affine",
"self",
".... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.array | Returns an NDArray, optionally subset by spatial envelope.
Keyword args:
envelope -- coordinate extent tuple or Envelope | greenwich/raster.py | def array(self, envelope=()):
"""Returns an NDArray, optionally subset by spatial envelope.
Keyword args:
envelope -- coordinate extent tuple or Envelope
"""
args = ()
if envelope:
args = self.get_offset(envelope)
return self.ds.ReadAsArray(*args) | def array(self, envelope=()):
"""Returns an NDArray, optionally subset by spatial envelope.
Keyword args:
envelope -- coordinate extent tuple or Envelope
"""
args = ()
if envelope:
args = self.get_offset(envelope)
return self.ds.ReadAsArray(*args) | [
"Returns",
"an",
"NDArray",
"optionally",
"subset",
"by",
"spatial",
"envelope",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L425-L434 | [
"def",
"array",
"(",
"self",
",",
"envelope",
"=",
"(",
")",
")",
":",
"args",
"=",
"(",
")",
"if",
"envelope",
":",
"args",
"=",
"self",
".",
"get_offset",
"(",
"envelope",
")",
"return",
"self",
".",
"ds",
".",
"ReadAsArray",
"(",
"*",
"args",
... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.envelope | Returns the minimum bounding rectangle as a tuple of min X, min Y,
max X, max Y. | greenwich/raster.py | def envelope(self):
"""Returns the minimum bounding rectangle as a tuple of min X, min Y,
max X, max Y.
"""
if self._envelope is None:
origin = self.affine.origin
ur_x = origin[0] + self.ds.RasterXSize * self.affine.scale[0]
ll_y = origin[1] + self.ds.... | def envelope(self):
"""Returns the minimum bounding rectangle as a tuple of min X, min Y,
max X, max Y.
"""
if self._envelope is None:
origin = self.affine.origin
ur_x = origin[0] + self.ds.RasterXSize * self.affine.scale[0]
ll_y = origin[1] + self.ds.... | [
"Returns",
"the",
"minimum",
"bounding",
"rectangle",
"as",
"a",
"tuple",
"of",
"min",
"X",
"min",
"Y",
"max",
"X",
"max",
"Y",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L459-L468 | [
"def",
"envelope",
"(",
"self",
")",
":",
"if",
"self",
".",
"_envelope",
"is",
"None",
":",
"origin",
"=",
"self",
".",
"affine",
".",
"origin",
"ur_x",
"=",
"origin",
"[",
"0",
"]",
"+",
"self",
".",
"ds",
".",
"RasterXSize",
"*",
"self",
".",
... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.get_offset | Returns a 4-tuple pixel window (x_offset, y_offset, x_size, y_size).
Arguments:
envelope -- coordinate extent tuple or Envelope | greenwich/raster.py | def get_offset(self, envelope):
"""Returns a 4-tuple pixel window (x_offset, y_offset, x_size, y_size).
Arguments:
envelope -- coordinate extent tuple or Envelope
"""
if isinstance(envelope, collections.Sequence):
envelope = Envelope(envelope)
if not (self.en... | def get_offset(self, envelope):
"""Returns a 4-tuple pixel window (x_offset, y_offset, x_size, y_size).
Arguments:
envelope -- coordinate extent tuple or Envelope
"""
if isinstance(envelope, collections.Sequence):
envelope = Envelope(envelope)
if not (self.en... | [
"Returns",
"a",
"4",
"-",
"tuple",
"pixel",
"window",
"(",
"x_offset",
"y_offset",
"x_size",
"y_size",
")",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L474-L488 | [
"def",
"get_offset",
"(",
"self",
",",
"envelope",
")",
":",
"if",
"isinstance",
"(",
"envelope",
",",
"collections",
".",
"Sequence",
")",
":",
"envelope",
"=",
"Envelope",
"(",
"envelope",
")",
"if",
"not",
"(",
"self",
".",
"envelope",
".",
"contains"... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.driver | Returns the underlying ImageDriver instance. | greenwich/raster.py | def driver(self):
"""Returns the underlying ImageDriver instance."""
if self._driver is None:
self._driver = ImageDriver(self.ds.GetDriver())
return self._driver | def driver(self):
"""Returns the underlying ImageDriver instance."""
if self._driver is None:
self._driver = ImageDriver(self.ds.GetDriver())
return self._driver | [
"Returns",
"the",
"underlying",
"ImageDriver",
"instance",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L491-L495 | [
"def",
"driver",
"(",
"self",
")",
":",
"if",
"self",
".",
"_driver",
"is",
"None",
":",
"self",
".",
"_driver",
"=",
"ImageDriver",
"(",
"self",
".",
"ds",
".",
"GetDriver",
"(",
")",
")",
"return",
"self",
".",
"_driver"
] | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.new | Derive new Raster instances.
Keyword args:
size -- tuple of image size (width, height)
affine -- AffineTransform or six-tuple of geotransformation values | greenwich/raster.py | def new(self, size=(), affine=None):
"""Derive new Raster instances.
Keyword args:
size -- tuple of image size (width, height)
affine -- AffineTransform or six-tuple of geotransformation values
"""
size = size or self.size + (len(self),)
band = self.ds.GetRasterB... | def new(self, size=(), affine=None):
"""Derive new Raster instances.
Keyword args:
size -- tuple of image size (width, height)
affine -- AffineTransform or six-tuple of geotransformation values
"""
size = size or self.size + (len(self),)
band = self.ds.GetRasterB... | [
"Derive",
"new",
"Raster",
"instances",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L497-L516 | [
"def",
"new",
"(",
"self",
",",
"size",
"=",
"(",
")",
",",
"affine",
"=",
"None",
")",
":",
"size",
"=",
"size",
"or",
"self",
".",
"size",
"+",
"(",
"len",
"(",
"self",
")",
",",
")",
"band",
"=",
"self",
".",
"ds",
".",
"GetRasterBand",
"(... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.masked_array | Returns a MaskedArray using nodata values.
Keyword args:
geometry -- any geometry, envelope, or coordinate extent tuple | greenwich/raster.py | def masked_array(self, geometry=None):
"""Returns a MaskedArray using nodata values.
Keyword args:
geometry -- any geometry, envelope, or coordinate extent tuple
"""
if geometry is None:
return self._masked_array()
geom = transform(geometry, self.sref)
... | def masked_array(self, geometry=None):
"""Returns a MaskedArray using nodata values.
Keyword args:
geometry -- any geometry, envelope, or coordinate extent tuple
"""
if geometry is None:
return self._masked_array()
geom = transform(geometry, self.sref)
... | [
"Returns",
"a",
"MaskedArray",
"using",
"nodata",
"values",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L544-L561 | [
"def",
"masked_array",
"(",
"self",
",",
"geometry",
"=",
"None",
")",
":",
"if",
"geometry",
"is",
"None",
":",
"return",
"self",
".",
"_masked_array",
"(",
")",
"geom",
"=",
"transform",
"(",
"geometry",
",",
"self",
".",
"sref",
")",
"env",
"=",
"... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.nodata | Returns read only property for band nodata value, assuming single
band rasters for now. | greenwich/raster.py | def nodata(self):
"""Returns read only property for band nodata value, assuming single
band rasters for now.
"""
if self._nodata is None:
self._nodata = self[0].GetNoDataValue()
return self._nodata | def nodata(self):
"""Returns read only property for band nodata value, assuming single
band rasters for now.
"""
if self._nodata is None:
self._nodata = self[0].GetNoDataValue()
return self._nodata | [
"Returns",
"read",
"only",
"property",
"for",
"band",
"nodata",
"value",
"assuming",
"single",
"band",
"rasters",
"for",
"now",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L564-L570 | [
"def",
"nodata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_nodata",
"is",
"None",
":",
"self",
".",
"_nodata",
"=",
"self",
"[",
"0",
"]",
".",
"GetNoDataValue",
"(",
")",
"return",
"self",
".",
"_nodata"
] | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.ReadRaster | Returns raster data bytes for partial or full extent.
Overrides gdal.Dataset.ReadRaster() with the full raster size by
default. | greenwich/raster.py | def ReadRaster(self, *args, **kwargs):
"""Returns raster data bytes for partial or full extent.
Overrides gdal.Dataset.ReadRaster() with the full raster size by
default.
"""
args = args or (0, 0, self.ds.RasterXSize, self.ds.RasterYSize)
return self.ds.ReadRaster(*args, ... | def ReadRaster(self, *args, **kwargs):
"""Returns raster data bytes for partial or full extent.
Overrides gdal.Dataset.ReadRaster() with the full raster size by
default.
"""
args = args or (0, 0, self.ds.RasterXSize, self.ds.RasterYSize)
return self.ds.ReadRaster(*args, ... | [
"Returns",
"raster",
"data",
"bytes",
"for",
"partial",
"or",
"full",
"extent",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L572-L579 | [
"def",
"ReadRaster",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"args",
"or",
"(",
"0",
",",
"0",
",",
"self",
".",
"ds",
".",
"RasterXSize",
",",
"self",
".",
"ds",
".",
"RasterYSize",
")",
"return",
"self",
... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.resample | Returns a new instance resampled to provided size.
Arguments:
size -- tuple of x,y image dimensions | greenwich/raster.py | def resample(self, size, interpolation=gdalconst.GRA_NearestNeighbour):
"""Returns a new instance resampled to provided size.
Arguments:
size -- tuple of x,y image dimensions
"""
# Find the scaling factor for pixel size.
factors = (size[0] / float(self.RasterXSize),
... | def resample(self, size, interpolation=gdalconst.GRA_NearestNeighbour):
"""Returns a new instance resampled to provided size.
Arguments:
size -- tuple of x,y image dimensions
"""
# Find the scaling factor for pixel size.
factors = (size[0] / float(self.RasterXSize),
... | [
"Returns",
"a",
"new",
"instance",
"resampled",
"to",
"provided",
"size",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L581-L596 | [
"def",
"resample",
"(",
"self",
",",
"size",
",",
"interpolation",
"=",
"gdalconst",
".",
"GRA_NearestNeighbour",
")",
":",
"# Find the scaling factor for pixel size.",
"factors",
"=",
"(",
"size",
"[",
"0",
"]",
"/",
"float",
"(",
"self",
".",
"RasterXSize",
... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.save | Save this instance to the path and format provided.
Arguments:
to -- output path as str, file, or MemFileIO instance
Keyword args:
driver -- GDAL driver name as string or ImageDriver | greenwich/raster.py | def save(self, to, driver=None):
"""Save this instance to the path and format provided.
Arguments:
to -- output path as str, file, or MemFileIO instance
Keyword args:
driver -- GDAL driver name as string or ImageDriver
"""
path = getattr(to, 'name', to)
i... | def save(self, to, driver=None):
"""Save this instance to the path and format provided.
Arguments:
to -- output path as str, file, or MemFileIO instance
Keyword args:
driver -- GDAL driver name as string or ImageDriver
"""
path = getattr(to, 'name', to)
i... | [
"Save",
"this",
"instance",
"to",
"the",
"path",
"and",
"format",
"provided",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L598-L613 | [
"def",
"save",
"(",
"self",
",",
"to",
",",
"driver",
"=",
"None",
")",
":",
"path",
"=",
"getattr",
"(",
"to",
",",
"'name'",
",",
"to",
")",
"if",
"not",
"driver",
"and",
"hasattr",
"(",
"path",
",",
"'encode'",
")",
":",
"driver",
"=",
"driver... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.SetProjection | Sets the spatial reference.
Intercepts the gdal.Dataset call to ensure use as a property setter.
Arguments:
sref -- SpatialReference or any format supported by the constructor | greenwich/raster.py | def SetProjection(self, sref):
"""Sets the spatial reference.
Intercepts the gdal.Dataset call to ensure use as a property setter.
Arguments:
sref -- SpatialReference or any format supported by the constructor
"""
if not hasattr(sref, 'ExportToWkt'):
sref = ... | def SetProjection(self, sref):
"""Sets the spatial reference.
Intercepts the gdal.Dataset call to ensure use as a property setter.
Arguments:
sref -- SpatialReference or any format supported by the constructor
"""
if not hasattr(sref, 'ExportToWkt'):
sref = ... | [
"Sets",
"the",
"spatial",
"reference",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L618-L629 | [
"def",
"SetProjection",
"(",
"self",
",",
"sref",
")",
":",
"if",
"not",
"hasattr",
"(",
"sref",
",",
"'ExportToWkt'",
")",
":",
"sref",
"=",
"SpatialReference",
"(",
"sref",
")",
"self",
".",
"_sref",
"=",
"sref",
"self",
".",
"ds",
".",
"SetProjectio... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.shape | Returns a tuple of row, column, (band count if multidimensional). | greenwich/raster.py | def shape(self):
"""Returns a tuple of row, column, (band count if multidimensional)."""
shp = (self.ds.RasterYSize, self.ds.RasterXSize, self.ds.RasterCount)
return shp[:2] if shp[2] <= 1 else shp | def shape(self):
"""Returns a tuple of row, column, (band count if multidimensional)."""
shp = (self.ds.RasterYSize, self.ds.RasterXSize, self.ds.RasterCount)
return shp[:2] if shp[2] <= 1 else shp | [
"Returns",
"a",
"tuple",
"of",
"row",
"column",
"(",
"band",
"count",
"if",
"multidimensional",
")",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L634-L637 | [
"def",
"shape",
"(",
"self",
")",
":",
"shp",
"=",
"(",
"self",
".",
"ds",
".",
"RasterYSize",
",",
"self",
".",
"ds",
".",
"RasterXSize",
",",
"self",
".",
"ds",
".",
"RasterCount",
")",
"return",
"shp",
"[",
":",
"2",
"]",
"if",
"shp",
"[",
"... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | Raster.warp | Returns a new reprojected instance.
Arguments:
to_sref -- spatial reference as a proj4 or wkt string, or a
SpatialReference
Keyword args:
dest -- filepath as str
interpolation -- GDAL interpolation type | greenwich/raster.py | def warp(self, to_sref, dest=None, interpolation=gdalconst.GRA_NearestNeighbour):
"""Returns a new reprojected instance.
Arguments:
to_sref -- spatial reference as a proj4 or wkt string, or a
SpatialReference
Keyword args:
dest -- filepath as str
interpolation --... | def warp(self, to_sref, dest=None, interpolation=gdalconst.GRA_NearestNeighbour):
"""Returns a new reprojected instance.
Arguments:
to_sref -- spatial reference as a proj4 or wkt string, or a
SpatialReference
Keyword args:
dest -- filepath as str
interpolation --... | [
"Returns",
"a",
"new",
"reprojected",
"instance",
"."
] | bkg/greenwich | python | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L644-L682 | [
"def",
"warp",
"(",
"self",
",",
"to_sref",
",",
"dest",
"=",
"None",
",",
"interpolation",
"=",
"gdalconst",
".",
"GRA_NearestNeighbour",
")",
":",
"if",
"not",
"hasattr",
"(",
"to_sref",
",",
"'ExportToWkt'",
")",
":",
"to_sref",
"=",
"SpatialReference",
... | 57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141 |
test | calc_chunklen | computes the ideal conversion ratio for the given alphabet.
A ratio is considered ideal when the number of bits in one output
encoding chunk that don't add up to one input encoding chunk is minimal. | pwm/encoding.py | def calc_chunklen(alph_len):
'''
computes the ideal conversion ratio for the given alphabet.
A ratio is considered ideal when the number of bits in one output
encoding chunk that don't add up to one input encoding chunk is minimal.
'''
binlen, enclen = min([
(i, i*8 / m... | def calc_chunklen(alph_len):
'''
computes the ideal conversion ratio for the given alphabet.
A ratio is considered ideal when the number of bits in one output
encoding chunk that don't add up to one input encoding chunk is minimal.
'''
binlen, enclen = min([
(i, i*8 / m... | [
"computes",
"the",
"ideal",
"conversion",
"ratio",
"for",
"the",
"given",
"alphabet",
".",
"A",
"ratio",
"is",
"considered",
"ideal",
"when",
"the",
"number",
"of",
"bits",
"in",
"one",
"output",
"encoding",
"chunk",
"that",
"don",
"t",
"add",
"up",
"to",
... | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/encoding.py#L22-L33 | [
"def",
"calc_chunklen",
"(",
"alph_len",
")",
":",
"binlen",
",",
"enclen",
"=",
"min",
"(",
"[",
"(",
"i",
",",
"i",
"*",
"8",
"/",
"math",
".",
"log",
"(",
"alph_len",
",",
"2",
")",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"7",
")",
... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | lookup_alphabet | retrieves a named charset or treats the input as a custom alphabet and use that | pwm/encoding.py | def lookup_alphabet(charset):
'''
retrieves a named charset or treats the input as a custom alphabet and use that
'''
if charset in PRESETS:
return PRESETS[charset]
if len(charset) < 16:
_logger.warning('very small alphabet in use, possibly a failed lookup?')
return charset | def lookup_alphabet(charset):
'''
retrieves a named charset or treats the input as a custom alphabet and use that
'''
if charset in PRESETS:
return PRESETS[charset]
if len(charset) < 16:
_logger.warning('very small alphabet in use, possibly a failed lookup?')
return charset | [
"retrieves",
"a",
"named",
"charset",
"or",
"treats",
"the",
"input",
"as",
"a",
"custom",
"alphabet",
"and",
"use",
"that"
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/encoding.py#L89-L97 | [
"def",
"lookup_alphabet",
"(",
"charset",
")",
":",
"if",
"charset",
"in",
"PRESETS",
":",
"return",
"PRESETS",
"[",
"charset",
"]",
"if",
"len",
"(",
"charset",
")",
"<",
"16",
":",
"_logger",
".",
"warning",
"(",
"'very small alphabet in use, possibly a fail... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | Encoder._encode_chunk | gets a chunk from the input data, converts it to a number and
encodes that number | pwm/encoding.py | def _encode_chunk(self, data, index):
'''
gets a chunk from the input data, converts it to a number and
encodes that number
'''
chunk = self._get_chunk(data, index)
return self._encode_long(self._chunk_to_long(chunk)) | def _encode_chunk(self, data, index):
'''
gets a chunk from the input data, converts it to a number and
encodes that number
'''
chunk = self._get_chunk(data, index)
return self._encode_long(self._chunk_to_long(chunk)) | [
"gets",
"a",
"chunk",
"from",
"the",
"input",
"data",
"converts",
"it",
"to",
"a",
"number",
"and",
"encodes",
"that",
"number"
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/encoding.py#L55-L61 | [
"def",
"_encode_chunk",
"(",
"self",
",",
"data",
",",
"index",
")",
":",
"chunk",
"=",
"self",
".",
"_get_chunk",
"(",
"data",
",",
"index",
")",
"return",
"self",
".",
"_encode_long",
"(",
"self",
".",
"_chunk_to_long",
"(",
"chunk",
")",
")"
] | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | Encoder._encode_long | encodes an integer of 8*self.chunklen[0] bits using the specified
alphabet | pwm/encoding.py | def _encode_long(self, val):
'''
encodes an integer of 8*self.chunklen[0] bits using the specified
alphabet
'''
return ''.join([
self.alphabet[(val//len(self.alphabet)**i) % len(self.alphabet)]
for i in reversed(range(self.chunklen[1]))
... | def _encode_long(self, val):
'''
encodes an integer of 8*self.chunklen[0] bits using the specified
alphabet
'''
return ''.join([
self.alphabet[(val//len(self.alphabet)**i) % len(self.alphabet)]
for i in reversed(range(self.chunklen[1]))
... | [
"encodes",
"an",
"integer",
"of",
"8",
"*",
"self",
".",
"chunklen",
"[",
"0",
"]",
"bits",
"using",
"the",
"specified",
"alphabet"
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/encoding.py#L63-L71 | [
"def",
"_encode_long",
"(",
"self",
",",
"val",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"self",
".",
"alphabet",
"[",
"(",
"val",
"//",
"len",
"(",
"self",
".",
"alphabet",
")",
"**",
"i",
")",
"%",
"len",
"(",
"self",
".",
"alphabet",
... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | Encoder._chunk_to_long | parses a chunk of bytes to integer using big-endian representation | pwm/encoding.py | def _chunk_to_long(self, chunk):
'''
parses a chunk of bytes to integer using big-endian representation
'''
return sum([
256**(self.chunklen[0]-1-i) * ord_byte(chunk[i])
for i in range(self.chunklen[0])
]) | def _chunk_to_long(self, chunk):
'''
parses a chunk of bytes to integer using big-endian representation
'''
return sum([
256**(self.chunklen[0]-1-i) * ord_byte(chunk[i])
for i in range(self.chunklen[0])
]) | [
"parses",
"a",
"chunk",
"of",
"bytes",
"to",
"integer",
"using",
"big",
"-",
"endian",
"representation"
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/encoding.py#L73-L80 | [
"def",
"_chunk_to_long",
"(",
"self",
",",
"chunk",
")",
":",
"return",
"sum",
"(",
"[",
"256",
"**",
"(",
"self",
".",
"chunklen",
"[",
"0",
"]",
"-",
"1",
"-",
"i",
")",
"*",
"ord_byte",
"(",
"chunk",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"... | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | Encoder._get_chunk | partition the data into chunks and retrieve the chunk at the given index | pwm/encoding.py | def _get_chunk(self, data, index):
'''
partition the data into chunks and retrieve the chunk at the given index
'''
return data[index*self.chunklen[0]:(index+1)*self.chunklen[0]] | def _get_chunk(self, data, index):
'''
partition the data into chunks and retrieve the chunk at the given index
'''
return data[index*self.chunklen[0]:(index+1)*self.chunklen[0]] | [
"partition",
"the",
"data",
"into",
"chunks",
"and",
"retrieve",
"the",
"chunk",
"at",
"the",
"given",
"index"
] | thusoy/pwm | python | https://github.com/thusoy/pwm/blob/fff7d755c34f3a7235a8bf217ffa2ff5aed4926f/pwm/encoding.py#L82-L86 | [
"def",
"_get_chunk",
"(",
"self",
",",
"data",
",",
"index",
")",
":",
"return",
"data",
"[",
"index",
"*",
"self",
".",
"chunklen",
"[",
"0",
"]",
":",
"(",
"index",
"+",
"1",
")",
"*",
"self",
".",
"chunklen",
"[",
"0",
"]",
"]"
] | fff7d755c34f3a7235a8bf217ffa2ff5aed4926f |
test | memoize | Cache result of function call. | counter_robots/__init__.py | def memoize(func):
"""Cache result of function call."""
cache = {}
@wraps(func)
def inner(filename):
if filename not in cache:
cache[filename] = func(filename)
return cache[filename]
return inner | def memoize(func):
"""Cache result of function call."""
cache = {}
@wraps(func)
def inner(filename):
if filename not in cache:
cache[filename] = func(filename)
return cache[filename]
return inner | [
"Cache",
"result",
"of",
"function",
"call",
"."
] | inveniosoftware/counter-robots | python | https://github.com/inveniosoftware/counter-robots/blob/484943fdc7e08f41d3ad7a9e2229afe0cec05547/counter_robots/__init__.py#L27-L36 | [
"def",
"memoize",
"(",
"func",
")",
":",
"cache",
"=",
"{",
"}",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"filename",
")",
":",
"if",
"filename",
"not",
"in",
"cache",
":",
"cache",
"[",
"filename",
"]",
"=",
"func",
"(",
"filename",
... | 484943fdc7e08f41d3ad7a9e2229afe0cec05547 |
test | _regexp | Get a list of patterns from a file and make a regular expression. | counter_robots/__init__.py | def _regexp(filename):
"""Get a list of patterns from a file and make a regular expression."""
lines = _get_resource_content(filename).decode('utf-8').splitlines()
return re.compile('|'.join(lines)) | def _regexp(filename):
"""Get a list of patterns from a file and make a regular expression."""
lines = _get_resource_content(filename).decode('utf-8').splitlines()
return re.compile('|'.join(lines)) | [
"Get",
"a",
"list",
"of",
"patterns",
"from",
"a",
"file",
"and",
"make",
"a",
"regular",
"expression",
"."
] | inveniosoftware/counter-robots | python | https://github.com/inveniosoftware/counter-robots/blob/484943fdc7e08f41d3ad7a9e2229afe0cec05547/counter_robots/__init__.py#L40-L43 | [
"def",
"_regexp",
"(",
"filename",
")",
":",
"lines",
"=",
"_get_resource_content",
"(",
"filename",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"splitlines",
"(",
")",
"return",
"re",
".",
"compile",
"(",
"'|'",
".",
"join",
"(",
"lines",
")",
")"
] | 484943fdc7e08f41d3ad7a9e2229afe0cec05547 |
test | normalize_date_format | Dates can be defined in many ways, but zipline use
aware datetime objects only. Plus, the software work
with utc timezone so we convert it. | python/dna/time_utils.py | def normalize_date_format(date):
'''
Dates can be defined in many ways, but zipline use
aware datetime objects only. Plus, the software work
with utc timezone so we convert it.
'''
if isinstance(date, int):
# This is probably epoch time
date = time.strftime('%Y-%m-%d %H:%M:%S',
... | def normalize_date_format(date):
'''
Dates can be defined in many ways, but zipline use
aware datetime objects only. Plus, the software work
with utc timezone so we convert it.
'''
if isinstance(date, int):
# This is probably epoch time
date = time.strftime('%Y-%m-%d %H:%M:%S',
... | [
"Dates",
"can",
"be",
"defined",
"in",
"many",
"ways",
"but",
"zipline",
"use",
"aware",
"datetime",
"objects",
"only",
".",
"Plus",
"the",
"software",
"work",
"with",
"utc",
"timezone",
"so",
"we",
"convert",
"it",
"."
] | hivetech/dna | python | https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/time_utils.py#L19-L39 | [
"def",
"normalize_date_format",
"(",
"date",
")",
":",
"if",
"isinstance",
"(",
"date",
",",
"int",
")",
":",
"# This is probably epoch time",
"date",
"=",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
",",
"time",
".",
"localtime",
"(",
"date",
")",
... | 50ad00031be29765b2576fa407d35a36e0608de9 |
test | _detect_timezone | Get timezone as set by the system | python/dna/time_utils.py | def _detect_timezone():
'''
Get timezone as set by the system
'''
default_timezone = 'America/New_York'
locale_code = locale.getdefaultlocale()
return default_timezone if not locale_code[0] else \
str(pytz.country_timezones[locale_code[0][-2:]][0]) | def _detect_timezone():
'''
Get timezone as set by the system
'''
default_timezone = 'America/New_York'
locale_code = locale.getdefaultlocale()
return default_timezone if not locale_code[0] else \
str(pytz.country_timezones[locale_code[0][-2:]][0]) | [
"Get",
"timezone",
"as",
"set",
"by",
"the",
"system"
] | hivetech/dna | python | https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/time_utils.py#L42-L49 | [
"def",
"_detect_timezone",
"(",
")",
":",
"default_timezone",
"=",
"'America/New_York'",
"locale_code",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"return",
"default_timezone",
"if",
"not",
"locale_code",
"[",
"0",
"]",
"else",
"str",
"(",
"pytz",
".",
... | 50ad00031be29765b2576fa407d35a36e0608de9 |
test | api_url | >>> # Harmonize api endpoints
>>> # __version__ should be like major.minor.fix
>>> from my_app import __version__
>>> api_url(__version__, '/some/endpoint')
/v0/some/endpoint | python/dna/apy/utils.py | def api_url(full_version, resource):
'''
>>> # Harmonize api endpoints
>>> # __version__ should be like major.minor.fix
>>> from my_app import __version__
>>> api_url(__version__, '/some/endpoint')
/v0/some/endpoint
'''
return '/v{}/{}'.format(dna.utils.Version(full_version).major, resou... | def api_url(full_version, resource):
'''
>>> # Harmonize api endpoints
>>> # __version__ should be like major.minor.fix
>>> from my_app import __version__
>>> api_url(__version__, '/some/endpoint')
/v0/some/endpoint
'''
return '/v{}/{}'.format(dna.utils.Version(full_version).major, resou... | [
">>>",
"#",
"Harmonize",
"api",
"endpoints",
">>>",
"#",
"__version__",
"should",
"be",
"like",
"major",
".",
"minor",
".",
"fix",
">>>",
"from",
"my_app",
"import",
"__version__",
">>>",
"api_url",
"(",
"__version__",
"/",
"some",
"/",
"endpoint",
")",
"/... | hivetech/dna | python | https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/apy/utils.py#L15-L23 | [
"def",
"api_url",
"(",
"full_version",
",",
"resource",
")",
":",
"return",
"'/v{}/{}'",
".",
"format",
"(",
"dna",
".",
"utils",
".",
"Version",
"(",
"full_version",
")",
".",
"major",
",",
"resource",
")"
] | 50ad00031be29765b2576fa407d35a36e0608de9 |
test | api_doc | >>> # Wrap api endpoints with more details
>>> api_doc('/resource', secure=True, key='value')
GET /resource?secure=true&key=value | python/dna/apy/utils.py | def api_doc(full_version, resource, method='GET', **kwargs):
'''
>>> # Wrap api endpoints with more details
>>> api_doc('/resource', secure=True, key='value')
GET /resource?secure=true&key=value
'''
doc = '{} {}'.format(method, api_url(full_version, resource))
params = '&'.join(['{}={}'.form... | def api_doc(full_version, resource, method='GET', **kwargs):
'''
>>> # Wrap api endpoints with more details
>>> api_doc('/resource', secure=True, key='value')
GET /resource?secure=true&key=value
'''
doc = '{} {}'.format(method, api_url(full_version, resource))
params = '&'.join(['{}={}'.form... | [
">>>",
"#",
"Wrap",
"api",
"endpoints",
"with",
"more",
"details",
">>>",
"api_doc",
"(",
"/",
"resource",
"secure",
"=",
"True",
"key",
"=",
"value",
")",
"GET",
"/",
"resource?secure",
"=",
"true&key",
"=",
"value"
] | hivetech/dna | python | https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/apy/utils.py#L26-L36 | [
"def",
"api_doc",
"(",
"full_version",
",",
"resource",
",",
"method",
"=",
"'GET'",
",",
"*",
"*",
"kwargs",
")",
":",
"doc",
"=",
"'{} {}'",
".",
"format",
"(",
"method",
",",
"api_url",
"(",
"full_version",
",",
"resource",
")",
")",
"params",
"=",
... | 50ad00031be29765b2576fa407d35a36e0608de9 |
test | FinancialDataStatusDatastatus.to_dict | Returns the model properties as a dict | probe/models/financial_data_status_datastatus.py | def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to... | def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to... | [
"Returns",
"the",
"model",
"properties",
"as",
"a",
"dict"
] | loanzen/probe-py | python | https://github.com/loanzen/probe-py/blob/b5dbb0dba26c9b451e9bf1dec9e1aaa7f42d75a5/probe/models/financial_data_status_datastatus.py#L96-L114 | [
"def",
"to_dict",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"attr",
",",
"_",
"in",
"iteritems",
"(",
"self",
".",
"swagger_types",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"attr",
")",
"if",
"isinstance",
"(",
"value",
","... | b5dbb0dba26c9b451e9bf1dec9e1aaa7f42d75a5 |
test | activate_pdb_hook | Catch exceptions with a prompt for post-mortem analyzis | python/dna/debug.py | def activate_pdb_hook():
''' Catch exceptions with a prompt for post-mortem analyzis'''
def debug_exception(type_exception, value, tb):
import pdb
pdb.post_mortem(tb)
import sys
sys.excepthook = debug_exception | def activate_pdb_hook():
''' Catch exceptions with a prompt for post-mortem analyzis'''
def debug_exception(type_exception, value, tb):
import pdb
pdb.post_mortem(tb)
import sys
sys.excepthook = debug_exception | [
"Catch",
"exceptions",
"with",
"a",
"prompt",
"for",
"post",
"-",
"mortem",
"analyzis"
] | hivetech/dna | python | https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/debug.py#L17-L24 | [
"def",
"activate_pdb_hook",
"(",
")",
":",
"def",
"debug_exception",
"(",
"type_exception",
",",
"value",
",",
"tb",
")",
":",
"import",
"pdb",
"pdb",
".",
"post_mortem",
"(",
"tb",
")",
"import",
"sys",
"sys",
".",
"excepthook",
"=",
"debug_exception"
] | 50ad00031be29765b2576fa407d35a36e0608de9 |
test | emphasis | Clearer data printing | python/dna/debug.py | def emphasis(obj, align=True):
''' Clearer data printing '''
if isinstance(obj, dict):
if align:
pretty_msg = os.linesep.join(
["%25s: %s" % (k, obj[k]) for k in sorted(obj.keys())])
else:
pretty_msg = json.dumps(obj, indent=4, sort_keys=True)
else:
... | def emphasis(obj, align=True):
''' Clearer data printing '''
if isinstance(obj, dict):
if align:
pretty_msg = os.linesep.join(
["%25s: %s" % (k, obj[k]) for k in sorted(obj.keys())])
else:
pretty_msg = json.dumps(obj, indent=4, sort_keys=True)
else:
... | [
"Clearer",
"data",
"printing"
] | hivetech/dna | python | https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/debug.py#L28-L38 | [
"def",
"emphasis",
"(",
"obj",
",",
"align",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"if",
"align",
":",
"pretty_msg",
"=",
"os",
".",
"linesep",
".",
"join",
"(",
"[",
"\"%25s: %s\"",
"%",
"(",
"k",
",",
"ob... | 50ad00031be29765b2576fa407d35a36e0608de9 |
test | API.listcoins | Use this function to list all coins with their data which are available on cryptocoincharts.
Usage: http://api.cryptocoincharts.info/listCoins | CryptoCoinChartsApi/CryptoCoinChartsApi.py | def listcoins(self):
'''
Use this function to list all coins with their data which are available on cryptocoincharts.
Usage: http://api.cryptocoincharts.info/listCoins
'''
url = self.API_PATH + 'listCoins'
json_data = json.loads(self._getdata(url))
... | def listcoins(self):
'''
Use this function to list all coins with their data which are available on cryptocoincharts.
Usage: http://api.cryptocoincharts.info/listCoins
'''
url = self.API_PATH + 'listCoins'
json_data = json.loads(self._getdata(url))
... | [
"Use",
"this",
"function",
"to",
"list",
"all",
"coins",
"with",
"their",
"data",
"which",
"are",
"available",
"on",
"cryptocoincharts",
".",
"Usage",
":",
"http",
":",
"//",
"api",
".",
"cryptocoincharts",
".",
"info",
"/",
"listCoins"
] | Dirrot/python-cryptocoincharts-api | python | https://github.com/Dirrot/python-cryptocoincharts-api/blob/8bf7a35c1032847aaea322b304014cd52853c273/CryptoCoinChartsApi/CryptoCoinChartsApi.py#L23-L42 | [
"def",
"listcoins",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"API_PATH",
"+",
"'listCoins'",
"json_data",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"_getdata",
"(",
"url",
")",
")",
"coins",
"=",
"[",
"]",
"for",
"entry",
"in",
"json_data",... | 8bf7a35c1032847aaea322b304014cd52853c273 |
test | API.tradingpair | Use this function to query price and volume data for ONE trading pair.
A list with all coin currencies can be found by using the listcoins method.
A example pair: currency1_currency2 = "doge_btc"
Usage: http://api.cryptocoincharts.info/tradingPair/[currency1_currency2] | CryptoCoinChartsApi/CryptoCoinChartsApi.py | def tradingpair(self, pair):
'''
Use this function to query price and volume data for ONE trading pair.
A list with all coin currencies can be found by using the listcoins method.
A example pair: currency1_currency2 = "doge_btc"
Usage: http://api.cryptocoincharts.info/tradingPai... | def tradingpair(self, pair):
'''
Use this function to query price and volume data for ONE trading pair.
A list with all coin currencies can be found by using the listcoins method.
A example pair: currency1_currency2 = "doge_btc"
Usage: http://api.cryptocoincharts.info/tradingPai... | [
"Use",
"this",
"function",
"to",
"query",
"price",
"and",
"volume",
"data",
"for",
"ONE",
"trading",
"pair",
".",
"A",
"list",
"with",
"all",
"coin",
"currencies",
"can",
"be",
"found",
"by",
"using",
"the",
"listcoins",
"method",
".",
"A",
"example",
"p... | Dirrot/python-cryptocoincharts-api | python | https://github.com/Dirrot/python-cryptocoincharts-api/blob/8bf7a35c1032847aaea322b304014cd52853c273/CryptoCoinChartsApi/CryptoCoinChartsApi.py#L44-L65 | [
"def",
"tradingpair",
"(",
"self",
",",
"pair",
")",
":",
"url",
"=",
"self",
".",
"API_PATH",
"+",
"'tradingPair/'",
"+",
"pair",
"json_data",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"_getdata",
"(",
"url",
")",
")",
"tradingpair",
"=",
"TradingP... | 8bf7a35c1032847aaea322b304014cd52853c273 |
test | API.tradingpairs | Use this function to query price and volume data for MANY trading pairs.
Usage: http://api.cryptocoincharts.info/tradingPairs/[currency1_currency2,currency2_currency3,...]
A example pair: currency1_currency2 = "doge_btc"
currency2_currency3 = "btc_eur"
... | CryptoCoinChartsApi/CryptoCoinChartsApi.py | def tradingpairs(self, pairs):
'''
Use this function to query price and volume data for MANY trading pairs.
Usage: http://api.cryptocoincharts.info/tradingPairs/[currency1_currency2,currency2_currency3,...]
A example pair: currency1_currency2 = "doge_btc"
... | def tradingpairs(self, pairs):
'''
Use this function to query price and volume data for MANY trading pairs.
Usage: http://api.cryptocoincharts.info/tradingPairs/[currency1_currency2,currency2_currency3,...]
A example pair: currency1_currency2 = "doge_btc"
... | [
"Use",
"this",
"function",
"to",
"query",
"price",
"and",
"volume",
"data",
"for",
"MANY",
"trading",
"pairs",
".",
"Usage",
":",
"http",
":",
"//",
"api",
".",
"cryptocoincharts",
".",
"info",
"/",
"tradingPairs",
"/",
"[",
"currency1_currency2",
"currency2... | Dirrot/python-cryptocoincharts-api | python | https://github.com/Dirrot/python-cryptocoincharts-api/blob/8bf7a35c1032847aaea322b304014cd52853c273/CryptoCoinChartsApi/CryptoCoinChartsApi.py#L67-L93 | [
"def",
"tradingpairs",
"(",
"self",
",",
"pairs",
")",
":",
"url",
"=",
"self",
".",
"API_PATH",
"+",
"'tradingPairs/'",
"data",
"=",
"{",
"'pairs'",
":",
"pairs",
"}",
"json_data",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"_getdata",
"(",
"url",
... | 8bf7a35c1032847aaea322b304014cd52853c273 |
test | API._getdata | Wrapper method | CryptoCoinChartsApi/CryptoCoinChartsApi.py | def _getdata(self, url, data = ""):
'''
Wrapper method
'''
request = Request(url)
if data != "":
request = Request(url, urlencode(data))
try:
response = urlopen(request)
except HTTPError as e:
print('The Se... | def _getdata(self, url, data = ""):
'''
Wrapper method
'''
request = Request(url)
if data != "":
request = Request(url, urlencode(data))
try:
response = urlopen(request)
except HTTPError as e:
print('The Se... | [
"Wrapper",
"method"
] | Dirrot/python-cryptocoincharts-api | python | https://github.com/Dirrot/python-cryptocoincharts-api/blob/8bf7a35c1032847aaea322b304014cd52853c273/CryptoCoinChartsApi/CryptoCoinChartsApi.py#L98-L117 | [
"def",
"_getdata",
"(",
"self",
",",
"url",
",",
"data",
"=",
"\"\"",
")",
":",
"request",
"=",
"Request",
"(",
"url",
")",
"if",
"data",
"!=",
"\"\"",
":",
"request",
"=",
"Request",
"(",
"url",
",",
"urlencode",
"(",
"data",
")",
")",
"try",
":... | 8bf7a35c1032847aaea322b304014cd52853c273 |
test | handle_jobs | Connects to the remote master and continuously receives calls, executes
them, then returns a response until interrupted. | highfive/worker.py | async def handle_jobs(job_handler, host, port, *, loop):
"""
Connects to the remote master and continuously receives calls, executes
them, then returns a response until interrupted.
"""
try:
try:
reader, writer = await asyncio.open_connection(host, port, loop=loop)
exce... | async def handle_jobs(job_handler, host, port, *, loop):
"""
Connects to the remote master and continuously receives calls, executes
them, then returns a response until interrupted.
"""
try:
try:
reader, writer = await asyncio.open_connection(host, port, loop=loop)
exce... | [
"Connects",
"to",
"the",
"remote",
"master",
"and",
"continuously",
"receives",
"calls",
"executes",
"them",
"then",
"returns",
"a",
"response",
"until",
"interrupted",
"."
] | abau171/highfive | python | https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/worker.py#L10-L43 | [
"async",
"def",
"handle_jobs",
"(",
"job_handler",
",",
"host",
",",
"port",
",",
"*",
",",
"loop",
")",
":",
"try",
":",
"try",
":",
"reader",
",",
"writer",
"=",
"await",
"asyncio",
".",
"open_connection",
"(",
"host",
",",
"port",
",",
"loop",
"="... | 07b3829331072035ab100d1d66deca3e8f3f372a |
test | worker_main | Starts an asyncio event loop to connect to the master and run jobs. | highfive/worker.py | def worker_main(job_handler, host, port):
"""
Starts an asyncio event loop to connect to the master and run jobs.
"""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
loop.run_until_complete(handle_jobs(job_handler, host, port, loop=loop))
loop.close() | def worker_main(job_handler, host, port):
"""
Starts an asyncio event loop to connect to the master and run jobs.
"""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
loop.run_until_complete(handle_jobs(job_handler, host, port, loop=loop))
loop.close() | [
"Starts",
"an",
"asyncio",
"event",
"loop",
"to",
"connect",
"to",
"the",
"master",
"and",
"run",
"jobs",
"."
] | abau171/highfive | python | https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/worker.py#L46-L54 | [
"def",
"worker_main",
"(",
"job_handler",
",",
"host",
",",
"port",
")",
":",
"loop",
"=",
"asyncio",
".",
"new_event_loop",
"(",
")",
"asyncio",
".",
"set_event_loop",
"(",
"None",
")",
"loop",
".",
"run_until_complete",
"(",
"handle_jobs",
"(",
"job_handle... | 07b3829331072035ab100d1d66deca3e8f3f372a |
test | run_worker_pool | Runs a pool of workers which connect to a remote HighFive master and begin
executing calls. | highfive/worker.py | def run_worker_pool(job_handler, host="localhost", port=48484,
*, max_workers=None):
"""
Runs a pool of workers which connect to a remote HighFive master and begin
executing calls.
"""
if max_workers is None:
max_workers = multiprocessing.cpu_count()
processes = [... | def run_worker_pool(job_handler, host="localhost", port=48484,
*, max_workers=None):
"""
Runs a pool of workers which connect to a remote HighFive master and begin
executing calls.
"""
if max_workers is None:
max_workers = multiprocessing.cpu_count()
processes = [... | [
"Runs",
"a",
"pool",
"of",
"workers",
"which",
"connect",
"to",
"a",
"remote",
"HighFive",
"master",
"and",
"begin",
"executing",
"calls",
"."
] | abau171/highfive | python | https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/worker.py#L57-L79 | [
"def",
"run_worker_pool",
"(",
"job_handler",
",",
"host",
"=",
"\"localhost\"",
",",
"port",
"=",
"48484",
",",
"*",
",",
"max_workers",
"=",
"None",
")",
":",
"if",
"max_workers",
"is",
"None",
":",
"max_workers",
"=",
"multiprocessing",
".",
"cpu_count",
... | 07b3829331072035ab100d1d66deca3e8f3f372a |
test | CompanyDetailCompany.classification | Sets the classification of this CompanyDetailCompany.
Classification of Company
:param classification: The classification of this CompanyDetailCompany.
:type: str | probe/models/company_detail_company.py | def classification(self, classification):
"""
Sets the classification of this CompanyDetailCompany.
Classification of Company
:param classification: The classification of this CompanyDetailCompany.
:type: str
"""
allowed_values = ["Public Limited Indian Non-Gover... | def classification(self, classification):
"""
Sets the classification of this CompanyDetailCompany.
Classification of Company
:param classification: The classification of this CompanyDetailCompany.
:type: str
"""
allowed_values = ["Public Limited Indian Non-Gover... | [
"Sets",
"the",
"classification",
"of",
"this",
"CompanyDetailCompany",
".",
"Classification",
"of",
"Company"
] | loanzen/probe-py | python | https://github.com/loanzen/probe-py/blob/b5dbb0dba26c9b451e9bf1dec9e1aaa7f42d75a5/probe/models/company_detail_company.py#L182-L196 | [
"def",
"classification",
"(",
"self",
",",
"classification",
")",
":",
"allowed_values",
"=",
"[",
"\"Public Limited Indian Non-Government Company\"",
",",
"\"Private Limited Indian Non-Government Company\"",
",",
"\"One Person Company\"",
",",
"\"Private Limited Foreign Company In... | b5dbb0dba26c9b451e9bf1dec9e1aaa7f42d75a5 |
test | LWLink._send_message | Add message to queue and start processing the queue. | lightwave/lightwave.py | def _send_message(self, msg):
"""Add message to queue and start processing the queue."""
LWLink.the_queue.put_nowait(msg)
if LWLink.thread is None or not LWLink.thread.isAlive():
LWLink.thread = Thread(target=self._send_queue)
LWLink.thread.start() | def _send_message(self, msg):
"""Add message to queue and start processing the queue."""
LWLink.the_queue.put_nowait(msg)
if LWLink.thread is None or not LWLink.thread.isAlive():
LWLink.thread = Thread(target=self._send_queue)
LWLink.thread.start() | [
"Add",
"message",
"to",
"queue",
"and",
"start",
"processing",
"the",
"queue",
"."
] | GeoffAtHome/lightwave | python | https://github.com/GeoffAtHome/lightwave/blob/2fab4ee8c9f14dd97dffd4b8cd70b217e884e581/lightwave/lightwave.py#L29-L34 | [
"def",
"_send_message",
"(",
"self",
",",
"msg",
")",
":",
"LWLink",
".",
"the_queue",
".",
"put_nowait",
"(",
"msg",
")",
"if",
"LWLink",
".",
"thread",
"is",
"None",
"or",
"not",
"LWLink",
".",
"thread",
".",
"isAlive",
"(",
")",
":",
"LWLink",
"."... | 2fab4ee8c9f14dd97dffd4b8cd70b217e884e581 |
test | LWLink.turn_on_light | Create the message to turn light on. | lightwave/lightwave.py | def turn_on_light(self, device_id, name):
"""Create the message to turn light on."""
msg = "!%sFdP32|Turn On|%s" % (device_id, name)
self._send_message(msg) | def turn_on_light(self, device_id, name):
"""Create the message to turn light on."""
msg = "!%sFdP32|Turn On|%s" % (device_id, name)
self._send_message(msg) | [
"Create",
"the",
"message",
"to",
"turn",
"light",
"on",
"."
] | GeoffAtHome/lightwave | python | https://github.com/GeoffAtHome/lightwave/blob/2fab4ee8c9f14dd97dffd4b8cd70b217e884e581/lightwave/lightwave.py#L46-L49 | [
"def",
"turn_on_light",
"(",
"self",
",",
"device_id",
",",
"name",
")",
":",
"msg",
"=",
"\"!%sFdP32|Turn On|%s\"",
"%",
"(",
"device_id",
",",
"name",
")",
"self",
".",
"_send_message",
"(",
"msg",
")"
] | 2fab4ee8c9f14dd97dffd4b8cd70b217e884e581 |
test | LWLink.turn_on_switch | Create the message to turn switch on. | lightwave/lightwave.py | def turn_on_switch(self, device_id, name):
"""Create the message to turn switch on."""
msg = "!%sF1|Turn On|%s" % (device_id, name)
self._send_message(msg) | def turn_on_switch(self, device_id, name):
"""Create the message to turn switch on."""
msg = "!%sF1|Turn On|%s" % (device_id, name)
self._send_message(msg) | [
"Create",
"the",
"message",
"to",
"turn",
"switch",
"on",
"."
] | GeoffAtHome/lightwave | python | https://github.com/GeoffAtHome/lightwave/blob/2fab4ee8c9f14dd97dffd4b8cd70b217e884e581/lightwave/lightwave.py#L51-L54 | [
"def",
"turn_on_switch",
"(",
"self",
",",
"device_id",
",",
"name",
")",
":",
"msg",
"=",
"\"!%sF1|Turn On|%s\"",
"%",
"(",
"device_id",
",",
"name",
")",
"self",
".",
"_send_message",
"(",
"msg",
")"
] | 2fab4ee8c9f14dd97dffd4b8cd70b217e884e581 |
test | LWLink.turn_on_with_brightness | Scale brightness from 0..255 to 1..32. | lightwave/lightwave.py | def turn_on_with_brightness(self, device_id, name, brightness):
"""Scale brightness from 0..255 to 1..32."""
brightness_value = round((brightness * 31) / 255) + 1
# F1 = Light on and F0 = light off. FdP[0..32] is brightness. 32 is
# full. We want that when turning the light on.
m... | def turn_on_with_brightness(self, device_id, name, brightness):
"""Scale brightness from 0..255 to 1..32."""
brightness_value = round((brightness * 31) / 255) + 1
# F1 = Light on and F0 = light off. FdP[0..32] is brightness. 32 is
# full. We want that when turning the light on.
m... | [
"Scale",
"brightness",
"from",
"0",
"..",
"255",
"to",
"1",
"..",
"32",
"."
] | GeoffAtHome/lightwave | python | https://github.com/GeoffAtHome/lightwave/blob/2fab4ee8c9f14dd97dffd4b8cd70b217e884e581/lightwave/lightwave.py#L56-L63 | [
"def",
"turn_on_with_brightness",
"(",
"self",
",",
"device_id",
",",
"name",
",",
"brightness",
")",
":",
"brightness_value",
"=",
"round",
"(",
"(",
"brightness",
"*",
"31",
")",
"/",
"255",
")",
"+",
"1",
"# F1 = Light on and F0 = light off. FdP[0..32] is brigh... | 2fab4ee8c9f14dd97dffd4b8cd70b217e884e581 |
test | LWLink.turn_off | Create the message to turn light or switch off. | lightwave/lightwave.py | def turn_off(self, device_id, name):
"""Create the message to turn light or switch off."""
msg = "!%sF0|Turn Off|%s" % (device_id, name)
self._send_message(msg) | def turn_off(self, device_id, name):
"""Create the message to turn light or switch off."""
msg = "!%sF0|Turn Off|%s" % (device_id, name)
self._send_message(msg) | [
"Create",
"the",
"message",
"to",
"turn",
"light",
"or",
"switch",
"off",
"."
] | GeoffAtHome/lightwave | python | https://github.com/GeoffAtHome/lightwave/blob/2fab4ee8c9f14dd97dffd4b8cd70b217e884e581/lightwave/lightwave.py#L65-L68 | [
"def",
"turn_off",
"(",
"self",
",",
"device_id",
",",
"name",
")",
":",
"msg",
"=",
"\"!%sF0|Turn Off|%s\"",
"%",
"(",
"device_id",
",",
"name",
")",
"self",
".",
"_send_message",
"(",
"msg",
")"
] | 2fab4ee8c9f14dd97dffd4b8cd70b217e884e581 |
test | LWLink._send_queue | If the queue is not empty, process the queue. | lightwave/lightwave.py | def _send_queue(self):
"""If the queue is not empty, process the queue."""
while not LWLink.the_queue.empty():
self._send_reliable_message(LWLink.the_queue.get_nowait()) | def _send_queue(self):
"""If the queue is not empty, process the queue."""
while not LWLink.the_queue.empty():
self._send_reliable_message(LWLink.the_queue.get_nowait()) | [
"If",
"the",
"queue",
"is",
"not",
"empty",
"process",
"the",
"queue",
"."
] | GeoffAtHome/lightwave | python | https://github.com/GeoffAtHome/lightwave/blob/2fab4ee8c9f14dd97dffd4b8cd70b217e884e581/lightwave/lightwave.py#L70-L73 | [
"def",
"_send_queue",
"(",
"self",
")",
":",
"while",
"not",
"LWLink",
".",
"the_queue",
".",
"empty",
"(",
")",
":",
"self",
".",
"_send_reliable_message",
"(",
"LWLink",
".",
"the_queue",
".",
"get_nowait",
"(",
")",
")"
] | 2fab4ee8c9f14dd97dffd4b8cd70b217e884e581 |
test | LWLink._send_reliable_message | Send msg to LightwaveRF hub. | lightwave/lightwave.py | def _send_reliable_message(self, msg):
"""Send msg to LightwaveRF hub."""
result = False
max_retries = 15
trans_id = next(LWLink.transaction_id)
msg = "%d,%s" % (trans_id, msg)
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) \
as... | def _send_reliable_message(self, msg):
"""Send msg to LightwaveRF hub."""
result = False
max_retries = 15
trans_id = next(LWLink.transaction_id)
msg = "%d,%s" % (trans_id, msg)
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) \
as... | [
"Send",
"msg",
"to",
"LightwaveRF",
"hub",
"."
] | GeoffAtHome/lightwave | python | https://github.com/GeoffAtHome/lightwave/blob/2fab4ee8c9f14dd97dffd4b8cd70b217e884e581/lightwave/lightwave.py#L75-L132 | [
"def",
"_send_reliable_message",
"(",
"self",
",",
"msg",
")",
":",
"result",
"=",
"False",
"max_retries",
"=",
"15",
"trans_id",
"=",
"next",
"(",
"LWLink",
".",
"transaction_id",
")",
"msg",
"=",
"\"%d,%s\"",
"%",
"(",
"trans_id",
",",
"msg",
")",
"try... | 2fab4ee8c9f14dd97dffd4b8cd70b217e884e581 |
test | create_adapter | Generates a wrapped adapter for the given object
Parameters
----------
obj : list, buffer, array, or file
Raises
------
ValueError
If presented with an object that cannot be adapted
Returns
-------
CMPH capable adapter | cmph/_adapters.py | def create_adapter(cmph, ffi, obj):
""" Generates a wrapped adapter for the given object
Parameters
----------
obj : list, buffer, array, or file
Raises
------
ValueError
If presented with an object that cannot be adapted
Returns
-------
CMPH capable adapter
"""
... | def create_adapter(cmph, ffi, obj):
""" Generates a wrapped adapter for the given object
Parameters
----------
obj : list, buffer, array, or file
Raises
------
ValueError
If presented with an object that cannot be adapted
Returns
-------
CMPH capable adapter
"""
... | [
"Generates",
"a",
"wrapped",
"adapter",
"for",
"the",
"given",
"object"
] | URXtech/cmph-cffi | python | https://github.com/URXtech/cmph-cffi/blob/85298572e51675cd0c7ef1052ed9989b0e57f0cc/cmph/_adapters.py#L99-L141 | [
"def",
"create_adapter",
"(",
"cmph",
",",
"ffi",
",",
"obj",
")",
":",
"# if arraylike and fixed unit size",
"# if file",
"# if buffer",
"if",
"is_file_location",
"(",
"obj",
")",
":",
"# The FP is captured for GC reasons inside the dtor closure",
"# pylint: disable=invalid-... | 85298572e51675cd0c7ef1052ed9989b0e57f0cc |
test | YearlyFinancials.nature | Sets the nature of this YearlyFinancials.
Nature of the balancesheet
:param nature: The nature of this YearlyFinancials.
:type: str | probe/models/yearly_financials.py | def nature(self, nature):
"""
Sets the nature of this YearlyFinancials.
Nature of the balancesheet
:param nature: The nature of this YearlyFinancials.
:type: str
"""
allowed_values = ["STANDALONE"]
if nature not in allowed_values:
raise ValueE... | def nature(self, nature):
"""
Sets the nature of this YearlyFinancials.
Nature of the balancesheet
:param nature: The nature of this YearlyFinancials.
:type: str
"""
allowed_values = ["STANDALONE"]
if nature not in allowed_values:
raise ValueE... | [
"Sets",
"the",
"nature",
"of",
"this",
"YearlyFinancials",
".",
"Nature",
"of",
"the",
"balancesheet"
] | loanzen/probe-py | python | https://github.com/loanzen/probe-py/blob/b5dbb0dba26c9b451e9bf1dec9e1aaa7f42d75a5/probe/models/yearly_financials.py#L176-L190 | [
"def",
"nature",
"(",
"self",
",",
"nature",
")",
":",
"allowed_values",
"=",
"[",
"\"STANDALONE\"",
"]",
"if",
"nature",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `nature`, must be one of {0}\"",
".",
"format",
"(",
"all... | b5dbb0dba26c9b451e9bf1dec9e1aaa7f42d75a5 |
test | computed_displaywidth | Figure out a reasonable default with. Use os.environ['COLUMNS'] if possible,
and failing that use 80. | columnize.py | def computed_displaywidth():
'''Figure out a reasonable default with. Use os.environ['COLUMNS'] if possible,
and failing that use 80.
'''
try:
width = int(os.environ['COLUMNS'])
except (KeyError, ValueError):
width = get_terminal_size().columns
return width or 80 | def computed_displaywidth():
'''Figure out a reasonable default with. Use os.environ['COLUMNS'] if possible,
and failing that use 80.
'''
try:
width = int(os.environ['COLUMNS'])
except (KeyError, ValueError):
width = get_terminal_size().columns
return width or 80 | [
"Figure",
"out",
"a",
"reasonable",
"default",
"with",
".",
"Use",
"os",
".",
"environ",
"[",
"COLUMNS",
"]",
"if",
"possible",
"and",
"failing",
"that",
"use",
"80",
"."
] | rocky/pycolumnize | python | https://github.com/rocky/pycolumnize/blob/4373faa989884d3a25f276f9bbb4911cc71eca17/columnize.py#L14-L23 | [
"def",
"computed_displaywidth",
"(",
")",
":",
"try",
":",
"width",
"=",
"int",
"(",
"os",
".",
"environ",
"[",
"'COLUMNS'",
"]",
")",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"width",
"=",
"get_terminal_size",
"(",
")",
".",
"columns",
... | 4373faa989884d3a25f276f9bbb4911cc71eca17 |
test | columnize | Return a list of strings as a compact set of columns arranged
horizontally or vertically.
For example, for a line width of 4 characters (arranged vertically):
['1', '2,', '3', '4'] => '1 3\n2 4\n'
or arranged horizontally:
['1', '2,', '3', '4'] => '1 2\n3 4\n'
Each column is only ... | columnize.py | def columnize(array, displaywidth=80, colsep = ' ',
arrange_vertical=True, ljust=True, lineprefix='',
opts={}):
"""Return a list of strings as a compact set of columns arranged
horizontally or vertically.
For example, for a line width of 4 characters (arranged vertically):
... | def columnize(array, displaywidth=80, colsep = ' ',
arrange_vertical=True, ljust=True, lineprefix='',
opts={}):
"""Return a list of strings as a compact set of columns arranged
horizontally or vertically.
For example, for a line width of 4 characters (arranged vertically):
... | [
"Return",
"a",
"list",
"of",
"strings",
"as",
"a",
"compact",
"set",
"of",
"columns",
"arranged",
"horizontally",
"or",
"vertically",
"."
] | rocky/pycolumnize | python | https://github.com/rocky/pycolumnize/blob/4373faa989884d3a25f276f9bbb4911cc71eca17/columnize.py#L45-L246 | [
"def",
"columnize",
"(",
"array",
",",
"displaywidth",
"=",
"80",
",",
"colsep",
"=",
"' '",
",",
"arrange_vertical",
"=",
"True",
",",
"ljust",
"=",
"True",
",",
"lineprefix",
"=",
"''",
",",
"opts",
"=",
"{",
"}",
")",
":",
"if",
"not",
"isinstanc... | 4373faa989884d3a25f276f9bbb4911cc71eca17 |
test | generate_hash | Generates a new Minimal Perfect Hash (MPH)
Parameters
----------
data : list, array-like, file-like
The input that is used to generate the minimal perfect hash.
Be aware, in most cases the input is expected to be distinct, and
many of the algorithms benefit from the input being sor... | cmph/__init__.py | def generate_hash(data, algorithm='chd_ph', hash_fns=(), chd_keys_per_bin=1,
chd_load_factor=None, fch_bits_per_key=None,
num_graph_vertices=None, brz_memory_size=8,
brz_temp_dir=None, brz_max_keys_per_bucket=128,
bdz_precomputed_rank=7, chd_avg_ke... | def generate_hash(data, algorithm='chd_ph', hash_fns=(), chd_keys_per_bin=1,
chd_load_factor=None, fch_bits_per_key=None,
num_graph_vertices=None, brz_memory_size=8,
brz_temp_dir=None, brz_max_keys_per_bucket=128,
bdz_precomputed_rank=7, chd_avg_ke... | [
"Generates",
"a",
"new",
"Minimal",
"Perfect",
"Hash",
"(",
"MPH",
")"
] | URXtech/cmph-cffi | python | https://github.com/URXtech/cmph-cffi/blob/85298572e51675cd0c7ef1052ed9989b0e57f0cc/cmph/__init__.py#L388-L567 | [
"def",
"generate_hash",
"(",
"data",
",",
"algorithm",
"=",
"'chd_ph'",
",",
"hash_fns",
"=",
"(",
")",
",",
"chd_keys_per_bin",
"=",
"1",
",",
"chd_load_factor",
"=",
"None",
",",
"fch_bits_per_key",
"=",
"None",
",",
"num_graph_vertices",
"=",
"None",
",",... | 85298572e51675cd0c7ef1052ed9989b0e57f0cc |
test | load_hash | Load a Minimal Perfect Hash (MPH)
Given an input stream, this will load a minimal perfect hash
Parameters
----------
existing_mph : file_like, string
An input stream that is file like, and able to load
a preexisting MPH, or the filename representing it.
Raises
------
IOErro... | cmph/__init__.py | def load_hash(existing_mph):
"""
Load a Minimal Perfect Hash (MPH)
Given an input stream, this will load a minimal perfect hash
Parameters
----------
existing_mph : file_like, string
An input stream that is file like, and able to load
a preexisting MPH, or the filename represent... | def load_hash(existing_mph):
"""
Load a Minimal Perfect Hash (MPH)
Given an input stream, this will load a minimal perfect hash
Parameters
----------
existing_mph : file_like, string
An input stream that is file like, and able to load
a preexisting MPH, or the filename represent... | [
"Load",
"a",
"Minimal",
"Perfect",
"Hash",
"(",
"MPH",
")",
"Given",
"an",
"input",
"stream",
"this",
"will",
"load",
"a",
"minimal",
"perfect",
"hash"
] | URXtech/cmph-cffi | python | https://github.com/URXtech/cmph-cffi/blob/85298572e51675cd0c7ef1052ed9989b0e57f0cc/cmph/__init__.py#L570-L601 | [
"def",
"load_hash",
"(",
"existing_mph",
")",
":",
"if",
"is_file_location",
"(",
"existing_mph",
")",
":",
"with",
"open",
"(",
"abspath",
"(",
"existing_mph",
")",
")",
"as",
"hash_table",
":",
"_mph",
"=",
"_cmph",
".",
"cmph_load",
"(",
"hash_table",
"... | 85298572e51675cd0c7ef1052ed9989b0e57f0cc |
test | MPH.save | Persist the Minimal Perfect Hash (MPH) to a stream
Parameters
----------
output : file_like
The stream to use to persist the MPH
Raises
------
IOError
If there is an issue accessing or manipulating the underlying
stream | cmph/__init__.py | def save(self, output):
"""
Persist the Minimal Perfect Hash (MPH) to a stream
Parameters
----------
output : file_like
The stream to use to persist the MPH
Raises
------
IOError
If there is an issue accessing or manipulating the ... | def save(self, output):
"""
Persist the Minimal Perfect Hash (MPH) to a stream
Parameters
----------
output : file_like
The stream to use to persist the MPH
Raises
------
IOError
If there is an issue accessing or manipulating the ... | [
"Persist",
"the",
"Minimal",
"Perfect",
"Hash",
"(",
"MPH",
")",
"to",
"a",
"stream"
] | URXtech/cmph-cffi | python | https://github.com/URXtech/cmph-cffi/blob/85298572e51675cd0c7ef1052ed9989b0e57f0cc/cmph/__init__.py#L230-L250 | [
"def",
"save",
"(",
"self",
",",
"output",
")",
":",
"assert",
"self",
".",
"_mph",
",",
"\"There is no MPH ?\"",
"if",
"isinstance",
"(",
"output",
",",
"six",
".",
"string_types",
")",
":",
"with",
"open",
"(",
"abspath",
"(",
"output",
")",
",",
"'w... | 85298572e51675cd0c7ef1052ed9989b0e57f0cc |
test | MPH.lookup | Generate hash code for a key from the Minimal Perfect Hash (MPH)
Parameters
----------
Key : object
The item to generate a key for, this works best for keys that
are strings, or can be transformed fairly directly into bytes
Returns : int
The code for... | cmph/__init__.py | def lookup(self, key):
"""
Generate hash code for a key from the Minimal Perfect Hash (MPH)
Parameters
----------
Key : object
The item to generate a key for, this works best for keys that
are strings, or can be transformed fairly directly into bytes
... | def lookup(self, key):
"""
Generate hash code for a key from the Minimal Perfect Hash (MPH)
Parameters
----------
Key : object
The item to generate a key for, this works best for keys that
are strings, or can be transformed fairly directly into bytes
... | [
"Generate",
"hash",
"code",
"for",
"a",
"key",
"from",
"the",
"Minimal",
"Perfect",
"Hash",
"(",
"MPH",
")"
] | URXtech/cmph-cffi | python | https://github.com/URXtech/cmph-cffi/blob/85298572e51675cd0c7ef1052ed9989b0e57f0cc/cmph/__init__.py#L252-L273 | [
"def",
"lookup",
"(",
"self",
",",
"key",
")",
":",
"assert",
"self",
".",
"_mph",
"key",
"=",
"convert_to_bytes",
"(",
"key",
")",
"box",
"=",
"ffi",
".",
"new",
"(",
"'char[]'",
",",
"key",
")",
"try",
":",
"result",
"=",
"_cmph",
".",
"cmph_sear... | 85298572e51675cd0c7ef1052ed9989b0e57f0cc |
test | Section.update_ | Update values of configuration section with dict.
Args:
sct_dict (dict): dict indexed with option names. Undefined
options are discarded.
conf_arg (bool): if True, only options that can be set in a config
file are updated. | loam/manager.py | def update_(self, sct_dict, conf_arg=True):
"""Update values of configuration section with dict.
Args:
sct_dict (dict): dict indexed with option names. Undefined
options are discarded.
conf_arg (bool): if True, only options that can be set in a config
... | def update_(self, sct_dict, conf_arg=True):
"""Update values of configuration section with dict.
Args:
sct_dict (dict): dict indexed with option names. Undefined
options are discarded.
conf_arg (bool): if True, only options that can be set in a config
... | [
"Update",
"values",
"of",
"configuration",
"section",
"with",
"dict",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/manager.py#L123-L136 | [
"def",
"update_",
"(",
"self",
",",
"sct_dict",
",",
"conf_arg",
"=",
"True",
")",
":",
"for",
"opt",
",",
"val",
"in",
"sct_dict",
".",
"items",
"(",
")",
":",
"if",
"opt",
"not",
"in",
"self",
".",
"def_",
":",
"continue",
"if",
"not",
"conf_arg"... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | Section.reset_ | Restore default values of options in this section. | loam/manager.py | def reset_(self):
"""Restore default values of options in this section."""
for opt, meta in self.defaults_():
self[opt] = meta.default | def reset_(self):
"""Restore default values of options in this section."""
for opt, meta in self.defaults_():
self[opt] = meta.default | [
"Restore",
"default",
"values",
"of",
"options",
"in",
"this",
"section",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/manager.py#L138-L141 | [
"def",
"reset_",
"(",
"self",
")",
":",
"for",
"opt",
",",
"meta",
"in",
"self",
".",
"defaults_",
"(",
")",
":",
"self",
"[",
"opt",
"]",
"=",
"meta",
".",
"default"
] | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | ConfigurationManager.from_dict_ | Use a dictionary to create a :class:`ConfigurationManager`.
Args:
conf_dict (dict of dict of :class:`ConfOpt`): the first level of
keys should be the section names. The second level should be
the option names. The values are the options metadata.
Returns:
... | loam/manager.py | def from_dict_(cls, conf_dict):
"""Use a dictionary to create a :class:`ConfigurationManager`.
Args:
conf_dict (dict of dict of :class:`ConfOpt`): the first level of
keys should be the section names. The second level should be
the option names. The values are... | def from_dict_(cls, conf_dict):
"""Use a dictionary to create a :class:`ConfigurationManager`.
Args:
conf_dict (dict of dict of :class:`ConfOpt`): the first level of
keys should be the section names. The second level should be
the option names. The values are... | [
"Use",
"a",
"dictionary",
"to",
"create",
"a",
":",
"class",
":",
"ConfigurationManager",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/manager.py#L187-L200 | [
"def",
"from_dict_",
"(",
"cls",
",",
"conf_dict",
")",
":",
"return",
"cls",
"(",
"*",
"*",
"{",
"name",
":",
"Section",
"(",
"*",
"*",
"opts",
")",
"for",
"name",
",",
"opts",
"in",
"conf_dict",
".",
"items",
"(",
")",
"}",
")"
] | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | ConfigurationManager.set_config_files_ | Set the list of config files.
Args:
config_files (pathlike): path of config files, given in the order
of reading. | loam/manager.py | def set_config_files_(self, *config_files):
"""Set the list of config files.
Args:
config_files (pathlike): path of config files, given in the order
of reading.
"""
self._config_files = tuple(pathlib.Path(path) for path in config_files) | def set_config_files_(self, *config_files):
"""Set the list of config files.
Args:
config_files (pathlike): path of config files, given in the order
of reading.
"""
self._config_files = tuple(pathlib.Path(path) for path in config_files) | [
"Set",
"the",
"list",
"of",
"config",
"files",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/manager.py#L212-L219 | [
"def",
"set_config_files_",
"(",
"self",
",",
"*",
"config_files",
")",
":",
"self",
".",
"_config_files",
"=",
"tuple",
"(",
"pathlib",
".",
"Path",
"(",
"path",
")",
"for",
"path",
"in",
"config_files",
")"
] | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | ConfigurationManager.opt_vals_ | Iterator over sections, option names, and option values.
This iterator is also implemented at the section level. The two loops
produce the same output::
for sct, opt, val in conf.opt_vals_():
print(sct, opt, val)
for sct in conf.sections_():
for... | loam/manager.py | def opt_vals_(self):
"""Iterator over sections, option names, and option values.
This iterator is also implemented at the section level. The two loops
produce the same output::
for sct, opt, val in conf.opt_vals_():
print(sct, opt, val)
for sct in conf.... | def opt_vals_(self):
"""Iterator over sections, option names, and option values.
This iterator is also implemented at the section level. The two loops
produce the same output::
for sct, opt, val in conf.opt_vals_():
print(sct, opt, val)
for sct in conf.... | [
"Iterator",
"over",
"sections",
"option",
"names",
"and",
"option",
"values",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/manager.py#L267-L284 | [
"def",
"opt_vals_",
"(",
"self",
")",
":",
"for",
"sct",
",",
"opt",
"in",
"self",
".",
"options_",
"(",
")",
":",
"yield",
"sct",
",",
"opt",
",",
"self",
"[",
"sct",
"]",
"[",
"opt",
"]"
] | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | ConfigurationManager.defaults_ | Iterator over sections, option names, and option metadata.
This iterator is also implemented at the section level. The two loops
produce the same output::
for sct, opt, meta in conf.defaults_():
print(sct, opt, meta.default)
for sct in conf.sections_():
... | loam/manager.py | def defaults_(self):
"""Iterator over sections, option names, and option metadata.
This iterator is also implemented at the section level. The two loops
produce the same output::
for sct, opt, meta in conf.defaults_():
print(sct, opt, meta.default)
for ... | def defaults_(self):
"""Iterator over sections, option names, and option metadata.
This iterator is also implemented at the section level. The two loops
produce the same output::
for sct, opt, meta in conf.defaults_():
print(sct, opt, meta.default)
for ... | [
"Iterator",
"over",
"sections",
"option",
"names",
"and",
"option",
"metadata",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/manager.py#L286-L304 | [
"def",
"defaults_",
"(",
"self",
")",
":",
"for",
"sct",
",",
"opt",
"in",
"self",
".",
"options_",
"(",
")",
":",
"yield",
"sct",
",",
"opt",
",",
"self",
"[",
"sct",
"]",
".",
"def_",
"[",
"opt",
"]"
] | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | ConfigurationManager.create_config_ | Create config file.
Create config file in :attr:`config_files_[index]`.
Parameters:
index(int): index of config file.
update (bool): if set to True and :attr:`config_files_` already
exists, its content is read and all the options it sets are
kept... | loam/manager.py | def create_config_(self, index=0, update=False):
"""Create config file.
Create config file in :attr:`config_files_[index]`.
Parameters:
index(int): index of config file.
update (bool): if set to True and :attr:`config_files_` already
exists, its content ... | def create_config_(self, index=0, update=False):
"""Create config file.
Create config file in :attr:`config_files_[index]`.
Parameters:
index(int): index of config file.
update (bool): if set to True and :attr:`config_files_` already
exists, its content ... | [
"Create",
"config",
"file",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/manager.py#L311-L337 | [
"def",
"create_config_",
"(",
"self",
",",
"index",
"=",
"0",
",",
"update",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"config_files_",
"[",
"index",
":",
"]",
":",
"return",
"path",
"=",
"self",
".",
"config_files_",
"[",
"index",
"]",
"if",... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | ConfigurationManager.update_ | Update values of configuration options with dict.
Args:
conf_dict (dict): dict of dict indexed with section and option
names.
conf_arg (bool): if True, only options that can be set in a config
file are updated. | loam/manager.py | def update_(self, conf_dict, conf_arg=True):
"""Update values of configuration options with dict.
Args:
conf_dict (dict): dict of dict indexed with section and option
names.
conf_arg (bool): if True, only options that can be set in a config
file a... | def update_(self, conf_dict, conf_arg=True):
"""Update values of configuration options with dict.
Args:
conf_dict (dict): dict of dict indexed with section and option
names.
conf_arg (bool): if True, only options that can be set in a config
file a... | [
"Update",
"values",
"of",
"configuration",
"options",
"with",
"dict",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/manager.py#L339-L349 | [
"def",
"update_",
"(",
"self",
",",
"conf_dict",
",",
"conf_arg",
"=",
"True",
")",
":",
"for",
"section",
",",
"secdict",
"in",
"conf_dict",
".",
"items",
"(",
")",
":",
"self",
"[",
"section",
"]",
".",
"update_",
"(",
"secdict",
",",
"conf_arg",
"... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | ConfigurationManager.read_config_ | Read a config file and set config values accordingly.
Returns:
dict: content of config file. | loam/manager.py | def read_config_(self, cfile):
"""Read a config file and set config values accordingly.
Returns:
dict: content of config file.
"""
if not cfile.exists():
return {}
try:
conf_dict = toml.load(str(cfile))
except toml.TomlDecodeError:
... | def read_config_(self, cfile):
"""Read a config file and set config values accordingly.
Returns:
dict: content of config file.
"""
if not cfile.exists():
return {}
try:
conf_dict = toml.load(str(cfile))
except toml.TomlDecodeError:
... | [
"Read",
"a",
"config",
"file",
"and",
"set",
"config",
"values",
"accordingly",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/manager.py#L351-L364 | [
"def",
"read_config_",
"(",
"self",
",",
"cfile",
")",
":",
"if",
"not",
"cfile",
".",
"exists",
"(",
")",
":",
"return",
"{",
"}",
"try",
":",
"conf_dict",
"=",
"toml",
".",
"load",
"(",
"str",
"(",
"cfile",
")",
")",
"except",
"toml",
".",
"Tom... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | ConfigurationManager.read_configs_ | Read config files and set config values accordingly.
Returns:
(dict, list, list): respectively content of files, list of
missing/empty files and list of files for which a parsing error
arised. | loam/manager.py | def read_configs_(self):
"""Read config files and set config values accordingly.
Returns:
(dict, list, list): respectively content of files, list of
missing/empty files and list of files for which a parsing error
arised.
"""
if not self.config_files_:... | def read_configs_(self):
"""Read config files and set config values accordingly.
Returns:
(dict, list, list): respectively content of files, list of
missing/empty files and list of files for which a parsing error
arised.
"""
if not self.config_files_:... | [
"Read",
"config",
"files",
"and",
"set",
"config",
"values",
"accordingly",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/manager.py#L366-L389 | [
"def",
"read_configs_",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"config_files_",
":",
"return",
"{",
"}",
",",
"[",
"]",
",",
"[",
"]",
"content",
"=",
"{",
"section",
":",
"{",
"}",
"for",
"section",
"in",
"self",
"}",
"empty_files",
"=",... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | _lookup_version | For the given module file (usually found by:
from package import __file__ as module_file
in the caller, return the location of
the current RELEASE-VERSION file and the file
itself. | yaclifw/version.py | def _lookup_version(module_file):
"""
For the given module file (usually found by:
from package import __file__ as module_file
in the caller, return the location of
the current RELEASE-VERSION file and the file
itself.
"""
version_dir = path.abspath(path.dirname(module_file))
v... | def _lookup_version(module_file):
"""
For the given module file (usually found by:
from package import __file__ as module_file
in the caller, return the location of
the current RELEASE-VERSION file and the file
itself.
"""
version_dir = path.abspath(path.dirname(module_file))
v... | [
"For",
"the",
"given",
"module",
"file",
"(",
"usually",
"found",
"by",
":"
] | openmicroscopy/yaclifw | python | https://github.com/openmicroscopy/yaclifw/blob/a01179fefb2c2c4260c75e6d1dc6e19de9979d64/yaclifw/version.py#L45-L57 | [
"def",
"_lookup_version",
"(",
"module_file",
")",
":",
"version_dir",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"dirname",
"(",
"module_file",
")",
")",
"version_file",
"=",
"path",
".",
"join",
"(",
"version_dir",
",",
"\"RELEASE-VERSION\"",
")",
"ret... | a01179fefb2c2c4260c75e6d1dc6e19de9979d64 |
test | _names | List of cli strings for a given option. | loam/cli.py | def _names(section, option):
"""List of cli strings for a given option."""
meta = section.def_[option]
action = meta.cmd_kwargs.get('action')
if action is internal.Switch:
names = ['-{}'.format(option), '+{}'.format(option)]
if meta.shortname is not None:
names.append('-{}'.f... | def _names(section, option):
"""List of cli strings for a given option."""
meta = section.def_[option]
action = meta.cmd_kwargs.get('action')
if action is internal.Switch:
names = ['-{}'.format(option), '+{}'.format(option)]
if meta.shortname is not None:
names.append('-{}'.f... | [
"List",
"of",
"cli",
"strings",
"for",
"a",
"given",
"option",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/cli.py#L14-L27 | [
"def",
"_names",
"(",
"section",
",",
"option",
")",
":",
"meta",
"=",
"section",
".",
"def_",
"[",
"option",
"]",
"action",
"=",
"meta",
".",
"cmd_kwargs",
".",
"get",
"(",
"'action'",
")",
"if",
"action",
"is",
"internal",
".",
"Switch",
":",
"name... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | CLIManager.sections_list | List of config sections used by a command.
Args:
cmd (str): command name, set to ``None`` or ``''`` for the bare
command.
Returns:
list of str: list of configuration sections used by that command. | loam/cli.py | def sections_list(self, cmd=None):
"""List of config sections used by a command.
Args:
cmd (str): command name, set to ``None`` or ``''`` for the bare
command.
Returns:
list of str: list of configuration sections used by that command.
"""
... | def sections_list(self, cmd=None):
"""List of config sections used by a command.
Args:
cmd (str): command name, set to ``None`` or ``''`` for the bare
command.
Returns:
list of str: list of configuration sections used by that command.
"""
... | [
"List",
"of",
"config",
"sections",
"used",
"by",
"a",
"command",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/cli.py#L104-L123 | [
"def",
"sections_list",
"(",
"self",
",",
"cmd",
"=",
"None",
")",
":",
"sections",
"=",
"list",
"(",
"self",
".",
"common",
".",
"sections",
")",
"if",
"not",
"cmd",
":",
"if",
"self",
".",
"bare",
"is",
"not",
"None",
":",
"sections",
".",
"exten... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | CLIManager._cmd_opts_solver | Scan options related to one command and enrich _opt_cmds. | loam/cli.py | def _cmd_opts_solver(self, cmd_name):
"""Scan options related to one command and enrich _opt_cmds."""
sections = self.sections_list(cmd_name)
cmd_dict = self._opt_cmds[cmd_name] if cmd_name else self._opt_bare
for sct in reversed(sections):
for opt, opt_meta in self._conf[sct... | def _cmd_opts_solver(self, cmd_name):
"""Scan options related to one command and enrich _opt_cmds."""
sections = self.sections_list(cmd_name)
cmd_dict = self._opt_cmds[cmd_name] if cmd_name else self._opt_bare
for sct in reversed(sections):
for opt, opt_meta in self._conf[sct... | [
"Scan",
"options",
"related",
"to",
"one",
"command",
"and",
"enrich",
"_opt_cmds",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/cli.py#L125-L139 | [
"def",
"_cmd_opts_solver",
"(",
"self",
",",
"cmd_name",
")",
":",
"sections",
"=",
"self",
".",
"sections_list",
"(",
"cmd_name",
")",
"cmd_dict",
"=",
"self",
".",
"_opt_cmds",
"[",
"cmd_name",
"]",
"if",
"cmd_name",
"else",
"self",
".",
"_opt_bare",
"fo... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | CLIManager._add_options_to_parser | Add options to a parser. | loam/cli.py | def _add_options_to_parser(self, opts_dict, parser):
"""Add options to a parser."""
store_bool = ('store_true', 'store_false')
for opt, sct in opts_dict.items():
meta = self._conf[sct].def_[opt]
kwargs = copy.deepcopy(meta.cmd_kwargs)
action = kwargs.get('acti... | def _add_options_to_parser(self, opts_dict, parser):
"""Add options to a parser."""
store_bool = ('store_true', 'store_false')
for opt, sct in opts_dict.items():
meta = self._conf[sct].def_[opt]
kwargs = copy.deepcopy(meta.cmd_kwargs)
action = kwargs.get('acti... | [
"Add",
"options",
"to",
"a",
"parser",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/cli.py#L141-L154 | [
"def",
"_add_options_to_parser",
"(",
"self",
",",
"opts_dict",
",",
"parser",
")",
":",
"store_bool",
"=",
"(",
"'store_true'",
",",
"'store_false'",
")",
"for",
"opt",
",",
"sct",
"in",
"opts_dict",
".",
"items",
"(",
")",
":",
"meta",
"=",
"self",
"."... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | CLIManager._build_parser | Build command line argument parser.
Returns:
:class:`argparse.ArgumentParser`: the command line argument parser.
You probably won't need to use it directly. To parse command line
arguments and update the :class:`ConfigurationManager` instance
accordingly, use the... | loam/cli.py | def _build_parser(self):
"""Build command line argument parser.
Returns:
:class:`argparse.ArgumentParser`: the command line argument parser.
You probably won't need to use it directly. To parse command line
arguments and update the :class:`ConfigurationManager` insta... | def _build_parser(self):
"""Build command line argument parser.
Returns:
:class:`argparse.ArgumentParser`: the command line argument parser.
You probably won't need to use it directly. To parse command line
arguments and update the :class:`ConfigurationManager` insta... | [
"Build",
"command",
"line",
"argument",
"parser",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/cli.py#L156-L180 | [
"def",
"_build_parser",
"(",
"self",
")",
":",
"main_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"self",
".",
"common",
".",
"help",
",",
"prefix_chars",
"=",
"'-+'",
")",
"self",
".",
"_add_options_to_parser",
"(",
"self",
".",... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | CLIManager.parse_args | Parse arguments and update options accordingly.
Args:
arglist (list of str): list of arguments to parse. If set to None,
``sys.argv[1:]`` is used.
Returns:
:class:`Namespace`: the argument namespace returned by the
:class:`argparse.ArgumentParser`. | loam/cli.py | def parse_args(self, arglist=None):
"""Parse arguments and update options accordingly.
Args:
arglist (list of str): list of arguments to parse. If set to None,
``sys.argv[1:]`` is used.
Returns:
:class:`Namespace`: the argument namespace returned by the
... | def parse_args(self, arglist=None):
"""Parse arguments and update options accordingly.
Args:
arglist (list of str): list of arguments to parse. If set to None,
``sys.argv[1:]`` is used.
Returns:
:class:`Namespace`: the argument namespace returned by the
... | [
"Parse",
"arguments",
"and",
"update",
"options",
"accordingly",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/cli.py#L182-L201 | [
"def",
"parse_args",
"(",
"self",
",",
"arglist",
"=",
"None",
")",
":",
"args",
"=",
"self",
".",
"_parser",
".",
"parse_args",
"(",
"args",
"=",
"arglist",
")",
"sub_cmd",
"=",
"args",
".",
"loam_sub_name",
"if",
"sub_cmd",
"is",
"None",
":",
"for",
... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | CLIManager._zsh_comp_command | Write zsh _arguments compdef for a given command.
Args:
zcf (file): zsh compdef file.
cmd (str): command name, set to None or '' for bare command.
grouping (bool): group options (zsh>=5.4).
add_help (bool): add an help option. | loam/cli.py | def _zsh_comp_command(self, zcf, cmd, grouping, add_help=True):
"""Write zsh _arguments compdef for a given command.
Args:
zcf (file): zsh compdef file.
cmd (str): command name, set to None or '' for bare command.
grouping (bool): group options (zsh>=5.4).
... | def _zsh_comp_command(self, zcf, cmd, grouping, add_help=True):
"""Write zsh _arguments compdef for a given command.
Args:
zcf (file): zsh compdef file.
cmd (str): command name, set to None or '' for bare command.
grouping (bool): group options (zsh>=5.4).
... | [
"Write",
"zsh",
"_arguments",
"compdef",
"for",
"a",
"given",
"command",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/cli.py#L203-L246 | [
"def",
"_zsh_comp_command",
"(",
"self",
",",
"zcf",
",",
"cmd",
",",
"grouping",
",",
"add_help",
"=",
"True",
")",
":",
"if",
"add_help",
":",
"if",
"grouping",
":",
"print",
"(",
"\"+ '(help)'\"",
",",
"end",
"=",
"BLK",
",",
"file",
"=",
"zcf",
"... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
test | CLIManager.zsh_complete | Write zsh compdef script.
Args:
path (path-like): desired path of the compdef script.
cmd (str): command name that should be completed.
cmds (str): extra command names that should be completed.
sourceable (bool): if True, the generated file will contain an
... | loam/cli.py | def zsh_complete(self, path, cmd, *cmds, sourceable=False):
"""Write zsh compdef script.
Args:
path (path-like): desired path of the compdef script.
cmd (str): command name that should be completed.
cmds (str): extra command names that should be completed.
... | def zsh_complete(self, path, cmd, *cmds, sourceable=False):
"""Write zsh compdef script.
Args:
path (path-like): desired path of the compdef script.
cmd (str): command name that should be completed.
cmds (str): extra command names that should be completed.
... | [
"Write",
"zsh",
"compdef",
"script",
"."
] | amorison/loam | python | https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/cli.py#L248-L292 | [
"def",
"zsh_complete",
"(",
"self",
",",
"path",
",",
"cmd",
",",
"*",
"cmds",
",",
"sourceable",
"=",
"False",
")",
":",
"grouping",
"=",
"internal",
".",
"zsh_version",
"(",
")",
">=",
"(",
"5",
",",
"4",
")",
"path",
"=",
"pathlib",
".",
"Path",... | a566c943a75e068a4510099331a1ddfe5bbbdd94 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.