repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
serge-sans-paille/pythran | pythran/analyses/aliases.py | Aliases.visit_ListComp | def visit_ListComp(self, node):
'''
A comprehension is not abstracted in any way
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return [a for i in b]')
>>> result = pm.gather(Aliases, module)
>>... | python | def visit_ListComp(self, node):
'''
A comprehension is not abstracted in any way
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return [a for i in b]')
>>> result = pm.gather(Aliases, module)
>>... | [
"def",
"visit_ListComp",
"(",
"self",
",",
"node",
")",
":",
"for",
"generator",
"in",
"node",
".",
"generators",
":",
"self",
".",
"visit_comprehension",
"(",
"generator",
")",
"self",
".",
"visit",
"(",
"node",
".",
"elt",
")",
"return",
"self",
".",
... | A comprehension is not abstracted in any way
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return [a for i in b]')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.ListComp)
... | [
"A",
"comprehension",
"is",
"not",
"abstracted",
"in",
"any",
"way"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L493-L507 | train |
serge-sans-paille/pythran | pythran/analyses/aliases.py | Aliases.visit_FunctionDef | def visit_FunctionDef(self, node):
'''
Initialise aliasing default value before visiting.
Add aliasing values for :
- Pythonic
- globals declarations
- current function arguments
'''
self.aliases = IntrinsicAliases.copy()
self.aliases... | python | def visit_FunctionDef(self, node):
'''
Initialise aliasing default value before visiting.
Add aliasing values for :
- Pythonic
- globals declarations
- current function arguments
'''
self.aliases = IntrinsicAliases.copy()
self.aliases... | [
"def",
"visit_FunctionDef",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"aliases",
"=",
"IntrinsicAliases",
".",
"copy",
"(",
")",
"self",
".",
"aliases",
".",
"update",
"(",
"(",
"f",
".",
"name",
",",
"{",
"f",
"}",
")",
"for",
"f",
"in",
... | Initialise aliasing default value before visiting.
Add aliasing values for :
- Pythonic
- globals declarations
- current function arguments | [
"Initialise",
"aliasing",
"default",
"value",
"before",
"visiting",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L532-L600 | train |
serge-sans-paille/pythran | pythran/analyses/aliases.py | Aliases.visit_For | def visit_For(self, node):
'''
For loop creates aliasing between the target
and the content of the iterator
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse("""
... def foo(a):
... for i in a:
... | python | def visit_For(self, node):
'''
For loop creates aliasing between the target
and the content of the iterator
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse("""
... def foo(a):
... for i in a:
... | [
"def",
"visit_For",
"(",
"self",
",",
"node",
")",
":",
"iter_aliases",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"iter",
")",
"if",
"all",
"(",
"isinstance",
"(",
"x",
",",
"ContainerOf",
")",
"for",
"x",
"in",
"iter_aliases",
")",
":",
"target_a... | For loop creates aliasing between the target
and the content of the iterator
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse("""
... def foo(a):
... for i in a:
... {i}""")
>>> result = pm.ga... | [
"For",
"loop",
"creates",
"aliasing",
"between",
"the",
"target",
"and",
"the",
"content",
"of",
"the",
"iterator"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L628-L666 | train |
serge-sans-paille/pythran | pythran/analyses/argument_read_once.py | ArgumentReadOnce.prepare | def prepare(self, node):
"""
Initialise arguments effects as this analysis in inter-procedural.
Initialisation done for Pythonic functions and default values set for
user defined functions.
"""
super(ArgumentReadOnce, self).prepare(node)
# global functions init
... | python | def prepare(self, node):
"""
Initialise arguments effects as this analysis in inter-procedural.
Initialisation done for Pythonic functions and default values set for
user defined functions.
"""
super(ArgumentReadOnce, self).prepare(node)
# global functions init
... | [
"def",
"prepare",
"(",
"self",
",",
"node",
")",
":",
"super",
"(",
"ArgumentReadOnce",
",",
"self",
")",
".",
"prepare",
"(",
"node",
")",
"for",
"n",
"in",
"self",
".",
"global_declarations",
".",
"values",
"(",
")",
":",
"fe",
"=",
"ArgumentReadOnce... | Initialise arguments effects as this analysis in inter-procedural.
Initialisation done for Pythonic functions and default values set for
user defined functions. | [
"Initialise",
"arguments",
"effects",
"as",
"this",
"analysis",
"in",
"inter",
"-",
"procedural",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/argument_read_once.py#L60-L88 | train |
astropy/regions | regions/io/ds9/write.py | ds9_objects_to_string | def ds9_objects_to_string(regions, coordsys='fk5', fmt='.6f', radunit='deg'):
"""
Converts a `list` of `~regions.Region` to DS9 region string.
Parameters
----------
regions : `list`
List of `~regions.Region` objects
coordsys : `str`, optional
This overrides the coordinate system... | python | def ds9_objects_to_string(regions, coordsys='fk5', fmt='.6f', radunit='deg'):
"""
Converts a `list` of `~regions.Region` to DS9 region string.
Parameters
----------
regions : `list`
List of `~regions.Region` objects
coordsys : `str`, optional
This overrides the coordinate system... | [
"def",
"ds9_objects_to_string",
"(",
"regions",
",",
"coordsys",
"=",
"'fk5'",
",",
"fmt",
"=",
"'.6f'",
",",
"radunit",
"=",
"'deg'",
")",
":",
"shapelist",
"=",
"to_shape_list",
"(",
"regions",
",",
"coordsys",
")",
"return",
"shapelist",
".",
"to_ds9",
... | Converts a `list` of `~regions.Region` to DS9 region string.
Parameters
----------
regions : `list`
List of `~regions.Region` objects
coordsys : `str`, optional
This overrides the coordinate system frame for all regions.
Default is 'fk5'.
fmt : `str`, optional
A pyth... | [
"Converts",
"a",
"list",
"of",
"~regions",
".",
"Region",
"to",
"DS9",
"region",
"string",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/write.py#L12-L46 | train |
astropy/regions | regions/io/ds9/write.py | write_ds9 | def write_ds9(regions, filename, coordsys='fk5', fmt='.6f', radunit='deg'):
"""
Converts a `list` of `~regions.Region` to DS9 string and write to file.
Parameters
----------
regions : `list`
List of `regions.Region` objects
filename : `str`
Filename in which the string is to be ... | python | def write_ds9(regions, filename, coordsys='fk5', fmt='.6f', radunit='deg'):
"""
Converts a `list` of `~regions.Region` to DS9 string and write to file.
Parameters
----------
regions : `list`
List of `regions.Region` objects
filename : `str`
Filename in which the string is to be ... | [
"def",
"write_ds9",
"(",
"regions",
",",
"filename",
",",
"coordsys",
"=",
"'fk5'",
",",
"fmt",
"=",
"'.6f'",
",",
"radunit",
"=",
"'deg'",
")",
":",
"output",
"=",
"ds9_objects_to_string",
"(",
"regions",
",",
"coordsys",
",",
"fmt",
",",
"radunit",
")"... | Converts a `list` of `~regions.Region` to DS9 string and write to file.
Parameters
----------
regions : `list`
List of `regions.Region` objects
filename : `str`
Filename in which the string is to be written.
coordsys : `str`, optional #TODO
Coordinate system that overrides t... | [
"Converts",
"a",
"list",
"of",
"~regions",
".",
"Region",
"to",
"DS9",
"string",
"and",
"write",
"to",
"file",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/write.py#L49-L83 | train |
astropy/regions | regions/io/crtf/write.py | crtf_objects_to_string | def crtf_objects_to_string(regions, coordsys='fk5', fmt='.6f', radunit='deg'):
"""
Converts a `list` of `~regions.Region` to CRTF region string.
Parameters
----------
regions : `list`
List of `~regions.Region` objects
coordsys : `str`, optional
Astropy Coordinate system that ove... | python | def crtf_objects_to_string(regions, coordsys='fk5', fmt='.6f', radunit='deg'):
"""
Converts a `list` of `~regions.Region` to CRTF region string.
Parameters
----------
regions : `list`
List of `~regions.Region` objects
coordsys : `str`, optional
Astropy Coordinate system that ove... | [
"def",
"crtf_objects_to_string",
"(",
"regions",
",",
"coordsys",
"=",
"'fk5'",
",",
"fmt",
"=",
"'.6f'",
",",
"radunit",
"=",
"'deg'",
")",
":",
"shapelist",
"=",
"to_shape_list",
"(",
"regions",
",",
"coordsys",
")",
"return",
"shapelist",
".",
"to_crtf",
... | Converts a `list` of `~regions.Region` to CRTF region string.
Parameters
----------
regions : `list`
List of `~regions.Region` objects
coordsys : `str`, optional
Astropy Coordinate system that overrides the coordinate system frame for
all regions. Default is 'fk5'.
fmt : `st... | [
"Converts",
"a",
"list",
"of",
"~regions",
".",
"Region",
"to",
"CRTF",
"region",
"string",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/crtf/write.py#L12-L48 | train |
astropy/regions | regions/io/crtf/write.py | write_crtf | def write_crtf(regions, filename, coordsys='fk5', fmt='.6f', radunit='deg'):
"""
Converts a `list` of `~regions.Region` to CRTF string and write to file.
Parameters
----------
regions : `list`
List of `~regions.Region` objects
filename : `str`
Filename in which the string is to ... | python | def write_crtf(regions, filename, coordsys='fk5', fmt='.6f', radunit='deg'):
"""
Converts a `list` of `~regions.Region` to CRTF string and write to file.
Parameters
----------
regions : `list`
List of `~regions.Region` objects
filename : `str`
Filename in which the string is to ... | [
"def",
"write_crtf",
"(",
"regions",
",",
"filename",
",",
"coordsys",
"=",
"'fk5'",
",",
"fmt",
"=",
"'.6f'",
",",
"radunit",
"=",
"'deg'",
")",
":",
"output",
"=",
"crtf_objects_to_string",
"(",
"regions",
",",
"coordsys",
",",
"fmt",
",",
"radunit",
"... | Converts a `list` of `~regions.Region` to CRTF string and write to file.
Parameters
----------
regions : `list`
List of `~regions.Region` objects
filename : `str`
Filename in which the string is to be written. Default is 'new.crtf'
coordsys : `str`, optional
Astropy Coordina... | [
"Converts",
"a",
"list",
"of",
"~regions",
".",
"Region",
"to",
"CRTF",
"string",
"and",
"write",
"to",
"file",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/crtf/write.py#L51-L86 | train |
astropy/regions | regions/shapes/rectangle.py | RectanglePixelRegion.corners | def corners(self):
"""
Return the x, y coordinate pairs that define the corners
"""
corners = [(-self.width/2, -self.height/2),
( self.width/2, -self.height/2),
( self.width/2, self.height/2),
(-self.width/2, self.height/2),
... | python | def corners(self):
"""
Return the x, y coordinate pairs that define the corners
"""
corners = [(-self.width/2, -self.height/2),
( self.width/2, -self.height/2),
( self.width/2, self.height/2),
(-self.width/2, self.height/2),
... | [
"def",
"corners",
"(",
"self",
")",
":",
"corners",
"=",
"[",
"(",
"-",
"self",
".",
"width",
"/",
"2",
",",
"-",
"self",
".",
"height",
"/",
"2",
")",
",",
"(",
"self",
".",
"width",
"/",
"2",
",",
"-",
"self",
".",
"height",
"/",
"2",
")"... | Return the x, y coordinate pairs that define the corners | [
"Return",
"the",
"x",
"y",
"coordinate",
"pairs",
"that",
"define",
"the",
"corners"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/shapes/rectangle.py#L202-L216 | train |
astropy/regions | regions/shapes/rectangle.py | RectanglePixelRegion.to_polygon | def to_polygon(self):
"""
Return a 4-cornered polygon equivalent to this rectangle
"""
x,y = self.corners.T
vertices = PixCoord(x=x, y=y)
return PolygonPixelRegion(vertices=vertices, meta=self.meta,
visual=self.visual) | python | def to_polygon(self):
"""
Return a 4-cornered polygon equivalent to this rectangle
"""
x,y = self.corners.T
vertices = PixCoord(x=x, y=y)
return PolygonPixelRegion(vertices=vertices, meta=self.meta,
visual=self.visual) | [
"def",
"to_polygon",
"(",
"self",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"corners",
".",
"T",
"vertices",
"=",
"PixCoord",
"(",
"x",
"=",
"x",
",",
"y",
"=",
"y",
")",
"return",
"PolygonPixelRegion",
"(",
"vertices",
"=",
"vertices",
",",
"meta... | Return a 4-cornered polygon equivalent to this rectangle | [
"Return",
"a",
"4",
"-",
"cornered",
"polygon",
"equivalent",
"to",
"this",
"rectangle"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/shapes/rectangle.py#L218-L225 | train |
astropy/regions | regions/shapes/rectangle.py | RectanglePixelRegion._lower_left_xy | def _lower_left_xy(self):
"""
Compute lower left `xy` position.
This is used for the conversion to matplotlib in ``as_artist``
Taken from http://photutils.readthedocs.io/en/latest/_modules/photutils/aperture/rectangle.html#RectangularAperture.plot
"""
hw = self.width / ... | python | def _lower_left_xy(self):
"""
Compute lower left `xy` position.
This is used for the conversion to matplotlib in ``as_artist``
Taken from http://photutils.readthedocs.io/en/latest/_modules/photutils/aperture/rectangle.html#RectangularAperture.plot
"""
hw = self.width / ... | [
"def",
"_lower_left_xy",
"(",
"self",
")",
":",
"hw",
"=",
"self",
".",
"width",
"/",
"2.",
"hh",
"=",
"self",
".",
"height",
"/",
"2.",
"sint",
"=",
"np",
".",
"sin",
"(",
"self",
".",
"angle",
")",
"cost",
"=",
"np",
".",
"cos",
"(",
"self",
... | Compute lower left `xy` position.
This is used for the conversion to matplotlib in ``as_artist``
Taken from http://photutils.readthedocs.io/en/latest/_modules/photutils/aperture/rectangle.html#RectangularAperture.plot | [
"Compute",
"lower",
"left",
"xy",
"position",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/shapes/rectangle.py#L228-L244 | train |
astropy/regions | regions/core/compound.py | CompoundPixelRegion._make_annulus_path | def _make_annulus_path(patch_inner, patch_outer):
"""
Defines a matplotlib annulus path from two patches.
This preserves the cubic Bezier curves (CURVE4) of the aperture
paths.
# This is borrowed from photutils aperture.
"""
import matplotlib.path as mpath
... | python | def _make_annulus_path(patch_inner, patch_outer):
"""
Defines a matplotlib annulus path from two patches.
This preserves the cubic Bezier curves (CURVE4) of the aperture
paths.
# This is borrowed from photutils aperture.
"""
import matplotlib.path as mpath
... | [
"def",
"_make_annulus_path",
"(",
"patch_inner",
",",
"patch_outer",
")",
":",
"import",
"matplotlib",
".",
"path",
"as",
"mpath",
"path_inner",
"=",
"patch_inner",
".",
"get_path",
"(",
")",
"transform_inner",
"=",
"patch_inner",
".",
"get_transform",
"(",
")",... | Defines a matplotlib annulus path from two patches.
This preserves the cubic Bezier curves (CURVE4) of the aperture
paths.
# This is borrowed from photutils aperture. | [
"Defines",
"a",
"matplotlib",
"annulus",
"path",
"from",
"two",
"patches",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/core/compound.py#L104-L130 | train |
astropy/regions | regions/io/fits/read.py | read_fits_region | def read_fits_region(filename, errors='strict'):
"""
Reads a FITS region file and scans for any fits regions table and
converts them into `Region` objects.
Parameters
----------
filename : str
The file path
errors : ``warn``, ``ignore``, ``strict``
The error handling scheme to... | python | def read_fits_region(filename, errors='strict'):
"""
Reads a FITS region file and scans for any fits regions table and
converts them into `Region` objects.
Parameters
----------
filename : str
The file path
errors : ``warn``, ``ignore``, ``strict``
The error handling scheme to... | [
"def",
"read_fits_region",
"(",
"filename",
",",
"errors",
"=",
"'strict'",
")",
":",
"regions",
"=",
"[",
"]",
"hdul",
"=",
"fits",
".",
"open",
"(",
"filename",
")",
"for",
"hdu",
"in",
"hdul",
":",
"if",
"hdu",
".",
"name",
"==",
"'REGION'",
":",
... | Reads a FITS region file and scans for any fits regions table and
converts them into `Region` objects.
Parameters
----------
filename : str
The file path
errors : ``warn``, ``ignore``, ``strict``
The error handling scheme to use for handling parsing errors.
The default is 'stric... | [
"Reads",
"a",
"FITS",
"region",
"file",
"and",
"scans",
"for",
"any",
"fits",
"regions",
"table",
"and",
"converts",
"them",
"into",
"Region",
"objects",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/fits/read.py#L228-L270 | train |
astropy/regions | regions/io/core.py | to_shape_list | def to_shape_list(region_list, coordinate_system='fk5'):
"""
Converts a list of regions into a `regions.ShapeList` object.
Parameters
----------
region_list: python list
Lists of `regions.Region` objects
format_type: str ('DS9' or 'CRTF')
The format type of the Shape object. Def... | python | def to_shape_list(region_list, coordinate_system='fk5'):
"""
Converts a list of regions into a `regions.ShapeList` object.
Parameters
----------
region_list: python list
Lists of `regions.Region` objects
format_type: str ('DS9' or 'CRTF')
The format type of the Shape object. Def... | [
"def",
"to_shape_list",
"(",
"region_list",
",",
"coordinate_system",
"=",
"'fk5'",
")",
":",
"shape_list",
"=",
"ShapeList",
"(",
")",
"for",
"region",
"in",
"region_list",
":",
"coord",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"region",
",",
"SkyRegion",
... | Converts a list of regions into a `regions.ShapeList` object.
Parameters
----------
region_list: python list
Lists of `regions.Region` objects
format_type: str ('DS9' or 'CRTF')
The format type of the Shape object. Default is 'DS9'.
coordinate_system: str
The astropy coordin... | [
"Converts",
"a",
"list",
"of",
"regions",
"into",
"a",
"regions",
".",
"ShapeList",
"object",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/core.py#L670-L738 | train |
astropy/regions | regions/io/core.py | to_ds9_meta | def to_ds9_meta(shape_meta):
"""
Makes the meta data DS9 compatible by filtering and mapping the valid keys
Parameters
----------
shape_meta: dict
meta attribute of a `regions.Shape` object
Returns
-------
meta : dict
DS9 compatible meta dictionary
"""
# meta k... | python | def to_ds9_meta(shape_meta):
"""
Makes the meta data DS9 compatible by filtering and mapping the valid keys
Parameters
----------
shape_meta: dict
meta attribute of a `regions.Shape` object
Returns
-------
meta : dict
DS9 compatible meta dictionary
"""
# meta k... | [
"def",
"to_ds9_meta",
"(",
"shape_meta",
")",
":",
"valid_keys",
"=",
"[",
"'symbol'",
",",
"'include'",
",",
"'tag'",
",",
"'line'",
",",
"'comment'",
",",
"'name'",
",",
"'select'",
",",
"'highlite'",
",",
"'fixed'",
",",
"'label'",
",",
"'text'",
",",
... | Makes the meta data DS9 compatible by filtering and mapping the valid keys
Parameters
----------
shape_meta: dict
meta attribute of a `regions.Shape` object
Returns
-------
meta : dict
DS9 compatible meta dictionary | [
"Makes",
"the",
"meta",
"data",
"DS9",
"compatible",
"by",
"filtering",
"and",
"mapping",
"the",
"valid",
"keys"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/core.py#L741-L775 | train |
astropy/regions | regions/io/core.py | _to_io_meta | def _to_io_meta(shape_meta, valid_keys, key_mappings):
"""
This is used to make meta data compatible with a specific io
by filtering and mapping to it's valid keys
Parameters
----------
shape_meta: dict
meta attribute of a `regions.Region` object
valid_keys : python list
Con... | python | def _to_io_meta(shape_meta, valid_keys, key_mappings):
"""
This is used to make meta data compatible with a specific io
by filtering and mapping to it's valid keys
Parameters
----------
shape_meta: dict
meta attribute of a `regions.Region` object
valid_keys : python list
Con... | [
"def",
"_to_io_meta",
"(",
"shape_meta",
",",
"valid_keys",
",",
"key_mappings",
")",
":",
"meta",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"shape_meta",
":",
"if",
"key",
"in",
"valid_keys",
":",
"meta",
"[",
"key_mappings",
".",
"get",
"(",
"key",
... | This is used to make meta data compatible with a specific io
by filtering and mapping to it's valid keys
Parameters
----------
shape_meta: dict
meta attribute of a `regions.Region` object
valid_keys : python list
Contains all the valid keys of a particular file format.
key_mappi... | [
"This",
"is",
"used",
"to",
"make",
"meta",
"data",
"compatible",
"with",
"a",
"specific",
"io",
"by",
"filtering",
"and",
"mapping",
"to",
"it",
"s",
"valid",
"keys"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/core.py#L809-L835 | train |
astropy/regions | regions/io/core.py | Shape.convert_coords | def convert_coords(self):
"""
Process list of coordinates
This mainly searches for tuple of coordinates in the coordinate list and
creates a SkyCoord or PixCoord object from them if appropriate for a
given region type. This involves again some coordinate transformation,
... | python | def convert_coords(self):
"""
Process list of coordinates
This mainly searches for tuple of coordinates in the coordinate list and
creates a SkyCoord or PixCoord object from them if appropriate for a
given region type. This involves again some coordinate transformation,
... | [
"def",
"convert_coords",
"(",
"self",
")",
":",
"if",
"self",
".",
"coordsys",
"in",
"[",
"'image'",
",",
"'physical'",
"]",
":",
"coords",
"=",
"self",
".",
"_convert_pix_coords",
"(",
")",
"else",
":",
"coords",
"=",
"self",
".",
"_convert_sky_coords",
... | Process list of coordinates
This mainly searches for tuple of coordinates in the coordinate list and
creates a SkyCoord or PixCoord object from them if appropriate for a
given region type. This involves again some coordinate transformation,
so this step could be moved to the parsing pro... | [
"Process",
"list",
"of",
"coordinates"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/core.py#L527-L547 | train |
astropy/regions | regions/io/core.py | Shape._convert_sky_coords | def _convert_sky_coords(self):
"""
Convert to sky coordinates
"""
parsed_angles = [(x, y)
for x, y in zip(self.coord[:-1:2], self.coord[1::2])
if (isinstance(x, coordinates.Angle) and isinstance(y, coordinates.Angle))
... | python | def _convert_sky_coords(self):
"""
Convert to sky coordinates
"""
parsed_angles = [(x, y)
for x, y in zip(self.coord[:-1:2], self.coord[1::2])
if (isinstance(x, coordinates.Angle) and isinstance(y, coordinates.Angle))
... | [
"def",
"_convert_sky_coords",
"(",
"self",
")",
":",
"parsed_angles",
"=",
"[",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"self",
".",
"coord",
"[",
":",
"-",
"1",
":",
"2",
"]",
",",
"self",
".",
"coord",
"[",
"1",
":"... | Convert to sky coordinates | [
"Convert",
"to",
"sky",
"coordinates"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/core.py#L549-L572 | train |
astropy/regions | regions/io/core.py | Shape._convert_pix_coords | def _convert_pix_coords(self):
"""
Convert to pixel coordinates, `regions.PixCoord`
"""
if self.region_type in ['polygon', 'line']:
# have to special-case polygon in the phys coord case
# b/c can't typecheck when iterating as in sky coord case
coords =... | python | def _convert_pix_coords(self):
"""
Convert to pixel coordinates, `regions.PixCoord`
"""
if self.region_type in ['polygon', 'line']:
# have to special-case polygon in the phys coord case
# b/c can't typecheck when iterating as in sky coord case
coords =... | [
"def",
"_convert_pix_coords",
"(",
"self",
")",
":",
"if",
"self",
".",
"region_type",
"in",
"[",
"'polygon'",
",",
"'line'",
"]",
":",
"coords",
"=",
"[",
"PixCoord",
"(",
"self",
".",
"coord",
"[",
"0",
":",
":",
"2",
"]",
",",
"self",
".",
"coor... | Convert to pixel coordinates, `regions.PixCoord` | [
"Convert",
"to",
"pixel",
"coordinates",
"regions",
".",
"PixCoord"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/core.py#L574-L592 | train |
astropy/regions | regions/io/core.py | Shape.to_region | def to_region(self):
"""
Converts to region, ``regions.Region`` object
"""
coords = self.convert_coords()
log.debug(coords)
viz_keywords = ['color', 'dash', 'dashlist', 'width', 'font', 'symsize',
'symbol', 'symsize', 'fontsize', 'fontstyle', 'use... | python | def to_region(self):
"""
Converts to region, ``regions.Region`` object
"""
coords = self.convert_coords()
log.debug(coords)
viz_keywords = ['color', 'dash', 'dashlist', 'width', 'font', 'symsize',
'symbol', 'symsize', 'fontsize', 'fontstyle', 'use... | [
"def",
"to_region",
"(",
"self",
")",
":",
"coords",
"=",
"self",
".",
"convert_coords",
"(",
")",
"log",
".",
"debug",
"(",
"coords",
")",
"viz_keywords",
"=",
"[",
"'color'",
",",
"'dash'",
",",
"'dashlist'",
",",
"'width'",
",",
"'font'",
",",
"'sym... | Converts to region, ``regions.Region`` object | [
"Converts",
"to",
"region",
"regions",
".",
"Region",
"object"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/core.py#L594-L628 | train |
astropy/regions | regions/io/core.py | Shape.check_crtf | def check_crtf(self):
"""
Checks for CRTF compatibility.
"""
if self.region_type not in regions_attributes:
raise ValueError("'{0}' is not a valid region type in this package"
"supported by CRTF".format(self.region_type))
if self.coordsys... | python | def check_crtf(self):
"""
Checks for CRTF compatibility.
"""
if self.region_type not in regions_attributes:
raise ValueError("'{0}' is not a valid region type in this package"
"supported by CRTF".format(self.region_type))
if self.coordsys... | [
"def",
"check_crtf",
"(",
"self",
")",
":",
"if",
"self",
".",
"region_type",
"not",
"in",
"regions_attributes",
":",
"raise",
"ValueError",
"(",
"\"'{0}' is not a valid region type in this package\"",
"\"supported by CRTF\"",
".",
"format",
"(",
"self",
".",
"region_... | Checks for CRTF compatibility. | [
"Checks",
"for",
"CRTF",
"compatibility",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/core.py#L633-L643 | train |
astropy/regions | regions/io/core.py | Shape.check_ds9 | def check_ds9(self):
"""
Checks for DS9 compatibility.
"""
if self.region_type not in regions_attributes:
raise ValueError("'{0}' is not a valid region type in this package"
"supported by DS9".format(self.region_type))
if self.coordsys no... | python | def check_ds9(self):
"""
Checks for DS9 compatibility.
"""
if self.region_type not in regions_attributes:
raise ValueError("'{0}' is not a valid region type in this package"
"supported by DS9".format(self.region_type))
if self.coordsys no... | [
"def",
"check_ds9",
"(",
"self",
")",
":",
"if",
"self",
".",
"region_type",
"not",
"in",
"regions_attributes",
":",
"raise",
"ValueError",
"(",
"\"'{0}' is not a valid region type in this package\"",
"\"supported by DS9\"",
".",
"format",
"(",
"self",
".",
"region_ty... | Checks for DS9 compatibility. | [
"Checks",
"for",
"DS9",
"compatibility",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/core.py#L645-L655 | train |
astropy/regions | regions/io/core.py | Shape._validate | def _validate(self):
"""
Checks whether all the attributes of this object is valid.
"""
if self.region_type not in regions_attributes:
raise ValueError("'{0}' is not a valid region type in this package"
.format(self.region_type))
if self.... | python | def _validate(self):
"""
Checks whether all the attributes of this object is valid.
"""
if self.region_type not in regions_attributes:
raise ValueError("'{0}' is not a valid region type in this package"
.format(self.region_type))
if self.... | [
"def",
"_validate",
"(",
"self",
")",
":",
"if",
"self",
".",
"region_type",
"not",
"in",
"regions_attributes",
":",
"raise",
"ValueError",
"(",
"\"'{0}' is not a valid region type in this package\"",
".",
"format",
"(",
"self",
".",
"region_type",
")",
")",
"if",... | Checks whether all the attributes of this object is valid. | [
"Checks",
"whether",
"all",
"the",
"attributes",
"of",
"this",
"object",
"is",
"valid",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/core.py#L657-L667 | train |
astropy/regions | regions/io/crtf/read.py | read_crtf | def read_crtf(filename, errors='strict'):
"""
Reads a CRTF region file and returns a list of region objects.
Parameters
----------
filename : `str`
The file path
errors : ``warn``, ``ignore``, ``strict``, optional
The error handling scheme to use for handling parsing errors.
... | python | def read_crtf(filename, errors='strict'):
"""
Reads a CRTF region file and returns a list of region objects.
Parameters
----------
filename : `str`
The file path
errors : ``warn``, ``ignore``, ``strict``, optional
The error handling scheme to use for handling parsing errors.
... | [
"def",
"read_crtf",
"(",
"filename",
",",
"errors",
"=",
"'strict'",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fh",
":",
"if",
"regex_begin",
".",
"search",
"(",
"fh",
".",
"readline",
"(",
")",
")",
":",
"region_string",
"=",
"fh",
".",... | Reads a CRTF region file and returns a list of region objects.
Parameters
----------
filename : `str`
The file path
errors : ``warn``, ``ignore``, ``strict``, optional
The error handling scheme to use for handling parsing errors.
The default is 'strict', which will raise a `~regions... | [
"Reads",
"a",
"CRTF",
"region",
"file",
"and",
"returns",
"a",
"list",
"of",
"region",
"objects",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/crtf/read.py#L43-L85 | train |
astropy/regions | regions/io/crtf/read.py | CRTFParser.parse_line | def parse_line(self, line):
"""
Parses a single line.
"""
# Skip blanks
if line == '':
return
# Skip comments
if regex_comment.search(line):
return
# Special case / header: parse global parameters into metadata
global_par... | python | def parse_line(self, line):
"""
Parses a single line.
"""
# Skip blanks
if line == '':
return
# Skip comments
if regex_comment.search(line):
return
# Special case / header: parse global parameters into metadata
global_par... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
"==",
"''",
":",
"return",
"if",
"regex_comment",
".",
"search",
"(",
"line",
")",
":",
"return",
"global_parameters",
"=",
"regex_global",
".",
"search",
"(",
"line",
")",
"if",
"g... | Parses a single line. | [
"Parses",
"a",
"single",
"line",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/crtf/read.py#L161-L199 | train |
astropy/regions | regions/io/crtf/read.py | CRTFRegionParser.parse | def parse(self):
"""
Starting point to parse the CRTF region string.
"""
self.convert_meta()
self.coordsys = self.meta.get('coord', 'image').lower()
self.set_coordsys()
self.convert_coordinates()
self.make_shape() | python | def parse(self):
"""
Starting point to parse the CRTF region string.
"""
self.convert_meta()
self.coordsys = self.meta.get('coord', 'image').lower()
self.set_coordsys()
self.convert_coordinates()
self.make_shape() | [
"def",
"parse",
"(",
"self",
")",
":",
"self",
".",
"convert_meta",
"(",
")",
"self",
".",
"coordsys",
"=",
"self",
".",
"meta",
".",
"get",
"(",
"'coord'",
",",
"'image'",
")",
".",
"lower",
"(",
")",
"self",
".",
"set_coordsys",
"(",
")",
"self",... | Starting point to parse the CRTF region string. | [
"Starting",
"point",
"to",
"parse",
"the",
"CRTF",
"region",
"string",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/crtf/read.py#L320-L329 | train |
astropy/regions | regions/io/crtf/read.py | CRTFRegionParser.set_coordsys | def set_coordsys(self):
"""
Mapping to astropy's coordinate system name
# TODO: needs expert attention (Most reference systems are not mapped)
"""
if self.coordsys.lower() in self.coordsys_mapping:
self.coordsys = self.coordsys_mapping[self.coordsys.lower()] | python | def set_coordsys(self):
"""
Mapping to astropy's coordinate system name
# TODO: needs expert attention (Most reference systems are not mapped)
"""
if self.coordsys.lower() in self.coordsys_mapping:
self.coordsys = self.coordsys_mapping[self.coordsys.lower()] | [
"def",
"set_coordsys",
"(",
"self",
")",
":",
"if",
"self",
".",
"coordsys",
".",
"lower",
"(",
")",
"in",
"self",
".",
"coordsys_mapping",
":",
"self",
".",
"coordsys",
"=",
"self",
".",
"coordsys_mapping",
"[",
"self",
".",
"coordsys",
".",
"lower",
... | Mapping to astropy's coordinate system name
# TODO: needs expert attention (Most reference systems are not mapped) | [
"Mapping",
"to",
"astropy",
"s",
"coordinate",
"system",
"name"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/crtf/read.py#L331-L338 | train |
astropy/regions | regions/io/crtf/read.py | CRTFRegionParser.convert_coordinates | def convert_coordinates(self):
"""
Convert coordinate string to `~astropy.coordinates.Angle` or `~astropy.units.quantity.Quantity` objects
"""
coord_list_str = regex_coordinate.findall(self.reg_str) + regex_length.findall(self.reg_str)
coord_list = []
if self.region_type... | python | def convert_coordinates(self):
"""
Convert coordinate string to `~astropy.coordinates.Angle` or `~astropy.units.quantity.Quantity` objects
"""
coord_list_str = regex_coordinate.findall(self.reg_str) + regex_length.findall(self.reg_str)
coord_list = []
if self.region_type... | [
"def",
"convert_coordinates",
"(",
"self",
")",
":",
"coord_list_str",
"=",
"regex_coordinate",
".",
"findall",
"(",
"self",
".",
"reg_str",
")",
"+",
"regex_length",
".",
"findall",
"(",
"self",
".",
"reg_str",
")",
"coord_list",
"=",
"[",
"]",
"if",
"sel... | Convert coordinate string to `~astropy.coordinates.Angle` or `~astropy.units.quantity.Quantity` objects | [
"Convert",
"coordinate",
"string",
"to",
"~astropy",
".",
"coordinates",
".",
"Angle",
"or",
"~astropy",
".",
"units",
".",
"quantity",
".",
"Quantity",
"objects"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/crtf/read.py#L340-L387 | train |
astropy/regions | regions/io/crtf/read.py | CRTFRegionParser.convert_meta | def convert_meta(self):
"""
Parses the meta_str to python dictionary and stores in ``meta`` attribute.
"""
if self.meta_str:
self.meta_str = regex_meta.findall(self.meta_str + ',')
if self.meta_str:
for par in self.meta_str:
if par[0] is no... | python | def convert_meta(self):
"""
Parses the meta_str to python dictionary and stores in ``meta`` attribute.
"""
if self.meta_str:
self.meta_str = regex_meta.findall(self.meta_str + ',')
if self.meta_str:
for par in self.meta_str:
if par[0] is no... | [
"def",
"convert_meta",
"(",
"self",
")",
":",
"if",
"self",
".",
"meta_str",
":",
"self",
".",
"meta_str",
"=",
"regex_meta",
".",
"findall",
"(",
"self",
".",
"meta_str",
"+",
"','",
")",
"if",
"self",
".",
"meta_str",
":",
"for",
"par",
"in",
"self... | Parses the meta_str to python dictionary and stores in ``meta`` attribute. | [
"Parses",
"the",
"meta_str",
"to",
"python",
"dictionary",
"and",
"stores",
"in",
"meta",
"attribute",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/crtf/read.py#L389-L419 | train |
astropy/regions | regions/io/fits/write.py | fits_region_objects_to_table | def fits_region_objects_to_table(regions):
"""
Converts list of regions to FITS region table.
Parameters
----------
regions : list
List of `regions.Region` objects
Returns
-------
region_string : `~astropy.table.Table`
FITS region table
Examples
--------
>... | python | def fits_region_objects_to_table(regions):
"""
Converts list of regions to FITS region table.
Parameters
----------
regions : list
List of `regions.Region` objects
Returns
-------
region_string : `~astropy.table.Table`
FITS region table
Examples
--------
>... | [
"def",
"fits_region_objects_to_table",
"(",
"regions",
")",
":",
"for",
"reg",
"in",
"regions",
":",
"if",
"isinstance",
"(",
"reg",
",",
"SkyRegion",
")",
":",
"raise",
"TypeError",
"(",
"'Every region must be a pixel region'",
".",
"format",
"(",
"reg",
")",
... | Converts list of regions to FITS region table.
Parameters
----------
regions : list
List of `regions.Region` objects
Returns
-------
region_string : `~astropy.table.Table`
FITS region table
Examples
--------
>>> from regions import CirclePixelRegion, PixCoord
... | [
"Converts",
"list",
"of",
"regions",
"to",
"FITS",
"region",
"table",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/fits/write.py#L15-L47 | train |
astropy/regions | regions/io/fits/write.py | write_fits_region | def write_fits_region(filename, regions, header=None):
"""
Converts list of regions to FITS region table and write to a file.
Parameters
----------
filename: str
Filename in which the table is to be written. Default is 'new.fits'
regions: list
List of `regions.Region` objects
... | python | def write_fits_region(filename, regions, header=None):
"""
Converts list of regions to FITS region table and write to a file.
Parameters
----------
filename: str
Filename in which the table is to be written. Default is 'new.fits'
regions: list
List of `regions.Region` objects
... | [
"def",
"write_fits_region",
"(",
"filename",
",",
"regions",
",",
"header",
"=",
"None",
")",
":",
"output",
"=",
"fits_region_objects_to_table",
"(",
"regions",
")",
"bin_table",
"=",
"fits",
".",
"BinTableHDU",
"(",
"data",
"=",
"output",
",",
"header",
"=... | Converts list of regions to FITS region table and write to a file.
Parameters
----------
filename: str
Filename in which the table is to be written. Default is 'new.fits'
regions: list
List of `regions.Region` objects
header: `~astropy.io.fits.header.Header` object
The FITS ... | [
"Converts",
"list",
"of",
"regions",
"to",
"FITS",
"region",
"table",
"and",
"write",
"to",
"a",
"file",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/fits/write.py#L50-L78 | train |
astropy/regions | regions/_utils/examples.py | make_example_dataset | def make_example_dataset(data='simulated', config=None):
"""Make example dataset.
This is a factory function for ``ExampleDataset`` objects.
The following config options are available (default values shown):
* ``crval = 0, 0``
* ``crpix = 180, 90``
* ``cdelt = -1, 1``
* ``shape = 180, 360... | python | def make_example_dataset(data='simulated', config=None):
"""Make example dataset.
This is a factory function for ``ExampleDataset`` objects.
The following config options are available (default values shown):
* ``crval = 0, 0``
* ``crpix = 180, 90``
* ``cdelt = -1, 1``
* ``shape = 180, 360... | [
"def",
"make_example_dataset",
"(",
"data",
"=",
"'simulated'",
",",
"config",
"=",
"None",
")",
":",
"if",
"data",
"==",
"'simulated'",
":",
"return",
"ExampleDatasetSimulated",
"(",
"config",
"=",
"config",
")",
"elif",
"data",
"==",
"'fermi'",
":",
"retur... | Make example dataset.
This is a factory function for ``ExampleDataset`` objects.
The following config options are available (default values shown):
* ``crval = 0, 0``
* ``crpix = 180, 90``
* ``cdelt = -1, 1``
* ``shape = 180, 360``
* ``ctype = 'GLON-AIT', 'GLAT-AIT'``
Parameters
... | [
"Make",
"example",
"dataset",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/_utils/examples.py#L17-L64 | train |
astropy/regions | regions/_utils/examples.py | _table_to_bintable | def _table_to_bintable(table):
"""Convert `~astropy.table.Table` to `astropy.io.fits.BinTable`."""
data = table.as_array()
header = fits.Header()
header.update(table.meta)
name = table.meta.pop('name', None)
return fits.BinTableHDU(data, header, name=name) | python | def _table_to_bintable(table):
"""Convert `~astropy.table.Table` to `astropy.io.fits.BinTable`."""
data = table.as_array()
header = fits.Header()
header.update(table.meta)
name = table.meta.pop('name', None)
return fits.BinTableHDU(data, header, name=name) | [
"def",
"_table_to_bintable",
"(",
"table",
")",
":",
"data",
"=",
"table",
".",
"as_array",
"(",
")",
"header",
"=",
"fits",
".",
"Header",
"(",
")",
"header",
".",
"update",
"(",
"table",
".",
"meta",
")",
"name",
"=",
"table",
".",
"meta",
".",
"... | Convert `~astropy.table.Table` to `astropy.io.fits.BinTable`. | [
"Convert",
"~astropy",
".",
"table",
".",
"Table",
"to",
"astropy",
".",
"io",
".",
"fits",
".",
"BinTable",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/_utils/examples.py#L223-L229 | train |
astropy/regions | regions/io/ds9/read.py | read_ds9 | def read_ds9(filename, errors='strict'):
"""
Read a DS9 region file in as a `list` of `~regions.Region` objects.
Parameters
----------
filename : `str`
The file path
errors : ``warn``, ``ignore``, ``strict``, optional
The error handling scheme to use for handling parsing errors.
... | python | def read_ds9(filename, errors='strict'):
"""
Read a DS9 region file in as a `list` of `~regions.Region` objects.
Parameters
----------
filename : `str`
The file path
errors : ``warn``, ``ignore``, ``strict``, optional
The error handling scheme to use for handling parsing errors.
... | [
"def",
"read_ds9",
"(",
"filename",
",",
"errors",
"=",
"'strict'",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fh",
":",
"region_string",
"=",
"fh",
".",
"read",
"(",
")",
"parser",
"=",
"DS9Parser",
"(",
"region_string",
",",
"errors",
"="... | Read a DS9 region file in as a `list` of `~regions.Region` objects.
Parameters
----------
filename : `str`
The file path
errors : ``warn``, ``ignore``, ``strict``, optional
The error handling scheme to use for handling parsing errors.
The default is 'strict', which will raise a `~re... | [
"Read",
"a",
"DS9",
"region",
"file",
"in",
"as",
"a",
"list",
"of",
"~regions",
".",
"Region",
"objects",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L38-L77 | train |
astropy/regions | regions/io/ds9/read.py | DS9Parser.set_coordsys | def set_coordsys(self, coordsys):
"""
Transform coordinate system
# TODO: needs expert attention
"""
if coordsys in self.coordsys_mapping:
self.coordsys = self.coordsys_mapping[coordsys]
else:
self.coordsys = coordsys | python | def set_coordsys(self, coordsys):
"""
Transform coordinate system
# TODO: needs expert attention
"""
if coordsys in self.coordsys_mapping:
self.coordsys = self.coordsys_mapping[coordsys]
else:
self.coordsys = coordsys | [
"def",
"set_coordsys",
"(",
"self",
",",
"coordsys",
")",
":",
"if",
"coordsys",
"in",
"self",
".",
"coordsys_mapping",
":",
"self",
".",
"coordsys",
"=",
"self",
".",
"coordsys_mapping",
"[",
"coordsys",
"]",
"else",
":",
"self",
".",
"coordsys",
"=",
"... | Transform coordinate system
# TODO: needs expert attention | [
"Transform",
"coordinate",
"system"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L215-L224 | train |
astropy/regions | regions/io/ds9/read.py | DS9Parser.run | def run(self):
"""
Run all steps
"""
for line_ in self.region_string.split('\n'):
for line in line_.split(";"):
self.parse_line(line)
log.debug('Global state: {}'.format(self)) | python | def run(self):
"""
Run all steps
"""
for line_ in self.region_string.split('\n'):
for line in line_.split(";"):
self.parse_line(line)
log.debug('Global state: {}'.format(self)) | [
"def",
"run",
"(",
"self",
")",
":",
"for",
"line_",
"in",
"self",
".",
"region_string",
".",
"split",
"(",
"'\\n'",
")",
":",
"for",
"line",
"in",
"line_",
".",
"split",
"(",
"\";\"",
")",
":",
"self",
".",
"parse_line",
"(",
"line",
")",
"log",
... | Run all steps | [
"Run",
"all",
"steps"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L226-L233 | train |
astropy/regions | regions/io/ds9/read.py | DS9Parser.parse_meta | def parse_meta(meta_str):
"""
Parse the metadata for a single ds9 region string.
Parameters
----------
meta_str : `str`
Meta string, the metadata is everything after the close-paren of the
region coordinate specification. All metadata is specified as
... | python | def parse_meta(meta_str):
"""
Parse the metadata for a single ds9 region string.
Parameters
----------
meta_str : `str`
Meta string, the metadata is everything after the close-paren of the
region coordinate specification. All metadata is specified as
... | [
"def",
"parse_meta",
"(",
"meta_str",
")",
":",
"keys_vals",
"=",
"[",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"_",
",",
"y",
"in",
"regex_meta",
".",
"findall",
"(",
"meta_str",
".",
"strip",
"(",
")",
")",
"]",
"extra_text",
"=",
"regex_meta",
... | Parse the metadata for a single ds9 region string.
Parameters
----------
meta_str : `str`
Meta string, the metadata is everything after the close-paren of the
region coordinate specification. All metadata is specified as
key=value pairs separated by whitespac... | [
"Parse",
"the",
"metadata",
"for",
"a",
"single",
"ds9",
"region",
"string",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L288-L327 | train |
astropy/regions | regions/io/ds9/read.py | DS9Parser.parse_region | def parse_region(self, include, region_type, region_end, line):
"""
Extract a Shape from a region string
"""
if self.coordsys is None:
raise DS9RegionParserError("No coordinate system specified and a"
" region has been found.")
e... | python | def parse_region(self, include, region_type, region_end, line):
"""
Extract a Shape from a region string
"""
if self.coordsys is None:
raise DS9RegionParserError("No coordinate system specified and a"
" region has been found.")
e... | [
"def",
"parse_region",
"(",
"self",
",",
"include",
",",
"region_type",
",",
"region_end",
",",
"line",
")",
":",
"if",
"self",
".",
"coordsys",
"is",
"None",
":",
"raise",
"DS9RegionParserError",
"(",
"\"No coordinate system specified and a\"",
"\" region has been ... | Extract a Shape from a region string | [
"Extract",
"a",
"Shape",
"from",
"a",
"region",
"string"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L329-L344 | train |
astropy/regions | regions/io/ds9/read.py | DS9RegionParser.parse | def parse(self):
"""
Convert line to shape object
"""
log.debug(self)
self.parse_composite()
self.split_line()
self.convert_coordinates()
self.convert_meta()
self.make_shape()
log.debug(self) | python | def parse(self):
"""
Convert line to shape object
"""
log.debug(self)
self.parse_composite()
self.split_line()
self.convert_coordinates()
self.convert_meta()
self.make_shape()
log.debug(self) | [
"def",
"parse",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"self",
")",
"self",
".",
"parse_composite",
"(",
")",
"self",
".",
"split_line",
"(",
")",
"self",
".",
"convert_coordinates",
"(",
")",
"self",
".",
"convert_meta",
"(",
")",
"self",
... | Convert line to shape object | [
"Convert",
"line",
"to",
"shape",
"object"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L431-L442 | train |
astropy/regions | regions/io/ds9/read.py | DS9RegionParser.split_line | def split_line(self):
"""
Split line into coordinates and meta string
"""
# coordinate of the # symbol or end of the line (-1) if not found
hash_or_end = self.line.find("#")
temp = self.line[self.region_end:hash_or_end].strip(" |")
self.coord_str = regex_paren.sub... | python | def split_line(self):
"""
Split line into coordinates and meta string
"""
# coordinate of the # symbol or end of the line (-1) if not found
hash_or_end = self.line.find("#")
temp = self.line[self.region_end:hash_or_end].strip(" |")
self.coord_str = regex_paren.sub... | [
"def",
"split_line",
"(",
"self",
")",
":",
"hash_or_end",
"=",
"self",
".",
"line",
".",
"find",
"(",
"\"#\"",
")",
"temp",
"=",
"self",
".",
"line",
"[",
"self",
".",
"region_end",
":",
"hash_or_end",
"]",
".",
"strip",
"(",
"\" |\"",
")",
"self",
... | Split line into coordinates and meta string | [
"Split",
"line",
"into",
"coordinates",
"and",
"meta",
"string"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L450-L463 | train |
astropy/regions | regions/io/ds9/read.py | DS9RegionParser.convert_coordinates | def convert_coordinates(self):
"""
Convert coordinate string to objects
"""
coord_list = []
# strip out "null" elements, i.e. ''. It might be possible to eliminate
# these some other way, i.e. with regex directly, but I don't know how.
# We need to copy in order ... | python | def convert_coordinates(self):
"""
Convert coordinate string to objects
"""
coord_list = []
# strip out "null" elements, i.e. ''. It might be possible to eliminate
# these some other way, i.e. with regex directly, but I don't know how.
# We need to copy in order ... | [
"def",
"convert_coordinates",
"(",
"self",
")",
":",
"coord_list",
"=",
"[",
"]",
"elements",
"=",
"[",
"x",
"for",
"x",
"in",
"regex_splitter",
".",
"split",
"(",
"self",
".",
"coord_str",
")",
"if",
"x",
"]",
"element_parsers",
"=",
"self",
".",
"lan... | Convert coordinate string to objects | [
"Convert",
"coordinate",
"string",
"to",
"objects"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L465-L494 | train |
astropy/regions | regions/io/ds9/read.py | DS9RegionParser.convert_meta | def convert_meta(self):
"""
Convert meta string to dict
"""
meta_ = DS9Parser.parse_meta(self.meta_str)
self.meta = copy.deepcopy(self.global_meta)
self.meta.update(meta_)
# the 'include' is not part of the metadata string;
# it is pre-parsed as part of th... | python | def convert_meta(self):
"""
Convert meta string to dict
"""
meta_ = DS9Parser.parse_meta(self.meta_str)
self.meta = copy.deepcopy(self.global_meta)
self.meta.update(meta_)
# the 'include' is not part of the metadata string;
# it is pre-parsed as part of th... | [
"def",
"convert_meta",
"(",
"self",
")",
":",
"meta_",
"=",
"DS9Parser",
".",
"parse_meta",
"(",
"self",
".",
"meta_str",
")",
"self",
".",
"meta",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"global_meta",
")",
"self",
".",
"meta",
".",
"update",
... | Convert meta string to dict | [
"Convert",
"meta",
"string",
"to",
"dict"
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L496-L507 | train |
astropy/regions | regions/core/pixcoord.py | PixCoord._validate | def _validate(val, name, expected='any'):
"""Validate that a given object is an appropriate `PixCoord`.
This is used for input validation throughout the regions package,
especially in the `__init__` method of pixel region classes.
Parameters
----------
val : `PixCoord`
... | python | def _validate(val, name, expected='any'):
"""Validate that a given object is an appropriate `PixCoord`.
This is used for input validation throughout the regions package,
especially in the `__init__` method of pixel region classes.
Parameters
----------
val : `PixCoord`
... | [
"def",
"_validate",
"(",
"val",
",",
"name",
",",
"expected",
"=",
"'any'",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"PixCoord",
")",
":",
"raise",
"TypeError",
"(",
"'{} must be a PixCoord'",
".",
"format",
"(",
"name",
")",
")",
"if",
"e... | Validate that a given object is an appropriate `PixCoord`.
This is used for input validation throughout the regions package,
especially in the `__init__` method of pixel region classes.
Parameters
----------
val : `PixCoord`
The object to check
name : str
... | [
"Validate",
"that",
"a",
"given",
"object",
"is",
"an",
"appropriate",
"PixCoord",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/core/pixcoord.py#L45-L79 | train |
astropy/regions | regions/core/pixcoord.py | PixCoord.to_sky | def to_sky(self, wcs, origin=_DEFAULT_WCS_ORIGIN, mode=_DEFAULT_WCS_MODE):
"""Convert this `PixCoord` to `~astropy.coordinates.SkyCoord`.
Calls :meth:`astropy.coordinates.SkyCoord.from_pixel`.
See parameter description there.
"""
return SkyCoord.from_pixel(
xp=self.x... | python | def to_sky(self, wcs, origin=_DEFAULT_WCS_ORIGIN, mode=_DEFAULT_WCS_MODE):
"""Convert this `PixCoord` to `~astropy.coordinates.SkyCoord`.
Calls :meth:`astropy.coordinates.SkyCoord.from_pixel`.
See parameter description there.
"""
return SkyCoord.from_pixel(
xp=self.x... | [
"def",
"to_sky",
"(",
"self",
",",
"wcs",
",",
"origin",
"=",
"_DEFAULT_WCS_ORIGIN",
",",
"mode",
"=",
"_DEFAULT_WCS_MODE",
")",
":",
"return",
"SkyCoord",
".",
"from_pixel",
"(",
"xp",
"=",
"self",
".",
"x",
",",
"yp",
"=",
"self",
".",
"y",
",",
"w... | Convert this `PixCoord` to `~astropy.coordinates.SkyCoord`.
Calls :meth:`astropy.coordinates.SkyCoord.from_pixel`.
See parameter description there. | [
"Convert",
"this",
"PixCoord",
"to",
"~astropy",
".",
"coordinates",
".",
"SkyCoord",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/core/pixcoord.py#L123-L132 | train |
astropy/regions | regions/core/pixcoord.py | PixCoord.from_sky | def from_sky(cls, skycoord, wcs, origin=_DEFAULT_WCS_ORIGIN, mode=_DEFAULT_WCS_MODE):
"""Create `PixCoord` from `~astropy.coordinates.SkyCoord`.
Calls :meth:`astropy.coordinates.SkyCoord.to_pixel`.
See parameter description there.
"""
x, y = skycoord.to_pixel(wcs=wcs, origin=ori... | python | def from_sky(cls, skycoord, wcs, origin=_DEFAULT_WCS_ORIGIN, mode=_DEFAULT_WCS_MODE):
"""Create `PixCoord` from `~astropy.coordinates.SkyCoord`.
Calls :meth:`astropy.coordinates.SkyCoord.to_pixel`.
See parameter description there.
"""
x, y = skycoord.to_pixel(wcs=wcs, origin=ori... | [
"def",
"from_sky",
"(",
"cls",
",",
"skycoord",
",",
"wcs",
",",
"origin",
"=",
"_DEFAULT_WCS_ORIGIN",
",",
"mode",
"=",
"_DEFAULT_WCS_MODE",
")",
":",
"x",
",",
"y",
"=",
"skycoord",
".",
"to_pixel",
"(",
"wcs",
"=",
"wcs",
",",
"origin",
"=",
"origin... | Create `PixCoord` from `~astropy.coordinates.SkyCoord`.
Calls :meth:`astropy.coordinates.SkyCoord.to_pixel`.
See parameter description there. | [
"Create",
"PixCoord",
"from",
"~astropy",
".",
"coordinates",
".",
"SkyCoord",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/core/pixcoord.py#L135-L142 | train |
astropy/regions | regions/core/pixcoord.py | PixCoord.separation | def separation(self, other):
r"""Separation to another pixel coordinate.
This is the two-dimensional cartesian separation :math:`d` with
.. math::
d = \sqrt{(x_1 - x_2) ^ 2 + (y_1 - y_2) ^ 2}
Parameters
----------
other : `PixCoord`
Other pixel ... | python | def separation(self, other):
r"""Separation to another pixel coordinate.
This is the two-dimensional cartesian separation :math:`d` with
.. math::
d = \sqrt{(x_1 - x_2) ^ 2 + (y_1 - y_2) ^ 2}
Parameters
----------
other : `PixCoord`
Other pixel ... | [
"def",
"separation",
"(",
"self",
",",
"other",
")",
":",
"r",
"dx",
"=",
"other",
".",
"x",
"-",
"self",
".",
"x",
"dy",
"=",
"other",
".",
"y",
"-",
"self",
".",
"y",
"return",
"np",
".",
"hypot",
"(",
"dx",
",",
"dy",
")"
] | r"""Separation to another pixel coordinate.
This is the two-dimensional cartesian separation :math:`d` with
.. math::
d = \sqrt{(x_1 - x_2) ^ 2 + (y_1 - y_2) ^ 2}
Parameters
----------
other : `PixCoord`
Other pixel coordinate
Returns
-... | [
"r",
"Separation",
"to",
"another",
"pixel",
"coordinate",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/core/pixcoord.py#L144-L164 | train |
astropy/regions | regions/_utils/wcs_helpers.py | skycoord_to_pixel_scale_angle | def skycoord_to_pixel_scale_angle(skycoord, wcs, small_offset=1 * u.arcsec):
"""
Convert a set of SkyCoord coordinates into pixel coordinates, pixel
scales, and position angles.
Parameters
----------
skycoord : `~astropy.coordinates.SkyCoord`
Sky coordinates
wcs : `~astropy.wcs.WCS`... | python | def skycoord_to_pixel_scale_angle(skycoord, wcs, small_offset=1 * u.arcsec):
"""
Convert a set of SkyCoord coordinates into pixel coordinates, pixel
scales, and position angles.
Parameters
----------
skycoord : `~astropy.coordinates.SkyCoord`
Sky coordinates
wcs : `~astropy.wcs.WCS`... | [
"def",
"skycoord_to_pixel_scale_angle",
"(",
"skycoord",
",",
"wcs",
",",
"small_offset",
"=",
"1",
"*",
"u",
".",
"arcsec",
")",
":",
"x",
",",
"y",
"=",
"skycoord_to_pixel",
"(",
"skycoord",
",",
"wcs",
",",
"mode",
"=",
"skycoord_to_pixel_mode",
")",
"p... | Convert a set of SkyCoord coordinates into pixel coordinates, pixel
scales, and position angles.
Parameters
----------
skycoord : `~astropy.coordinates.SkyCoord`
Sky coordinates
wcs : `~astropy.wcs.WCS`
The WCS transformation to use
small_offset : `~astropy.units.Quantity`
... | [
"Convert",
"a",
"set",
"of",
"SkyCoord",
"coordinates",
"into",
"pixel",
"coordinates",
"pixel",
"scales",
"and",
"position",
"angles",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/_utils/wcs_helpers.py#L13-L69 | train |
astropy/regions | regions/_utils/wcs_helpers.py | assert_angle | def assert_angle(name, q):
"""
Check that ``q`` is an angular `~astropy.units.Quantity`.
"""
if isinstance(q, u.Quantity):
if q.unit.physical_type == 'angle':
pass
else:
raise ValueError("{0} should have angular units".format(name))
else:
raise TypeErr... | python | def assert_angle(name, q):
"""
Check that ``q`` is an angular `~astropy.units.Quantity`.
"""
if isinstance(q, u.Quantity):
if q.unit.physical_type == 'angle':
pass
else:
raise ValueError("{0} should have angular units".format(name))
else:
raise TypeErr... | [
"def",
"assert_angle",
"(",
"name",
",",
"q",
")",
":",
"if",
"isinstance",
"(",
"q",
",",
"u",
".",
"Quantity",
")",
":",
"if",
"q",
".",
"unit",
".",
"physical_type",
"==",
"'angle'",
":",
"pass",
"else",
":",
"raise",
"ValueError",
"(",
"\"{0} sho... | Check that ``q`` is an angular `~astropy.units.Quantity`. | [
"Check",
"that",
"q",
"is",
"an",
"angular",
"~astropy",
".",
"units",
".",
"Quantity",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/_utils/wcs_helpers.py#L86-L96 | train |
astropy/regions | ah_bootstrap.py | _silence | def _silence():
"""A context manager that silences sys.stdout and sys.stderr."""
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = _DummyFile()
sys.stderr = _DummyFile()
exception_occurred = False
try:
yield
except:
exception_occurred = True
# Go ahead... | python | def _silence():
"""A context manager that silences sys.stdout and sys.stderr."""
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = _DummyFile()
sys.stderr = _DummyFile()
exception_occurred = False
try:
yield
except:
exception_occurred = True
# Go ahead... | [
"def",
"_silence",
"(",
")",
":",
"old_stdout",
"=",
"sys",
".",
"stdout",
"old_stderr",
"=",
"sys",
".",
"stderr",
"sys",
".",
"stdout",
"=",
"_DummyFile",
"(",
")",
"sys",
".",
"stderr",
"=",
"_DummyFile",
"(",
")",
"exception_occurred",
"=",
"False",
... | A context manager that silences sys.stdout and sys.stderr. | [
"A",
"context",
"manager",
"that",
"silences",
"sys",
".",
"stdout",
"and",
"sys",
".",
"stderr",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/ah_bootstrap.py#L914-L933 | train |
astropy/regions | ah_bootstrap.py | use_astropy_helpers | def use_astropy_helpers(**kwargs):
"""
Ensure that the `astropy_helpers` module is available and is importable.
This supports automatic submodule initialization if astropy_helpers is
included in a project as a git submodule, or will download it from PyPI if
necessary.
Parameters
----------
... | python | def use_astropy_helpers(**kwargs):
"""
Ensure that the `astropy_helpers` module is available and is importable.
This supports automatic submodule initialization if astropy_helpers is
included in a project as a git submodule, or will download it from PyPI if
necessary.
Parameters
----------
... | [
"def",
"use_astropy_helpers",
"(",
"**",
"kwargs",
")",
":",
"global",
"BOOTSTRAPPER",
"config",
"=",
"BOOTSTRAPPER",
".",
"config",
"config",
".",
"update",
"(",
"**",
"kwargs",
")",
"BOOTSTRAPPER",
"=",
"_Bootstrapper",
"(",
"**",
"config",
")",
"BOOTSTRAPPE... | Ensure that the `astropy_helpers` module is available and is importable.
This supports automatic submodule initialization if astropy_helpers is
included in a project as a git submodule, or will download it from PyPI if
necessary.
Parameters
----------
path : str or None, optional
A fil... | [
"Ensure",
"that",
"the",
"astropy_helpers",
"module",
"is",
"available",
"and",
"is",
"importable",
".",
"This",
"supports",
"automatic",
"submodule",
"initialization",
"if",
"astropy_helpers",
"is",
"included",
"in",
"a",
"project",
"as",
"a",
"git",
"submodule",... | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/ah_bootstrap.py#L959-L1022 | train |
astropy/regions | ah_bootstrap.py | _Bootstrapper.config | def config(self):
"""
A `dict` containing the options this `_Bootstrapper` was configured
with.
"""
return dict((optname, getattr(self, optname))
for optname, _ in CFG_OPTIONS if hasattr(self, optname)) | python | def config(self):
"""
A `dict` containing the options this `_Bootstrapper` was configured
with.
"""
return dict((optname, getattr(self, optname))
for optname, _ in CFG_OPTIONS if hasattr(self, optname)) | [
"def",
"config",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"optname",
",",
"getattr",
"(",
"self",
",",
"optname",
")",
")",
"for",
"optname",
",",
"_",
"in",
"CFG_OPTIONS",
"if",
"hasattr",
"(",
"self",
",",
"optname",
")",
")"
] | A `dict` containing the options this `_Bootstrapper` was configured
with. | [
"A",
"dict",
"containing",
"the",
"options",
"this",
"_Bootstrapper",
"was",
"configured",
"with",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/ah_bootstrap.py#L393-L400 | train |
astropy/regions | ah_bootstrap.py | _Bootstrapper.get_local_directory_dist | def get_local_directory_dist(self):
"""
Handle importing a vendored package from a subdirectory of the source
distribution.
"""
if not os.path.isdir(self.path):
return
log.info('Attempting to import astropy_helpers from {0} {1!r}'.format(
's... | python | def get_local_directory_dist(self):
"""
Handle importing a vendored package from a subdirectory of the source
distribution.
"""
if not os.path.isdir(self.path):
return
log.info('Attempting to import astropy_helpers from {0} {1!r}'.format(
's... | [
"def",
"get_local_directory_dist",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"path",
")",
":",
"return",
"log",
".",
"info",
"(",
"'Attempting to import astropy_helpers from {0} {1!r}'",
".",
"format",
"(",
"'submod... | Handle importing a vendored package from a subdirectory of the source
distribution. | [
"Handle",
"importing",
"a",
"vendored",
"package",
"from",
"a",
"subdirectory",
"of",
"the",
"source",
"distribution",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/ah_bootstrap.py#L402-L429 | train |
astropy/regions | ah_bootstrap.py | _Bootstrapper.get_local_file_dist | def get_local_file_dist(self):
"""
Handle importing from a source archive; this also uses setup_requires
but points easy_install directly to the source archive.
"""
if not os.path.isfile(self.path):
return
log.info('Attempting to unpack and import astropy_he... | python | def get_local_file_dist(self):
"""
Handle importing from a source archive; this also uses setup_requires
but points easy_install directly to the source archive.
"""
if not os.path.isfile(self.path):
return
log.info('Attempting to unpack and import astropy_he... | [
"def",
"get_local_file_dist",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"path",
")",
":",
"return",
"log",
".",
"info",
"(",
"'Attempting to unpack and import astropy_helpers from '",
"'{0!r}'",
".",
"format",
"(",... | Handle importing from a source archive; this also uses setup_requires
but points easy_install directly to the source archive. | [
"Handle",
"importing",
"from",
"a",
"source",
"archive",
";",
"this",
"also",
"uses",
"setup_requires",
"but",
"points",
"easy_install",
"directly",
"to",
"the",
"source",
"archive",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/ah_bootstrap.py#L431-L461 | train |
astropy/regions | ah_bootstrap.py | _Bootstrapper._directory_import | def _directory_import(self):
"""
Import astropy_helpers from the given path, which will be added to
sys.path.
Must return True if the import succeeded, and False otherwise.
"""
# Return True on success, False on failure but download is allowed, and
# otherwise r... | python | def _directory_import(self):
"""
Import astropy_helpers from the given path, which will be added to
sys.path.
Must return True if the import succeeded, and False otherwise.
"""
# Return True on success, False on failure but download is allowed, and
# otherwise r... | [
"def",
"_directory_import",
"(",
"self",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"path",
")",
"ws",
"=",
"pkg_resources",
".",
"WorkingSet",
"(",
"[",
"]",
")",
"ws",
".",
"add_entry",
"(",
"path",
")",
"dist",
"... | Import astropy_helpers from the given path, which will be added to
sys.path.
Must return True if the import succeeded, and False otherwise. | [
"Import",
"astropy_helpers",
"from",
"the",
"given",
"path",
"which",
"will",
"be",
"added",
"to",
"sys",
".",
"path",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/ah_bootstrap.py#L486-L519 | train |
astropy/regions | ah_bootstrap.py | _Bootstrapper._check_submodule | def _check_submodule(self):
"""
Check if the given path is a git submodule.
See the docstrings for ``_check_submodule_using_git`` and
``_check_submodule_no_git`` for further details.
"""
if (self.path is None or
(os.path.exists(self.path) and not os.path... | python | def _check_submodule(self):
"""
Check if the given path is a git submodule.
See the docstrings for ``_check_submodule_using_git`` and
``_check_submodule_no_git`` for further details.
"""
if (self.path is None or
(os.path.exists(self.path) and not os.path... | [
"def",
"_check_submodule",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"path",
"is",
"None",
"or",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"path",
... | Check if the given path is a git submodule.
See the docstrings for ``_check_submodule_using_git`` and
``_check_submodule_no_git`` for further details. | [
"Check",
"if",
"the",
"given",
"path",
"is",
"a",
"git",
"submodule",
"."
] | 452d962c417e4ff20d1268f99535c6ff89c83437 | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/ah_bootstrap.py#L607-L622 | train |
EconForge/dolo | dolo/numeric/tensor.py | sdot | def sdot( U, V ):
'''
Computes the tensorproduct reducing last dimensoin of U with first dimension of V.
For matrices, it is equal to regular matrix product.
'''
nu = U.ndim
#nv = V.ndim
return np.tensordot( U, V, axes=(nu-1,0) ) | python | def sdot( U, V ):
'''
Computes the tensorproduct reducing last dimensoin of U with first dimension of V.
For matrices, it is equal to regular matrix product.
'''
nu = U.ndim
#nv = V.ndim
return np.tensordot( U, V, axes=(nu-1,0) ) | [
"def",
"sdot",
"(",
"U",
",",
"V",
")",
":",
"nu",
"=",
"U",
".",
"ndim",
"return",
"np",
".",
"tensordot",
"(",
"U",
",",
"V",
",",
"axes",
"=",
"(",
"nu",
"-",
"1",
",",
"0",
")",
")"
] | Computes the tensorproduct reducing last dimensoin of U with first dimension of V.
For matrices, it is equal to regular matrix product. | [
"Computes",
"the",
"tensorproduct",
"reducing",
"last",
"dimensoin",
"of",
"U",
"with",
"first",
"dimension",
"of",
"V",
".",
"For",
"matrices",
"it",
"is",
"equal",
"to",
"regular",
"matrix",
"product",
"."
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/tensor.py#L44-L51 | train |
EconForge/dolo | dolo/numeric/interpolation/smolyak.py | SmolyakBasic.set_values | def set_values(self,x):
""" Updates self.theta parameter. No returns values"""
x = numpy.atleast_2d(x)
x = x.real # ahem
C_inv = self.__C_inv__
theta = numpy.dot( x, C_inv )
self.theta = theta
return theta | python | def set_values(self,x):
""" Updates self.theta parameter. No returns values"""
x = numpy.atleast_2d(x)
x = x.real # ahem
C_inv = self.__C_inv__
theta = numpy.dot( x, C_inv )
self.theta = theta
return theta | [
"def",
"set_values",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"numpy",
".",
"atleast_2d",
"(",
"x",
")",
"x",
"=",
"x",
".",
"real",
"C_inv",
"=",
"self",
".",
"__C_inv__",
"theta",
"=",
"numpy",
".",
"dot",
"(",
"x",
",",
"C_inv",
")",
"self... | Updates self.theta parameter. No returns values | [
"Updates",
"self",
".",
"theta",
"parameter",
".",
"No",
"returns",
"values"
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/interpolation/smolyak.py#L256-L267 | train |
EconForge/dolo | dolo/numeric/discretization/discretization.py | tauchen | def tauchen(N, mu, rho, sigma, m=2):
"""
Approximate an AR1 process by a finite markov chain using Tauchen's method.
:param N: scalar, number of nodes for Z
:param mu: scalar, unconditional mean of process
:param rho: scalar
:param sigma: scalar, std. dev. of epsilons
:param m: max +- std. ... | python | def tauchen(N, mu, rho, sigma, m=2):
"""
Approximate an AR1 process by a finite markov chain using Tauchen's method.
:param N: scalar, number of nodes for Z
:param mu: scalar, unconditional mean of process
:param rho: scalar
:param sigma: scalar, std. dev. of epsilons
:param m: max +- std. ... | [
"def",
"tauchen",
"(",
"N",
",",
"mu",
",",
"rho",
",",
"sigma",
",",
"m",
"=",
"2",
")",
":",
"Z",
"=",
"np",
".",
"zeros",
"(",
"(",
"N",
",",
"1",
")",
")",
"Zprob",
"=",
"np",
".",
"zeros",
"(",
"(",
"N",
",",
"N",
")",
")",
"a",
... | Approximate an AR1 process by a finite markov chain using Tauchen's method.
:param N: scalar, number of nodes for Z
:param mu: scalar, unconditional mean of process
:param rho: scalar
:param sigma: scalar, std. dev. of epsilons
:param m: max +- std. devs.
:returns: Z, N*1 vector, nodes for Z. Z... | [
"Approximate",
"an",
"AR1",
"process",
"by",
"a",
"finite",
"markov",
"chain",
"using",
"Tauchen",
"s",
"method",
"."
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/discretization/discretization.py#L13-L50 | train |
EconForge/dolo | dolo/numeric/discretization/discretization.py | rouwenhorst | def rouwenhorst(rho, sigma, N):
"""
Approximate an AR1 process by a finite markov chain using Rouwenhorst's method.
:param rho: autocorrelation of the AR1 process
:param sigma: conditional standard deviation of the AR1 process
:param N: number of states
:return [nodes, P]: equally spaced nodes ... | python | def rouwenhorst(rho, sigma, N):
"""
Approximate an AR1 process by a finite markov chain using Rouwenhorst's method.
:param rho: autocorrelation of the AR1 process
:param sigma: conditional standard deviation of the AR1 process
:param N: number of states
:return [nodes, P]: equally spaced nodes ... | [
"def",
"rouwenhorst",
"(",
"rho",
",",
"sigma",
",",
"N",
")",
":",
"from",
"numpy",
"import",
"sqrt",
",",
"linspace",
",",
"array",
",",
"zeros",
"sigma",
"=",
"float",
"(",
"sigma",
")",
"if",
"N",
"==",
"1",
":",
"nodes",
"=",
"array",
"(",
"... | Approximate an AR1 process by a finite markov chain using Rouwenhorst's method.
:param rho: autocorrelation of the AR1 process
:param sigma: conditional standard deviation of the AR1 process
:param N: number of states
:return [nodes, P]: equally spaced nodes and transition matrix | [
"Approximate",
"an",
"AR1",
"process",
"by",
"a",
"finite",
"markov",
"chain",
"using",
"Rouwenhorst",
"s",
"method",
"."
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/discretization/discretization.py#L53-L97 | train |
EconForge/dolo | dolo/numeric/discretization/discretization.py | tensor_markov | def tensor_markov( *args ):
"""Computes the product of two independent markov chains.
:param m1: a tuple containing the nodes and the transition matrix of the first chain
:param m2: a tuple containing the nodes and the transition matrix of the second chain
:return: a tuple containing the nodes and the ... | python | def tensor_markov( *args ):
"""Computes the product of two independent markov chains.
:param m1: a tuple containing the nodes and the transition matrix of the first chain
:param m2: a tuple containing the nodes and the transition matrix of the second chain
:return: a tuple containing the nodes and the ... | [
"def",
"tensor_markov",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"m1",
"=",
"args",
"[",
"0",
"]",
"m2",
"=",
"args",
"[",
"1",
"]",
"tail",
"=",
"args",
"[",
"2",
":",
"]",
"prod",
"=",
"tensor_markov",
"(",
... | Computes the product of two independent markov chains.
:param m1: a tuple containing the nodes and the transition matrix of the first chain
:param m2: a tuple containing the nodes and the transition matrix of the second chain
:return: a tuple containing the nodes and the transition matrix of the product ch... | [
"Computes",
"the",
"product",
"of",
"two",
"independent",
"markov",
"chains",
"."
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/discretization/discretization.py#L155-L201 | train |
EconForge/dolo | trash/dolo/misc/modfile.py | dynare_import | def dynare_import(filename,full_output=False, debug=False):
'''Imports model defined in specified file'''
import os
basename = os.path.basename(filename)
fname = re.compile('(.*)\.(.*)').match(basename).group(1)
f = open(filename)
txt = f.read()
model = parse_dynare_text(txt,full_output=full... | python | def dynare_import(filename,full_output=False, debug=False):
'''Imports model defined in specified file'''
import os
basename = os.path.basename(filename)
fname = re.compile('(.*)\.(.*)').match(basename).group(1)
f = open(filename)
txt = f.read()
model = parse_dynare_text(txt,full_output=full... | [
"def",
"dynare_import",
"(",
"filename",
",",
"full_output",
"=",
"False",
",",
"debug",
"=",
"False",
")",
":",
"import",
"os",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"fname",
"=",
"re",
".",
"compile",
"(",
"'(.*)\... | Imports model defined in specified file | [
"Imports",
"model",
"defined",
"in",
"specified",
"file"
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/trash/dolo/misc/modfile.py#L311-L320 | train |
EconForge/dolo | dolo/algos/perfect_foresight.py | _shocks_to_epsilons | def _shocks_to_epsilons(model, shocks, T):
"""
Helper function to support input argument `shocks` being one of many
different data types. Will always return a `T, n_e` matrix.
"""
n_e = len(model.calibration['exogenous'])
# if we have a DataFrame, convert it to a dict and rely on the method bel... | python | def _shocks_to_epsilons(model, shocks, T):
"""
Helper function to support input argument `shocks` being one of many
different data types. Will always return a `T, n_e` matrix.
"""
n_e = len(model.calibration['exogenous'])
# if we have a DataFrame, convert it to a dict and rely on the method bel... | [
"def",
"_shocks_to_epsilons",
"(",
"model",
",",
"shocks",
",",
"T",
")",
":",
"n_e",
"=",
"len",
"(",
"model",
".",
"calibration",
"[",
"'exogenous'",
"]",
")",
"if",
"isinstance",
"(",
"shocks",
",",
"pd",
".",
"DataFrame",
")",
":",
"shocks",
"=",
... | Helper function to support input argument `shocks` being one of many
different data types. Will always return a `T, n_e` matrix. | [
"Helper",
"function",
"to",
"support",
"input",
"argument",
"shocks",
"being",
"one",
"of",
"many",
"different",
"data",
"types",
".",
"Will",
"always",
"return",
"a",
"T",
"n_e",
"matrix",
"."
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/algos/perfect_foresight.py#L9-L49 | train |
EconForge/dolo | trash/dolo/misc/symbolic_interactive.py | clear_all | def clear_all():
"""
Clears all parameters, variables, and shocks defined previously
"""
frame = inspect.currentframe().f_back
try:
if frame.f_globals.get('variables_order'):
# we should avoid to declare symbols twice !
del frame.f_globals['variables_order']
... | python | def clear_all():
"""
Clears all parameters, variables, and shocks defined previously
"""
frame = inspect.currentframe().f_back
try:
if frame.f_globals.get('variables_order'):
# we should avoid to declare symbols twice !
del frame.f_globals['variables_order']
... | [
"def",
"clear_all",
"(",
")",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"try",
":",
"if",
"frame",
".",
"f_globals",
".",
"get",
"(",
"'variables_order'",
")",
":",
"del",
"frame",
".",
"f_globals",
"[",
"'variables_orde... | Clears all parameters, variables, and shocks defined previously | [
"Clears",
"all",
"parameters",
"variables",
"and",
"shocks",
"defined",
"previously"
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/trash/dolo/misc/symbolic_interactive.py#L319-L333 | train |
EconForge/dolo | trash/dolo/algos/dtcscc/nonlinearsystem.py | nonlinear_system | def nonlinear_system(model, initial_dr=None, maxit=10, tol=1e-8, grid={}, distribution={}, verbose=True):
'''
Finds a global solution for ``model`` by solving one large system of equations
using a simple newton algorithm.
Parameters
----------
model: NumericModel
"dtcscc" model to be ... | python | def nonlinear_system(model, initial_dr=None, maxit=10, tol=1e-8, grid={}, distribution={}, verbose=True):
'''
Finds a global solution for ``model`` by solving one large system of equations
using a simple newton algorithm.
Parameters
----------
model: NumericModel
"dtcscc" model to be ... | [
"def",
"nonlinear_system",
"(",
"model",
",",
"initial_dr",
"=",
"None",
",",
"maxit",
"=",
"10",
",",
"tol",
"=",
"1e-8",
",",
"grid",
"=",
"{",
"}",
",",
"distribution",
"=",
"{",
"}",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"verbose",
":",
... | Finds a global solution for ``model`` by solving one large system of equations
using a simple newton algorithm.
Parameters
----------
model: NumericModel
"dtcscc" model to be solved
verbose: boolean
if True, display iterations
initial_dr: decision rule
initial guess for ... | [
"Finds",
"a",
"global",
"solution",
"for",
"model",
"by",
"solving",
"one",
"large",
"system",
"of",
"equations",
"using",
"a",
"simple",
"newton",
"algorithm",
"."
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/trash/dolo/algos/dtcscc/nonlinearsystem.py#L10-L97 | train |
EconForge/dolo | dolo/numeric/discretization/quadrature.py | gauss_hermite_nodes | def gauss_hermite_nodes(orders, sigma, mu=None):
'''
Computes the weights and nodes for Gauss Hermite quadrature.
Parameters
----------
orders : int, list, array
The order of integration used in the quadrature routine
sigma : array-like
If one dimensional, the variance of the no... | python | def gauss_hermite_nodes(orders, sigma, mu=None):
'''
Computes the weights and nodes for Gauss Hermite quadrature.
Parameters
----------
orders : int, list, array
The order of integration used in the quadrature routine
sigma : array-like
If one dimensional, the variance of the no... | [
"def",
"gauss_hermite_nodes",
"(",
"orders",
",",
"sigma",
",",
"mu",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"orders",
",",
"int",
")",
":",
"orders",
"=",
"[",
"orders",
"]",
"import",
"numpy",
"if",
"mu",
"is",
"None",
":",
"mu",
"=",
"n... | Computes the weights and nodes for Gauss Hermite quadrature.
Parameters
----------
orders : int, list, array
The order of integration used in the quadrature routine
sigma : array-like
If one dimensional, the variance of the normal distribution being
approximated. If multidimensi... | [
"Computes",
"the",
"weights",
"and",
"nodes",
"for",
"Gauss",
"Hermite",
"quadrature",
"."
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/discretization/quadrature.py#L59-L122 | train |
EconForge/dolo | dolo/numeric/optimize/newton.py | newton | def newton(f, x, verbose=False, tol=1e-6, maxit=5, jactype='serial'):
"""Solve nonlinear system using safeguarded Newton iterations
Parameters
----------
Return
------
"""
if verbose:
print = lambda txt: old_print(txt)
else:
print = lambda txt: None
it = 0
e... | python | def newton(f, x, verbose=False, tol=1e-6, maxit=5, jactype='serial'):
"""Solve nonlinear system using safeguarded Newton iterations
Parameters
----------
Return
------
"""
if verbose:
print = lambda txt: old_print(txt)
else:
print = lambda txt: None
it = 0
e... | [
"def",
"newton",
"(",
"f",
",",
"x",
",",
"verbose",
"=",
"False",
",",
"tol",
"=",
"1e-6",
",",
"maxit",
"=",
"5",
",",
"jactype",
"=",
"'serial'",
")",
":",
"if",
"verbose",
":",
"print",
"=",
"lambda",
"txt",
":",
"old_print",
"(",
"txt",
")",... | Solve nonlinear system using safeguarded Newton iterations
Parameters
----------
Return
------ | [
"Solve",
"nonlinear",
"system",
"using",
"safeguarded",
"Newton",
"iterations"
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/optimize/newton.py#L81-L151 | train |
EconForge/dolo | dolo/numeric/extern/qz.py | qzordered | def qzordered(A,B,crit=1.0):
"Eigenvalues bigger than crit are sorted in the top-left."
TOL = 1e-10
def select(alpha, beta):
return alpha**2>crit*beta**2
[S,T,alpha,beta,U,V] = ordqz(A,B,output='real',sort=select)
eigval = abs(numpy.diag(S)/numpy.diag(T))
return [S,T,U,V,eigval] | python | def qzordered(A,B,crit=1.0):
"Eigenvalues bigger than crit are sorted in the top-left."
TOL = 1e-10
def select(alpha, beta):
return alpha**2>crit*beta**2
[S,T,alpha,beta,U,V] = ordqz(A,B,output='real',sort=select)
eigval = abs(numpy.diag(S)/numpy.diag(T))
return [S,T,U,V,eigval] | [
"def",
"qzordered",
"(",
"A",
",",
"B",
",",
"crit",
"=",
"1.0",
")",
":",
"\"Eigenvalues bigger than crit are sorted in the top-left.\"",
"TOL",
"=",
"1e-10",
"def",
"select",
"(",
"alpha",
",",
"beta",
")",
":",
"return",
"alpha",
"**",
"2",
">",
"crit",
... | Eigenvalues bigger than crit are sorted in the top-left. | [
"Eigenvalues",
"bigger",
"than",
"crit",
"are",
"sorted",
"in",
"the",
"top",
"-",
"left",
"."
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/extern/qz.py#L6-L18 | train |
EconForge/dolo | dolo/numeric/extern/qz.py | ordqz | def ordqz(A, B, sort='lhp', output='real', overwrite_a=False,
overwrite_b=False, check_finite=True):
"""
QZ decomposition for a pair of matrices with reordering.
.. versionadded:: 0.17.0
Parameters
----------
A : (N, N) array_like
2d array to decompose
B : (N, N) array_li... | python | def ordqz(A, B, sort='lhp', output='real', overwrite_a=False,
overwrite_b=False, check_finite=True):
"""
QZ decomposition for a pair of matrices with reordering.
.. versionadded:: 0.17.0
Parameters
----------
A : (N, N) array_like
2d array to decompose
B : (N, N) array_li... | [
"def",
"ordqz",
"(",
"A",
",",
"B",
",",
"sort",
"=",
"'lhp'",
",",
"output",
"=",
"'real'",
",",
"overwrite_a",
"=",
"False",
",",
"overwrite_b",
"=",
"False",
",",
"check_finite",
"=",
"True",
")",
":",
"import",
"warnings",
"import",
"numpy",
"as",
... | QZ decomposition for a pair of matrices with reordering.
.. versionadded:: 0.17.0
Parameters
----------
A : (N, N) array_like
2d array to decompose
B : (N, N) array_like
2d array to decompose
sort : {callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
Specifies whether the ... | [
"QZ",
"decomposition",
"for",
"a",
"pair",
"of",
"matrices",
"with",
"reordering",
"."
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/extern/qz.py#L21-L154 | train |
EconForge/dolo | trash/dolo/algos/dtcscc/time_iteration_2.py | parameterized_expectations_direct | def parameterized_expectations_direct(model, verbose=False, initial_dr=None,
pert_order=1, grid={}, distribution={},
maxit=100, tol=1e-8):
'''
Finds a global solution for ``model`` using parameterized expectations
function. Requires... | python | def parameterized_expectations_direct(model, verbose=False, initial_dr=None,
pert_order=1, grid={}, distribution={},
maxit=100, tol=1e-8):
'''
Finds a global solution for ``model`` using parameterized expectations
function. Requires... | [
"def",
"parameterized_expectations_direct",
"(",
"model",
",",
"verbose",
"=",
"False",
",",
"initial_dr",
"=",
"None",
",",
"pert_order",
"=",
"1",
",",
"grid",
"=",
"{",
"}",
",",
"distribution",
"=",
"{",
"}",
",",
"maxit",
"=",
"100",
",",
"tol",
"... | Finds a global solution for ``model`` using parameterized expectations
function. Requires the model to be written with controls as a direct
function of the model objects.
The algorithm iterates on the expectations function in the arbitrage
equation. It follows the discussion in section 9.9 of Miranda a... | [
"Finds",
"a",
"global",
"solution",
"for",
"model",
"using",
"parameterized",
"expectations",
"function",
".",
"Requires",
"the",
"model",
"to",
"be",
"written",
"with",
"controls",
"as",
"a",
"direct",
"function",
"of",
"the",
"model",
"objects",
"."
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/trash/dolo/algos/dtcscc/time_iteration_2.py#L186-L312 | train |
EconForge/dolo | dolo/compiler/misc.py | numdiff | def numdiff(fun, args):
"""Vectorized numerical differentiation"""
# vectorized version
epsilon = 1e-8
args = list(args)
v0 = fun(*args)
N = v0.shape[0]
l_v = len(v0)
dvs = []
for i, a in enumerate(args):
l_a = (a).shape[1]
dv = numpy.zeros((N, l_v, l_a))
na... | python | def numdiff(fun, args):
"""Vectorized numerical differentiation"""
# vectorized version
epsilon = 1e-8
args = list(args)
v0 = fun(*args)
N = v0.shape[0]
l_v = len(v0)
dvs = []
for i, a in enumerate(args):
l_a = (a).shape[1]
dv = numpy.zeros((N, l_v, l_a))
na... | [
"def",
"numdiff",
"(",
"fun",
",",
"args",
")",
":",
"epsilon",
"=",
"1e-8",
"args",
"=",
"list",
"(",
"args",
")",
"v0",
"=",
"fun",
"(",
"*",
"args",
")",
"N",
"=",
"v0",
".",
"shape",
"[",
"0",
"]",
"l_v",
"=",
"len",
"(",
"v0",
")",
"dv... | Vectorized numerical differentiation | [
"Vectorized",
"numerical",
"differentiation"
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/compiler/misc.py#L97-L118 | train |
EconForge/dolo | dolo/numeric/filters.py | bandpass_filter | def bandpass_filter(data, k, w1, w2):
"""
This function will apply a bandpass filter to data. It will be kth
order and will select the band between w1 and w2.
Parameters
----------
data: array, dtype=float
The data you wish to filter
k: number, int
The order ... | python | def bandpass_filter(data, k, w1, w2):
"""
This function will apply a bandpass filter to data. It will be kth
order and will select the band between w1 and w2.
Parameters
----------
data: array, dtype=float
The data you wish to filter
k: number, int
The order ... | [
"def",
"bandpass_filter",
"(",
"data",
",",
"k",
",",
"w1",
",",
"w2",
")",
":",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"low_w",
"=",
"np",
".",
"pi",
"*",
"2",
"/",
"w2",
"high_w",
"=",
"np",
".",
"pi",
"*",
"2",
"/",
"w1",
"... | This function will apply a bandpass filter to data. It will be kth
order and will select the band between w1 and w2.
Parameters
----------
data: array, dtype=float
The data you wish to filter
k: number, int
The order of approximation for the filter. A max value for
... | [
"This",
"function",
"will",
"apply",
"a",
"bandpass",
"filter",
"to",
"data",
".",
"It",
"will",
"be",
"kth",
"order",
"and",
"will",
"select",
"the",
"band",
"between",
"w1",
"and",
"w2",
"."
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/numeric/filters.py#L83-L119 | train |
EconForge/dolo | dolo/misc/dprint.py | dprint | def dprint(s):
'''Prints `s` with additional debugging informations'''
import inspect
frameinfo = inspect.stack()[1]
callerframe = frameinfo.frame
d = callerframe.f_locals
if (isinstance(s,str)):
val = eval(s, d)
else:
val = s
cc = frameinfo.code_context[0]
... | python | def dprint(s):
'''Prints `s` with additional debugging informations'''
import inspect
frameinfo = inspect.stack()[1]
callerframe = frameinfo.frame
d = callerframe.f_locals
if (isinstance(s,str)):
val = eval(s, d)
else:
val = s
cc = frameinfo.code_context[0]
... | [
"def",
"dprint",
"(",
"s",
")",
":",
"import",
"inspect",
"frameinfo",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"1",
"]",
"callerframe",
"=",
"frameinfo",
".",
"frame",
"d",
"=",
"callerframe",
".",
"f_locals",
"if",
"(",
"isinstance",
"(",
"s",
... | Prints `s` with additional debugging informations | [
"Prints",
"s",
"with",
"additional",
"debugging",
"informations"
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/misc/dprint.py#L21-L46 | train |
EconForge/dolo | dolo/compiler/function_compiler_sympy.py | non_decreasing_series | def non_decreasing_series(n, size):
'''Lists all combinations of 0,...,n-1 in increasing order'''
if size == 1:
return [[a] for a in range(n)]
else:
lc = non_decreasing_series(n, size-1)
ll = []
for l in lc:
last = l[-1]
for i in range(last, n):
... | python | def non_decreasing_series(n, size):
'''Lists all combinations of 0,...,n-1 in increasing order'''
if size == 1:
return [[a] for a in range(n)]
else:
lc = non_decreasing_series(n, size-1)
ll = []
for l in lc:
last = l[-1]
for i in range(last, n):
... | [
"def",
"non_decreasing_series",
"(",
"n",
",",
"size",
")",
":",
"if",
"size",
"==",
"1",
":",
"return",
"[",
"[",
"a",
"]",
"for",
"a",
"in",
"range",
"(",
"n",
")",
"]",
"else",
":",
"lc",
"=",
"non_decreasing_series",
"(",
"n",
",",
"size",
"-... | Lists all combinations of 0,...,n-1 in increasing order | [
"Lists",
"all",
"combinations",
"of",
"0",
"...",
"n",
"-",
"1",
"in",
"increasing",
"order"
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/compiler/function_compiler_sympy.py#L13-L26 | train |
EconForge/dolo | dolo/compiler/function_compiler_sympy.py | higher_order_diff | def higher_order_diff(eqs, syms, order=2):
'''Takes higher order derivatives of a list of equations w.r.t a list of paramters'''
import numpy
eqs = list([sympy.sympify(eq) for eq in eqs])
syms = list([sympy.sympify(s) for s in syms])
neq = len(eqs)
p = len(syms)
D = [numpy.array(eqs)]
... | python | def higher_order_diff(eqs, syms, order=2):
'''Takes higher order derivatives of a list of equations w.r.t a list of paramters'''
import numpy
eqs = list([sympy.sympify(eq) for eq in eqs])
syms = list([sympy.sympify(s) for s in syms])
neq = len(eqs)
p = len(syms)
D = [numpy.array(eqs)]
... | [
"def",
"higher_order_diff",
"(",
"eqs",
",",
"syms",
",",
"order",
"=",
"2",
")",
":",
"import",
"numpy",
"eqs",
"=",
"list",
"(",
"[",
"sympy",
".",
"sympify",
"(",
"eq",
")",
"for",
"eq",
"in",
"eqs",
"]",
")",
"syms",
"=",
"list",
"(",
"[",
... | Takes higher order derivatives of a list of equations w.r.t a list of paramters | [
"Takes",
"higher",
"order",
"derivatives",
"of",
"a",
"list",
"of",
"equations",
"w",
".",
"r",
".",
"t",
"a",
"list",
"of",
"paramters"
] | d91ddf148b009bf79852d9aec70f3a1877e0f79a | https://github.com/EconForge/dolo/blob/d91ddf148b009bf79852d9aec70f3a1877e0f79a/dolo/compiler/function_compiler_sympy.py#L28-L60 | train |
pokerregion/poker | poker/website/pocketfives.py | get_ranked_players | def get_ranked_players():
"""Get the list of the first 100 ranked players."""
rankings_page = requests.get(RANKINGS_URL)
root = etree.HTML(rankings_page.text)
player_rows = root.xpath('//div[@id="ranked"]//tr')
for row in player_rows[1:]:
player_row = row.xpath('td[@class!="country"]//text... | python | def get_ranked_players():
"""Get the list of the first 100 ranked players."""
rankings_page = requests.get(RANKINGS_URL)
root = etree.HTML(rankings_page.text)
player_rows = root.xpath('//div[@id="ranked"]//tr')
for row in player_rows[1:]:
player_row = row.xpath('td[@class!="country"]//text... | [
"def",
"get_ranked_players",
"(",
")",
":",
"rankings_page",
"=",
"requests",
".",
"get",
"(",
"RANKINGS_URL",
")",
"root",
"=",
"etree",
".",
"HTML",
"(",
"rankings_page",
".",
"text",
")",
"player_rows",
"=",
"root",
".",
"xpath",
"(",
"'//div[@id=\"ranked... | Get the list of the first 100 ranked players. | [
"Get",
"the",
"list",
"of",
"the",
"first",
"100",
"ranked",
"players",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/website/pocketfives.py#L31-L50 | train |
pokerregion/poker | poker/card.py | Rank.difference | def difference(cls, first, second):
"""Tells the numerical difference between two ranks."""
# so we always get a Rank instance even if string were passed in
first, second = cls(first), cls(second)
rank_list = list(cls)
return abs(rank_list.index(first) - rank_list.index(second)) | python | def difference(cls, first, second):
"""Tells the numerical difference between two ranks."""
# so we always get a Rank instance even if string were passed in
first, second = cls(first), cls(second)
rank_list = list(cls)
return abs(rank_list.index(first) - rank_list.index(second)) | [
"def",
"difference",
"(",
"cls",
",",
"first",
",",
"second",
")",
":",
"first",
",",
"second",
"=",
"cls",
"(",
"first",
")",
",",
"cls",
"(",
"second",
")",
"rank_list",
"=",
"list",
"(",
"cls",
")",
"return",
"abs",
"(",
"rank_list",
".",
"index... | Tells the numerical difference between two ranks. | [
"Tells",
"the",
"numerical",
"difference",
"between",
"two",
"ranks",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/card.py#L42-L48 | train |
pokerregion/poker | poker/card.py | _CardMeta.make_random | def make_random(cls):
"""Returns a random Card instance."""
self = object.__new__(cls)
self.rank = Rank.make_random()
self.suit = Suit.make_random()
return self | python | def make_random(cls):
"""Returns a random Card instance."""
self = object.__new__(cls)
self.rank = Rank.make_random()
self.suit = Suit.make_random()
return self | [
"def",
"make_random",
"(",
"cls",
")",
":",
"self",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"self",
".",
"rank",
"=",
"Rank",
".",
"make_random",
"(",
")",
"self",
".",
"suit",
"=",
"Suit",
".",
"make_random",
"(",
")",
"return",
"self"
] | Returns a random Card instance. | [
"Returns",
"a",
"random",
"Card",
"instance",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/card.py#L64-L69 | train |
pokerregion/poker | poker/commands.py | twoplustwo_player | def twoplustwo_player(username):
"""Get profile information about a Two plus Two Forum member given the username."""
from .website.twoplustwo import ForumMember, AmbiguousUserNameError, UserNotFoundError
try:
member = ForumMember(username)
except UserNotFoundError:
raise click.ClickExc... | python | def twoplustwo_player(username):
"""Get profile information about a Two plus Two Forum member given the username."""
from .website.twoplustwo import ForumMember, AmbiguousUserNameError, UserNotFoundError
try:
member = ForumMember(username)
except UserNotFoundError:
raise click.ClickExc... | [
"def",
"twoplustwo_player",
"(",
"username",
")",
":",
"from",
".",
"website",
".",
"twoplustwo",
"import",
"ForumMember",
",",
"AmbiguousUserNameError",
",",
"UserNotFoundError",
"try",
":",
"member",
"=",
"ForumMember",
"(",
"username",
")",
"except",
"UserNotFo... | Get profile information about a Two plus Two Forum member given the username. | [
"Get",
"profile",
"information",
"about",
"a",
"Two",
"plus",
"Two",
"Forum",
"member",
"given",
"the",
"username",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/commands.py#L59-L95 | train |
pokerregion/poker | poker/commands.py | p5list | def p5list(num):
"""List pocketfives ranked players, max 100 if no NUM, or NUM if specified."""
from .website.pocketfives import get_ranked_players
format_str = '{:>4.4} {!s:<15.13}{!s:<18.15}{!s:<9.6}{!s:<10.7}'\
'{!s:<14.11}{!s:<12.9}{!s:<12.9}{!s:<12.9}{!s:<4.4}'
click.echo(form... | python | def p5list(num):
"""List pocketfives ranked players, max 100 if no NUM, or NUM if specified."""
from .website.pocketfives import get_ranked_players
format_str = '{:>4.4} {!s:<15.13}{!s:<18.15}{!s:<9.6}{!s:<10.7}'\
'{!s:<14.11}{!s:<12.9}{!s:<12.9}{!s:<12.9}{!s:<4.4}'
click.echo(form... | [
"def",
"p5list",
"(",
"num",
")",
":",
"from",
".",
"website",
".",
"pocketfives",
"import",
"get_ranked_players",
"format_str",
"=",
"'{:>4.4} {!s:<15.13}{!s:<18.15}{!s:<9.6}{!s:<10.7}'",
"'{!s:<14.11}{!s:<12.9}{!s:<12.9}{!s:<12.9}{!s:<4.4}'",
"click",
".",
"echo",
"(",
... | List pocketfives ranked players, max 100 if no NUM, or NUM if specified. | [
"List",
"pocketfives",
"ranked",
"players",
"max",
"100",
"if",
"no",
"NUM",
"or",
"NUM",
"if",
"specified",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/commands.py#L100-L119 | train |
pokerregion/poker | poker/commands.py | psstatus | def psstatus():
"""Shows PokerStars status such as number of players, tournaments."""
from .website.pokerstars import get_status
_print_header('PokerStars status')
status = get_status()
_print_values(
('Info updated', status.updated),
('Tables', status.tables),
('Players', ... | python | def psstatus():
"""Shows PokerStars status such as number of players, tournaments."""
from .website.pokerstars import get_status
_print_header('PokerStars status')
status = get_status()
_print_values(
('Info updated', status.updated),
('Tables', status.tables),
('Players', ... | [
"def",
"psstatus",
"(",
")",
":",
"from",
".",
"website",
".",
"pokerstars",
"import",
"get_status",
"_print_header",
"(",
"'PokerStars status'",
")",
"status",
"=",
"get_status",
"(",
")",
"_print_values",
"(",
"(",
"'Info updated'",
",",
"status",
".",
"upda... | Shows PokerStars status such as number of players, tournaments. | [
"Shows",
"PokerStars",
"status",
"such",
"as",
"number",
"of",
"players",
"tournaments",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/commands.py#L123-L145 | train |
pokerregion/poker | poker/room/pokerstars.py | Notes.notes | def notes(self):
"""Tuple of notes.."""
return tuple(self._get_note_data(note) for note in self.root.iter('note')) | python | def notes(self):
"""Tuple of notes.."""
return tuple(self._get_note_data(note) for note in self.root.iter('note')) | [
"def",
"notes",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"self",
".",
"_get_note_data",
"(",
"note",
")",
"for",
"note",
"in",
"self",
".",
"root",
".",
"iter",
"(",
"'note'",
")",
")"
] | Tuple of notes.. | [
"Tuple",
"of",
"notes",
".."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L335-L337 | train |
pokerregion/poker | poker/room/pokerstars.py | Notes.labels | def labels(self):
"""Tuple of labels."""
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label')) | python | def labels(self):
"""Tuple of labels."""
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label')) | [
"def",
"labels",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"_Label",
"(",
"label",
".",
"get",
"(",
"'id'",
")",
",",
"label",
".",
"get",
"(",
"'color'",
")",
",",
"label",
".",
"text",
")",
"for",
"label",
"in",
"self",
".",
"root",
".",
... | Tuple of labels. | [
"Tuple",
"of",
"labels",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L340-L343 | train |
pokerregion/poker | poker/room/pokerstars.py | Notes.add_note | def add_note(self, player, text, label=None, update=None):
"""Add a note to the xml. If update param is None, it will be the current time."""
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
... | python | def add_note(self, player, text, label=None, update=None):
"""Add a note to the xml. If update param is None, it will be the current time."""
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
... | [
"def",
"add_note",
"(",
"self",
",",
"player",
",",
"text",
",",
"label",
"=",
"None",
",",
"update",
"=",
"None",
")",
":",
"if",
"label",
"is",
"not",
"None",
"and",
"(",
"label",
"not",
"in",
"self",
".",
"label_names",
")",
":",
"raise",
"Label... | Add a note to the xml. If update param is None, it will be the current time. | [
"Add",
"a",
"note",
"to",
"the",
"xml",
".",
"If",
"update",
"param",
"is",
"None",
"it",
"will",
"be",
"the",
"current",
"time",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L354-L365 | train |
pokerregion/poker | poker/room/pokerstars.py | Notes.append_note | def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text | python | def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text | [
"def",
"append_note",
"(",
"self",
",",
"player",
",",
"text",
")",
":",
"note",
"=",
"self",
".",
"_find_note",
"(",
"player",
")",
"note",
".",
"text",
"+=",
"text"
] | Append text to an already existing note. | [
"Append",
"text",
"to",
"an",
"already",
"existing",
"note",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L367-L370 | train |
pokerregion/poker | poker/room/pokerstars.py | Notes.prepend_note | def prepend_note(self, player, text):
"""Prepend text to an already existing note."""
note = self._find_note(player)
note.text = text + note.text | python | def prepend_note(self, player, text):
"""Prepend text to an already existing note."""
note = self._find_note(player)
note.text = text + note.text | [
"def",
"prepend_note",
"(",
"self",
",",
"player",
",",
"text",
")",
":",
"note",
"=",
"self",
".",
"_find_note",
"(",
"player",
")",
"note",
".",
"text",
"=",
"text",
"+",
"note",
".",
"text"
] | Prepend text to an already existing note. | [
"Prepend",
"text",
"to",
"an",
"already",
"existing",
"note",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L372-L375 | train |
pokerregion/poker | poker/room/pokerstars.py | Notes.get_label | def get_label(self, name):
"""Find the label by name."""
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text) | python | def get_label(self, name):
"""Find the label by name."""
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text) | [
"def",
"get_label",
"(",
"self",
",",
"name",
")",
":",
"label_tag",
"=",
"self",
".",
"_find_label",
"(",
"name",
")",
"return",
"_Label",
"(",
"label_tag",
".",
"get",
"(",
"'id'",
")",
",",
"label_tag",
".",
"get",
"(",
"'color'",
")",
",",
"label... | Find the label by name. | [
"Find",
"the",
"label",
"by",
"name",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L412-L415 | train |
pokerregion/poker | poker/room/pokerstars.py | Notes.add_label | def add_label(self, name, color):
"""Add a new label. It's id will automatically be calculated."""
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels... | python | def add_label(self, name, color):
"""Add a new label. It's id will automatically be calculated."""
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels... | [
"def",
"add_label",
"(",
"self",
",",
"name",
",",
"color",
")",
":",
"color_upper",
"=",
"color",
".",
"upper",
"(",
")",
"if",
"not",
"self",
".",
"_color_re",
".",
"match",
"(",
"color_upper",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid color: {}'... | Add a new label. It's id will automatically be calculated. | [
"Add",
"a",
"new",
"label",
".",
"It",
"s",
"id",
"will",
"automatically",
"be",
"calculated",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L417-L430 | train |
pokerregion/poker | poker/room/pokerstars.py | Notes.del_label | def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name)) | python | def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name)) | [
"def",
"del_label",
"(",
"self",
",",
"name",
")",
":",
"labels_tag",
"=",
"self",
".",
"root",
"[",
"0",
"]",
"labels_tag",
".",
"remove",
"(",
"self",
".",
"_find_label",
"(",
"name",
")",
")"
] | Delete a label by name. | [
"Delete",
"a",
"label",
"by",
"name",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L432-L435 | train |
pokerregion/poker | poker/room/pokerstars.py | Notes.save | def save(self, filename):
"""Save the note XML to a file."""
with open(filename, 'w') as fp:
fp.write(str(self)) | python | def save(self, filename):
"""Save the note XML to a file."""
with open(filename, 'w') as fp:
fp.write(str(self)) | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"str",
"(",
"self",
")",
")"
] | Save the note XML to a file. | [
"Save",
"the",
"note",
"XML",
"to",
"a",
"file",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L447-L450 | train |
pokerregion/poker | poker/handhistory.py | _BaseHandHistory.board | def board(self):
"""Calculates board from flop, turn and river."""
board = []
if self.flop:
board.extend(self.flop.cards)
if self.turn:
board.append(self.turn)
if self.river:
board.append(self.river)
return tuple... | python | def board(self):
"""Calculates board from flop, turn and river."""
board = []
if self.flop:
board.extend(self.flop.cards)
if self.turn:
board.append(self.turn)
if self.river:
board.append(self.river)
return tuple... | [
"def",
"board",
"(",
"self",
")",
":",
"board",
"=",
"[",
"]",
"if",
"self",
".",
"flop",
":",
"board",
".",
"extend",
"(",
"self",
".",
"flop",
".",
"cards",
")",
"if",
"self",
".",
"turn",
":",
"board",
".",
"append",
"(",
"self",
".",
"turn"... | Calculates board from flop, turn and river. | [
"Calculates",
"board",
"from",
"flop",
"turn",
"and",
"river",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/handhistory.py#L167-L176 | train |
pokerregion/poker | poker/handhistory.py | _BaseHandHistory._parse_date | def _parse_date(self, date_string):
"""Parse the date_string and return a datetime object as UTC."""
date = datetime.strptime(date_string, self._DATE_FORMAT)
self.date = self._TZ.localize(date).astimezone(pytz.UTC) | python | def _parse_date(self, date_string):
"""Parse the date_string and return a datetime object as UTC."""
date = datetime.strptime(date_string, self._DATE_FORMAT)
self.date = self._TZ.localize(date).astimezone(pytz.UTC) | [
"def",
"_parse_date",
"(",
"self",
",",
"date_string",
")",
":",
"date",
"=",
"datetime",
".",
"strptime",
"(",
"date_string",
",",
"self",
".",
"_DATE_FORMAT",
")",
"self",
".",
"date",
"=",
"self",
".",
"_TZ",
".",
"localize",
"(",
"date",
")",
".",
... | Parse the date_string and return a datetime object as UTC. | [
"Parse",
"the",
"date_string",
"and",
"return",
"a",
"datetime",
"object",
"as",
"UTC",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/handhistory.py#L178-L181 | train |
pokerregion/poker | poker/handhistory.py | _SplittableHandHistoryMixin._split_raw | def _split_raw(self):
"""Split hand history by sections."""
self._splitted = self._split_re.split(self.raw)
# search split locations (basically empty strings)
self._sections = [ind for ind, elem in enumerate(self._splitted) if not elem] | python | def _split_raw(self):
"""Split hand history by sections."""
self._splitted = self._split_re.split(self.raw)
# search split locations (basically empty strings)
self._sections = [ind for ind, elem in enumerate(self._splitted) if not elem] | [
"def",
"_split_raw",
"(",
"self",
")",
":",
"self",
".",
"_splitted",
"=",
"self",
".",
"_split_re",
".",
"split",
"(",
"self",
".",
"raw",
")",
"self",
".",
"_sections",
"=",
"[",
"ind",
"for",
"ind",
",",
"elem",
"in",
"enumerate",
"(",
"self",
"... | Split hand history by sections. | [
"Split",
"hand",
"history",
"by",
"sections",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/handhistory.py#L201-L206 | train |
pokerregion/poker | poker/website/twoplustwo.py | ForumMember._get_timezone | def _get_timezone(self, root):
"""Find timezone informatation on bottom of the page."""
tz_str = root.xpath('//div[@class="smallfont" and @align="center"]')[0].text
hours = int(self._tz_re.search(tz_str).group(1))
return tzoffset(tz_str, hours * 60) | python | def _get_timezone(self, root):
"""Find timezone informatation on bottom of the page."""
tz_str = root.xpath('//div[@class="smallfont" and @align="center"]')[0].text
hours = int(self._tz_re.search(tz_str).group(1))
return tzoffset(tz_str, hours * 60) | [
"def",
"_get_timezone",
"(",
"self",
",",
"root",
")",
":",
"tz_str",
"=",
"root",
".",
"xpath",
"(",
"'//div[@class=\"smallfont\" and @align=\"center\"]'",
")",
"[",
"0",
"]",
".",
"text",
"hours",
"=",
"int",
"(",
"self",
".",
"_tz_re",
".",
"search",
"(... | Find timezone informatation on bottom of the page. | [
"Find",
"timezone",
"informatation",
"on",
"bottom",
"of",
"the",
"page",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/website/twoplustwo.py#L125-L129 | train |
pokerregion/poker | poker/website/pokerstars.py | get_current_tournaments | def get_current_tournaments():
"""Get the next 200 tournaments from pokerstars."""
schedule_page = requests.get(TOURNAMENTS_XML_URL)
root = etree.XML(schedule_page.content)
for tour in root.iter('{*}tournament'):
yield _Tournament(
start_date=tour.findtext('{*}start_date'),
... | python | def get_current_tournaments():
"""Get the next 200 tournaments from pokerstars."""
schedule_page = requests.get(TOURNAMENTS_XML_URL)
root = etree.XML(schedule_page.content)
for tour in root.iter('{*}tournament'):
yield _Tournament(
start_date=tour.findtext('{*}start_date'),
... | [
"def",
"get_current_tournaments",
"(",
")",
":",
"schedule_page",
"=",
"requests",
".",
"get",
"(",
"TOURNAMENTS_XML_URL",
")",
"root",
"=",
"etree",
".",
"XML",
"(",
"schedule_page",
".",
"content",
")",
"for",
"tour",
"in",
"root",
".",
"iter",
"(",
"'{*... | Get the next 200 tournaments from pokerstars. | [
"Get",
"the",
"next",
"200",
"tournaments",
"from",
"pokerstars",
"."
] | 2d8cf208fdf2b26bdc935972dcbe7a983a9e9768 | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/website/pokerstars.py#L29-L42 | train |
RKrahl/pytest-dependency | setup.py | _filter_file | def _filter_file(src, dest, subst):
"""Copy src to dest doing substitutions on the fly.
"""
substre = re.compile(r'\$(%s)' % '|'.join(subst.keys()))
def repl(m):
return subst[m.group(1)]
with open(src, "rt") as sf, open(dest, "wt") as df:
while True:
l = sf.readline()
... | python | def _filter_file(src, dest, subst):
"""Copy src to dest doing substitutions on the fly.
"""
substre = re.compile(r'\$(%s)' % '|'.join(subst.keys()))
def repl(m):
return subst[m.group(1)]
with open(src, "rt") as sf, open(dest, "wt") as df:
while True:
l = sf.readline()
... | [
"def",
"_filter_file",
"(",
"src",
",",
"dest",
",",
"subst",
")",
":",
"substre",
"=",
"re",
".",
"compile",
"(",
"r'\\$(%s)'",
"%",
"'|'",
".",
"join",
"(",
"subst",
".",
"keys",
"(",
")",
")",
")",
"def",
"repl",
"(",
"m",
")",
":",
"return",
... | Copy src to dest doing substitutions on the fly. | [
"Copy",
"src",
"to",
"dest",
"doing",
"substitutions",
"on",
"the",
"fly",
"."
] | 7b7c10818266ec4b05c36c341cf84f05d7ab53ce | https://github.com/RKrahl/pytest-dependency/blob/7b7c10818266ec4b05c36c341cf84f05d7ab53ce/setup.py#L18-L29 | train |
profusion/sgqlc | sgqlc/endpoint/base.py | BaseEndpoint._fixup_graphql_error | def _fixup_graphql_error(self, data):
'''Given a possible GraphQL error payload, make sure it's in shape.
This will ensure the given ``data`` is in the shape:
.. code-block:: json
{"errors": [{"message": "some string"}]}
If ``errors`` is not an array, it will be made into ... | python | def _fixup_graphql_error(self, data):
'''Given a possible GraphQL error payload, make sure it's in shape.
This will ensure the given ``data`` is in the shape:
.. code-block:: json
{"errors": [{"message": "some string"}]}
If ``errors`` is not an array, it will be made into ... | [
"def",
"_fixup_graphql_error",
"(",
"self",
",",
"data",
")",
":",
"original_data",
"=",
"data",
"errors",
"=",
"data",
".",
"get",
"(",
"'errors'",
")",
"original_errors",
"=",
"errors",
"if",
"not",
"isinstance",
"(",
"errors",
",",
"list",
")",
":",
"... | Given a possible GraphQL error payload, make sure it's in shape.
This will ensure the given ``data`` is in the shape:
.. code-block:: json
{"errors": [{"message": "some string"}]}
If ``errors`` is not an array, it will be made into a single element
array, with the object i... | [
"Given",
"a",
"possible",
"GraphQL",
"error",
"payload",
"make",
"sure",
"it",
"s",
"in",
"shape",
"."
] | 684afb059c93f142150043cafac09b7fd52bfa27 | https://github.com/profusion/sgqlc/blob/684afb059c93f142150043cafac09b7fd52bfa27/sgqlc/endpoint/base.py#L104-L163 | train |
profusion/sgqlc | sgqlc/endpoint/base.py | BaseEndpoint.snippet | def snippet(code, locations, sep=' | ', colmark=('-', '^'), context=5):
'''Given a code and list of locations, convert to snippet lines.
return will include line number, a separator (``sep``), then
line contents.
At most ``context`` lines are shown before each location line.
A... | python | def snippet(code, locations, sep=' | ', colmark=('-', '^'), context=5):
'''Given a code and list of locations, convert to snippet lines.
return will include line number, a separator (``sep``), then
line contents.
At most ``context`` lines are shown before each location line.
A... | [
"def",
"snippet",
"(",
"code",
",",
"locations",
",",
"sep",
"=",
"' | '",
",",
"colmark",
"=",
"(",
"'-'",
",",
"'^'",
")",
",",
"context",
"=",
"5",
")",
":",
"if",
"not",
"locations",
":",
"return",
"[",
"]",
"lines",
"=",
"code",
".",
"split"... | Given a code and list of locations, convert to snippet lines.
return will include line number, a separator (``sep``), then
line contents.
At most ``context`` lines are shown before each location line.
After each location line, the column is marked using
``colmark``. The first ... | [
"Given",
"a",
"code",
"and",
"list",
"of",
"locations",
"convert",
"to",
"snippet",
"lines",
"."
] | 684afb059c93f142150043cafac09b7fd52bfa27 | https://github.com/profusion/sgqlc/blob/684afb059c93f142150043cafac09b7fd52bfa27/sgqlc/endpoint/base.py#L206-L236 | train |
profusion/sgqlc | sgqlc/types/__init__.py | _create_non_null_wrapper | def _create_non_null_wrapper(name, t):
'creates type wrapper for non-null of given type'
def __new__(cls, json_data, selection_list=None):
if json_data is None:
raise ValueError(name + ' received null value')
return t(json_data, selection_list)
def __to_graphql_input__(value, in... | python | def _create_non_null_wrapper(name, t):
'creates type wrapper for non-null of given type'
def __new__(cls, json_data, selection_list=None):
if json_data is None:
raise ValueError(name + ' received null value')
return t(json_data, selection_list)
def __to_graphql_input__(value, in... | [
"def",
"_create_non_null_wrapper",
"(",
"name",
",",
"t",
")",
":",
"'creates type wrapper for non-null of given type'",
"def",
"__new__",
"(",
"cls",
",",
"json_data",
",",
"selection_list",
"=",
"None",
")",
":",
"if",
"json_data",
"is",
"None",
":",
"raise",
... | creates type wrapper for non-null of given type | [
"creates",
"type",
"wrapper",
"for",
"non",
"-",
"null",
"of",
"given",
"type"
] | 684afb059c93f142150043cafac09b7fd52bfa27 | https://github.com/profusion/sgqlc/blob/684afb059c93f142150043cafac09b7fd52bfa27/sgqlc/types/__init__.py#L869-L883 | train |
profusion/sgqlc | sgqlc/types/__init__.py | _create_list_of_wrapper | def _create_list_of_wrapper(name, t):
'creates type wrapper for list of given type'
def __new__(cls, json_data, selection_list=None):
if json_data is None:
return None
return [t(v, selection_list) for v in json_data]
def __to_graphql_input__(value, indent=0, indent_string=' '):... | python | def _create_list_of_wrapper(name, t):
'creates type wrapper for list of given type'
def __new__(cls, json_data, selection_list=None):
if json_data is None:
return None
return [t(v, selection_list) for v in json_data]
def __to_graphql_input__(value, indent=0, indent_string=' '):... | [
"def",
"_create_list_of_wrapper",
"(",
"name",
",",
"t",
")",
":",
"'creates type wrapper for list of given type'",
"def",
"__new__",
"(",
"cls",
",",
"json_data",
",",
"selection_list",
"=",
"None",
")",
":",
"if",
"json_data",
"is",
"None",
":",
"return",
"Non... | creates type wrapper for list of given type | [
"creates",
"type",
"wrapper",
"for",
"list",
"of",
"given",
"type"
] | 684afb059c93f142150043cafac09b7fd52bfa27 | https://github.com/profusion/sgqlc/blob/684afb059c93f142150043cafac09b7fd52bfa27/sgqlc/types/__init__.py#L886-L909 | train |
profusion/sgqlc | sgqlc/endpoint/http.py | add_query_to_url | def add_query_to_url(url, extra_query):
'''Adds an extra query to URL, returning the new URL.
Extra query may be a dict or a list as returned by
:func:`urllib.parse.parse_qsl()` and :func:`urllib.parse.parse_qs()`.
'''
split = urllib.parse.urlsplit(url)
merged_query = urllib.parse.parse_qsl(sp... | python | def add_query_to_url(url, extra_query):
'''Adds an extra query to URL, returning the new URL.
Extra query may be a dict or a list as returned by
:func:`urllib.parse.parse_qsl()` and :func:`urllib.parse.parse_qs()`.
'''
split = urllib.parse.urlsplit(url)
merged_query = urllib.parse.parse_qsl(sp... | [
"def",
"add_query_to_url",
"(",
"url",
",",
"extra_query",
")",
":",
"split",
"=",
"urllib",
".",
"parse",
".",
"urlsplit",
"(",
"url",
")",
"merged_query",
"=",
"urllib",
".",
"parse",
".",
"parse_qsl",
"(",
"split",
".",
"query",
")",
"if",
"isinstance... | Adds an extra query to URL, returning the new URL.
Extra query may be a dict or a list as returned by
:func:`urllib.parse.parse_qsl()` and :func:`urllib.parse.parse_qs()`. | [
"Adds",
"an",
"extra",
"query",
"to",
"URL",
"returning",
"the",
"new",
"URL",
"."
] | 684afb059c93f142150043cafac09b7fd52bfa27 | https://github.com/profusion/sgqlc/blob/684afb059c93f142150043cafac09b7fd52bfa27/sgqlc/endpoint/http.py#L33-L59 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.